PackageManagerService.java revision f8579581c1d6bf993f26d21aefca410ac9b6706b
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.READ_EXTERNAL_STORAGE;
22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
24import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
30import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
38import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
39import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
40import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
41import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
48import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
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_OPERATION_PENDING;
81import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
82import static android.content.pm.PackageManager.PERMISSION_DENIED;
83import static android.content.pm.PackageManager.PERMISSION_GRANTED;
84import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
85import static android.content.pm.PackageParser.isApkFile;
86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
87import static android.system.OsConstants.O_CREAT;
88import static android.system.OsConstants.O_RDWR;
89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
90import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
91import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
92import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
93import static com.android.internal.util.ArrayUtils.appendInt;
94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
104import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
105
106import android.Manifest;
107import android.annotation.IntDef;
108import android.annotation.NonNull;
109import android.annotation.Nullable;
110import android.app.ActivityManager;
111import android.app.AppOpsManager;
112import android.app.IActivityManager;
113import android.app.ResourcesManager;
114import android.app.admin.IDevicePolicyManager;
115import android.app.admin.SecurityLog;
116import android.app.backup.IBackupManager;
117import android.content.BroadcastReceiver;
118import android.content.ComponentName;
119import android.content.ContentResolver;
120import android.content.Context;
121import android.content.IIntentReceiver;
122import android.content.Intent;
123import android.content.IntentFilter;
124import android.content.IntentSender;
125import android.content.IntentSender.SendIntentException;
126import android.content.ServiceConnection;
127import android.content.pm.ActivityInfo;
128import android.content.pm.ApplicationInfo;
129import android.content.pm.AppsQueryHelper;
130import android.content.pm.AuxiliaryResolveInfo;
131import android.content.pm.ChangedPackages;
132import android.content.pm.FallbackCategoryProvider;
133import android.content.pm.FeatureInfo;
134import android.content.pm.IOnPermissionsChangeListener;
135import android.content.pm.IPackageDataObserver;
136import android.content.pm.IPackageDeleteObserver;
137import android.content.pm.IPackageDeleteObserver2;
138import android.content.pm.IPackageInstallObserver2;
139import android.content.pm.IPackageInstaller;
140import android.content.pm.IPackageManager;
141import android.content.pm.IPackageMoveObserver;
142import android.content.pm.IPackageStatsObserver;
143import android.content.pm.InstantAppInfo;
144import android.content.pm.InstantAppRequest;
145import android.content.pm.InstantAppResolveInfo;
146import android.content.pm.InstrumentationInfo;
147import android.content.pm.IntentFilterVerificationInfo;
148import android.content.pm.KeySet;
149import android.content.pm.PackageCleanItem;
150import android.content.pm.PackageInfo;
151import android.content.pm.PackageInfoLite;
152import android.content.pm.PackageInstaller;
153import android.content.pm.PackageManager;
154import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
155import android.content.pm.PackageManagerInternal;
156import android.content.pm.PackageParser;
157import android.content.pm.PackageParser.ActivityIntentInfo;
158import android.content.pm.PackageParser.PackageLite;
159import android.content.pm.PackageParser.PackageParserException;
160import android.content.pm.PackageStats;
161import android.content.pm.PackageUserState;
162import android.content.pm.ParceledListSlice;
163import android.content.pm.PermissionGroupInfo;
164import android.content.pm.PermissionInfo;
165import android.content.pm.ProviderInfo;
166import android.content.pm.ResolveInfo;
167import android.content.pm.ServiceInfo;
168import android.content.pm.SharedLibraryInfo;
169import android.content.pm.Signature;
170import android.content.pm.UserInfo;
171import android.content.pm.VerifierDeviceIdentity;
172import android.content.pm.VerifierInfo;
173import android.content.pm.VersionedPackage;
174import android.content.res.Resources;
175import android.database.ContentObserver;
176import android.graphics.Bitmap;
177import android.hardware.display.DisplayManager;
178import android.net.Uri;
179import android.os.Binder;
180import android.os.Build;
181import android.os.Bundle;
182import android.os.Debug;
183import android.os.Environment;
184import android.os.Environment.UserEnvironment;
185import android.os.FileUtils;
186import android.os.Handler;
187import android.os.IBinder;
188import android.os.Looper;
189import android.os.Message;
190import android.os.Parcel;
191import android.os.ParcelFileDescriptor;
192import android.os.PatternMatcher;
193import android.os.Process;
194import android.os.RemoteCallbackList;
195import android.os.RemoteException;
196import android.os.ResultReceiver;
197import android.os.SELinux;
198import android.os.ServiceManager;
199import android.os.ShellCallback;
200import android.os.SystemClock;
201import android.os.SystemProperties;
202import android.os.Trace;
203import android.os.UserHandle;
204import android.os.UserManager;
205import android.os.UserManagerInternal;
206import android.os.storage.IStorageManager;
207import android.os.storage.StorageEventListener;
208import android.os.storage.StorageManager;
209import android.os.storage.StorageManagerInternal;
210import android.os.storage.VolumeInfo;
211import android.os.storage.VolumeRecord;
212import android.provider.Settings.Global;
213import android.provider.Settings.Secure;
214import android.security.KeyStore;
215import android.security.SystemKeyStore;
216import android.service.pm.PackageServiceDumpProto;
217import android.system.ErrnoException;
218import android.system.Os;
219import android.text.TextUtils;
220import android.text.format.DateUtils;
221import android.util.ArrayMap;
222import android.util.ArraySet;
223import android.util.Base64;
224import android.util.BootTimingsTraceLog;
225import android.util.DisplayMetrics;
226import android.util.EventLog;
227import android.util.ExceptionUtils;
228import android.util.Log;
229import android.util.LogPrinter;
230import android.util.MathUtils;
231import android.util.PackageUtils;
232import android.util.Pair;
233import android.util.PrintStreamPrinter;
234import android.util.Slog;
235import android.util.SparseArray;
236import android.util.SparseBooleanArray;
237import android.util.SparseIntArray;
238import android.util.Xml;
239import android.util.jar.StrictJarFile;
240import android.util.proto.ProtoOutputStream;
241import android.view.Display;
242
243import com.android.internal.R;
244import com.android.internal.annotations.GuardedBy;
245import com.android.internal.app.IMediaContainerService;
246import com.android.internal.app.ResolverActivity;
247import com.android.internal.content.NativeLibraryHelper;
248import com.android.internal.content.PackageHelper;
249import com.android.internal.logging.MetricsLogger;
250import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
251import com.android.internal.os.IParcelFileDescriptorFactory;
252import com.android.internal.os.RoSystemProperties;
253import com.android.internal.os.SomeArgs;
254import com.android.internal.os.Zygote;
255import com.android.internal.telephony.CarrierAppUtils;
256import com.android.internal.util.ArrayUtils;
257import com.android.internal.util.ConcurrentUtils;
258import com.android.internal.util.DumpUtils;
259import com.android.internal.util.FastPrintWriter;
260import com.android.internal.util.FastXmlSerializer;
261import com.android.internal.util.IndentingPrintWriter;
262import com.android.internal.util.Preconditions;
263import com.android.internal.util.XmlUtils;
264import com.android.server.AttributeCache;
265import com.android.server.DeviceIdleController;
266import com.android.server.EventLogTags;
267import com.android.server.FgThread;
268import com.android.server.IntentResolver;
269import com.android.server.LocalServices;
270import com.android.server.LockGuard;
271import com.android.server.ServiceThread;
272import com.android.server.SystemConfig;
273import com.android.server.SystemServerInitThreadPool;
274import com.android.server.Watchdog;
275import com.android.server.net.NetworkPolicyManagerInternal;
276import com.android.server.pm.Installer.InstallerException;
277import com.android.server.pm.PermissionsState.PermissionState;
278import com.android.server.pm.Settings.DatabaseVersion;
279import com.android.server.pm.Settings.VersionInfo;
280import com.android.server.pm.dex.DexManager;
281import com.android.server.storage.DeviceStorageMonitorInternal;
282
283import dalvik.system.CloseGuard;
284import dalvik.system.DexFile;
285import dalvik.system.VMRuntime;
286
287import libcore.io.IoUtils;
288import libcore.util.EmptyArray;
289
290import org.xmlpull.v1.XmlPullParser;
291import org.xmlpull.v1.XmlPullParserException;
292import org.xmlpull.v1.XmlSerializer;
293
294import java.io.BufferedOutputStream;
295import java.io.BufferedReader;
296import java.io.ByteArrayInputStream;
297import java.io.ByteArrayOutputStream;
298import java.io.File;
299import java.io.FileDescriptor;
300import java.io.FileInputStream;
301import java.io.FileOutputStream;
302import java.io.FileReader;
303import java.io.FilenameFilter;
304import java.io.IOException;
305import java.io.PrintWriter;
306import java.lang.annotation.Retention;
307import java.lang.annotation.RetentionPolicy;
308import java.nio.charset.StandardCharsets;
309import java.security.DigestInputStream;
310import java.security.MessageDigest;
311import java.security.NoSuchAlgorithmException;
312import java.security.PublicKey;
313import java.security.SecureRandom;
314import java.security.cert.Certificate;
315import java.security.cert.CertificateEncodingException;
316import java.security.cert.CertificateException;
317import java.text.SimpleDateFormat;
318import java.util.ArrayList;
319import java.util.Arrays;
320import java.util.Collection;
321import java.util.Collections;
322import java.util.Comparator;
323import java.util.Date;
324import java.util.HashMap;
325import java.util.HashSet;
326import java.util.Iterator;
327import java.util.List;
328import java.util.Map;
329import java.util.Objects;
330import java.util.Set;
331import java.util.concurrent.CountDownLatch;
332import java.util.concurrent.Future;
333import java.util.concurrent.TimeUnit;
334import java.util.concurrent.atomic.AtomicBoolean;
335import java.util.concurrent.atomic.AtomicInteger;
336
337/**
338 * Keep track of all those APKs everywhere.
339 * <p>
340 * Internally there are two important locks:
341 * <ul>
342 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
343 * and other related state. It is a fine-grained lock that should only be held
344 * momentarily, as it's one of the most contended locks in the system.
345 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
346 * operations typically involve heavy lifting of application data on disk. Since
347 * {@code installd} is single-threaded, and it's operations can often be slow,
348 * this lock should never be acquired while already holding {@link #mPackages}.
349 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
350 * holding {@link #mInstallLock}.
351 * </ul>
352 * Many internal methods rely on the caller to hold the appropriate locks, and
353 * this contract is expressed through method name suffixes:
354 * <ul>
355 * <li>fooLI(): the caller must hold {@link #mInstallLock}
356 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
357 * being modified must be frozen
358 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
359 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
360 * </ul>
361 * <p>
362 * Because this class is very central to the platform's security; please run all
363 * CTS and unit tests whenever making modifications:
364 *
365 * <pre>
366 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
367 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
368 * </pre>
369 */
370public class PackageManagerService extends IPackageManager.Stub
371        implements PackageSender {
372    static final String TAG = "PackageManager";
373    static final boolean DEBUG_SETTINGS = false;
374    static final boolean DEBUG_PREFERRED = false;
375    static final boolean DEBUG_UPGRADE = false;
376    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
377    private static final boolean DEBUG_BACKUP = false;
378    private static final boolean DEBUG_INSTALL = false;
379    private static final boolean DEBUG_REMOVE = false;
380    private static final boolean DEBUG_BROADCASTS = false;
381    private static final boolean DEBUG_SHOW_INFO = false;
382    private static final boolean DEBUG_PACKAGE_INFO = false;
383    private static final boolean DEBUG_INTENT_MATCHING = false;
384    private static final boolean DEBUG_PACKAGE_SCANNING = false;
385    private static final boolean DEBUG_VERIFY = false;
386    private static final boolean DEBUG_FILTERS = false;
387    private static final boolean DEBUG_PERMISSIONS = false;
388    private static final boolean DEBUG_SHARED_LIBRARIES = false;
389
390    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
391    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
392    // user, but by default initialize to this.
393    public static final boolean DEBUG_DEXOPT = false;
394
395    private static final boolean DEBUG_ABI_SELECTION = false;
396    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
397    private static final boolean DEBUG_TRIAGED_MISSING = false;
398    private static final boolean DEBUG_APP_DATA = false;
399
400    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
401    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
402
403    private static final boolean HIDE_EPHEMERAL_APIS = false;
404
405    private static final boolean ENABLE_FREE_CACHE_V2 =
406            SystemProperties.getBoolean("fw.free_cache_v2", true);
407
408    private static final int RADIO_UID = Process.PHONE_UID;
409    private static final int LOG_UID = Process.LOG_UID;
410    private static final int NFC_UID = Process.NFC_UID;
411    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
412    private static final int SHELL_UID = Process.SHELL_UID;
413
414    // Cap the size of permission trees that 3rd party apps can define
415    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
416
417    // Suffix used during package installation when copying/moving
418    // package apks to install directory.
419    private static final String INSTALL_PACKAGE_SUFFIX = "-";
420
421    static final int SCAN_NO_DEX = 1<<1;
422    static final int SCAN_FORCE_DEX = 1<<2;
423    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
424    static final int SCAN_NEW_INSTALL = 1<<4;
425    static final int SCAN_UPDATE_TIME = 1<<5;
426    static final int SCAN_BOOTING = 1<<6;
427    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
428    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
429    static final int SCAN_REPLACING = 1<<9;
430    static final int SCAN_REQUIRE_KNOWN = 1<<10;
431    static final int SCAN_MOVE = 1<<11;
432    static final int SCAN_INITIAL = 1<<12;
433    static final int SCAN_CHECK_ONLY = 1<<13;
434    static final int SCAN_DONT_KILL_APP = 1<<14;
435    static final int SCAN_IGNORE_FROZEN = 1<<15;
436    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
437    static final int SCAN_AS_INSTANT_APP = 1<<17;
438    static final int SCAN_AS_FULL_APP = 1<<18;
439    /** Should not be with the scan flags */
440    static final int FLAGS_REMOVE_CHATTY = 1<<31;
441
442    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
443
444    private static final int[] EMPTY_INT_ARRAY = new int[0];
445
446    private static final int TYPE_UNKNOWN = 0;
447    private static final int TYPE_ACTIVITY = 1;
448    private static final int TYPE_RECEIVER = 2;
449    private static final int TYPE_SERVICE = 3;
450    private static final int TYPE_PROVIDER = 4;
451    @IntDef(prefix = { "TYPE_" }, value = {
452            TYPE_UNKNOWN,
453            TYPE_ACTIVITY,
454            TYPE_RECEIVER,
455            TYPE_SERVICE,
456            TYPE_PROVIDER,
457    })
458    @Retention(RetentionPolicy.SOURCE)
459    public @interface ComponentType {}
460
461    /**
462     * Timeout (in milliseconds) after which the watchdog should declare that
463     * our handler thread is wedged.  The usual default for such things is one
464     * minute but we sometimes do very lengthy I/O operations on this thread,
465     * such as installing multi-gigabyte applications, so ours needs to be longer.
466     */
467    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
468
469    /**
470     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
471     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
472     * settings entry if available, otherwise we use the hardcoded default.  If it's been
473     * more than this long since the last fstrim, we force one during the boot sequence.
474     *
475     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
476     * one gets run at the next available charging+idle time.  This final mandatory
477     * no-fstrim check kicks in only of the other scheduling criteria is never met.
478     */
479    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
480
481    /**
482     * Whether verification is enabled by default.
483     */
484    private static final boolean DEFAULT_VERIFY_ENABLE = true;
485
486    /**
487     * The default maximum time to wait for the verification agent to return in
488     * milliseconds.
489     */
490    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
491
492    /**
493     * The default response for package verification timeout.
494     *
495     * This can be either PackageManager.VERIFICATION_ALLOW or
496     * PackageManager.VERIFICATION_REJECT.
497     */
498    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
499
500    static final String PLATFORM_PACKAGE_NAME = "android";
501
502    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
503
504    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
505            DEFAULT_CONTAINER_PACKAGE,
506            "com.android.defcontainer.DefaultContainerService");
507
508    private static final String KILL_APP_REASON_GIDS_CHANGED =
509            "permission grant or revoke changed gids";
510
511    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
512            "permissions revoked";
513
514    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
515
516    private static final String PACKAGE_SCHEME = "package";
517
518    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
519
520    /** Permission grant: not grant the permission. */
521    private static final int GRANT_DENIED = 1;
522
523    /** Permission grant: grant the permission as an install permission. */
524    private static final int GRANT_INSTALL = 2;
525
526    /** Permission grant: grant the permission as a runtime one. */
527    private static final int GRANT_RUNTIME = 3;
528
529    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
530    private static final int GRANT_UPGRADE = 4;
531
532    /** Canonical intent used to identify what counts as a "web browser" app */
533    private static final Intent sBrowserIntent;
534    static {
535        sBrowserIntent = new Intent();
536        sBrowserIntent.setAction(Intent.ACTION_VIEW);
537        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
538        sBrowserIntent.setData(Uri.parse("http:"));
539    }
540
541    /**
542     * The set of all protected actions [i.e. those actions for which a high priority
543     * intent filter is disallowed].
544     */
545    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
546    static {
547        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
548        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
549        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
550        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
551    }
552
553    // Compilation reasons.
554    public static final int REASON_FIRST_BOOT = 0;
555    public static final int REASON_BOOT = 1;
556    public static final int REASON_INSTALL = 2;
557    public static final int REASON_BACKGROUND_DEXOPT = 3;
558    public static final int REASON_AB_OTA = 4;
559
560    public static final int REASON_LAST = REASON_AB_OTA;
561
562    /** All dangerous permission names in the same order as the events in MetricsEvent */
563    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
564            Manifest.permission.READ_CALENDAR,
565            Manifest.permission.WRITE_CALENDAR,
566            Manifest.permission.CAMERA,
567            Manifest.permission.READ_CONTACTS,
568            Manifest.permission.WRITE_CONTACTS,
569            Manifest.permission.GET_ACCOUNTS,
570            Manifest.permission.ACCESS_FINE_LOCATION,
571            Manifest.permission.ACCESS_COARSE_LOCATION,
572            Manifest.permission.RECORD_AUDIO,
573            Manifest.permission.READ_PHONE_STATE,
574            Manifest.permission.CALL_PHONE,
575            Manifest.permission.READ_CALL_LOG,
576            Manifest.permission.WRITE_CALL_LOG,
577            Manifest.permission.ADD_VOICEMAIL,
578            Manifest.permission.USE_SIP,
579            Manifest.permission.PROCESS_OUTGOING_CALLS,
580            Manifest.permission.READ_CELL_BROADCASTS,
581            Manifest.permission.BODY_SENSORS,
582            Manifest.permission.SEND_SMS,
583            Manifest.permission.RECEIVE_SMS,
584            Manifest.permission.READ_SMS,
585            Manifest.permission.RECEIVE_WAP_PUSH,
586            Manifest.permission.RECEIVE_MMS,
587            Manifest.permission.READ_EXTERNAL_STORAGE,
588            Manifest.permission.WRITE_EXTERNAL_STORAGE,
589            Manifest.permission.READ_PHONE_NUMBERS,
590            Manifest.permission.ANSWER_PHONE_CALLS);
591
592
593    /**
594     * Version number for the package parser cache. Increment this whenever the format or
595     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
596     */
597    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
598
599    /**
600     * Whether the package parser cache is enabled.
601     */
602    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
603
604    final ServiceThread mHandlerThread;
605
606    final PackageHandler mHandler;
607
608    private final ProcessLoggingHandler mProcessLoggingHandler;
609
610    /**
611     * Messages for {@link #mHandler} that need to wait for system ready before
612     * being dispatched.
613     */
614    private ArrayList<Message> mPostSystemReadyMessages;
615
616    final int mSdkVersion = Build.VERSION.SDK_INT;
617
618    final Context mContext;
619    final boolean mFactoryTest;
620    final boolean mOnlyCore;
621    final DisplayMetrics mMetrics;
622    final int mDefParseFlags;
623    final String[] mSeparateProcesses;
624    final boolean mIsUpgrade;
625    final boolean mIsPreNUpgrade;
626    final boolean mIsPreNMR1Upgrade;
627
628    // Have we told the Activity Manager to whitelist the default container service by uid yet?
629    @GuardedBy("mPackages")
630    boolean mDefaultContainerWhitelisted = false;
631
632    @GuardedBy("mPackages")
633    private boolean mDexOptDialogShown;
634
635    /** The location for ASEC container files on internal storage. */
636    final String mAsecInternalPath;
637
638    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
639    // LOCK HELD.  Can be called with mInstallLock held.
640    @GuardedBy("mInstallLock")
641    final Installer mInstaller;
642
643    /** Directory where installed third-party apps stored */
644    final File mAppInstallDir;
645
646    /**
647     * Directory to which applications installed internally have their
648     * 32 bit native libraries copied.
649     */
650    private File mAppLib32InstallDir;
651
652    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
653    // apps.
654    final File mDrmAppPrivateInstallDir;
655
656    // ----------------------------------------------------------------
657
658    // Lock for state used when installing and doing other long running
659    // operations.  Methods that must be called with this lock held have
660    // the suffix "LI".
661    final Object mInstallLock = new Object();
662
663    // ----------------------------------------------------------------
664
665    // Keys are String (package name), values are Package.  This also serves
666    // as the lock for the global state.  Methods that must be called with
667    // this lock held have the prefix "LP".
668    @GuardedBy("mPackages")
669    final ArrayMap<String, PackageParser.Package> mPackages =
670            new ArrayMap<String, PackageParser.Package>();
671
672    final ArrayMap<String, Set<String>> mKnownCodebase =
673            new ArrayMap<String, Set<String>>();
674
675    // Keys are isolated uids and values are the uid of the application
676    // that created the isolated proccess.
677    @GuardedBy("mPackages")
678    final SparseIntArray mIsolatedOwners = new SparseIntArray();
679
680    /**
681     * Tracks new system packages [received in an OTA] that we expect to
682     * find updated user-installed versions. Keys are package name, values
683     * are package location.
684     */
685    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
686    /**
687     * Tracks high priority intent filters for protected actions. During boot, certain
688     * filter actions are protected and should never be allowed to have a high priority
689     * intent filter for them. However, there is one, and only one exception -- the
690     * setup wizard. It must be able to define a high priority intent filter for these
691     * actions to ensure there are no escapes from the wizard. We need to delay processing
692     * of these during boot as we need to look at all of the system packages in order
693     * to know which component is the setup wizard.
694     */
695    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
696    /**
697     * Whether or not processing protected filters should be deferred.
698     */
699    private boolean mDeferProtectedFilters = true;
700
701    /**
702     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
703     */
704    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
705    /**
706     * Whether or not system app permissions should be promoted from install to runtime.
707     */
708    boolean mPromoteSystemApps;
709
710    @GuardedBy("mPackages")
711    final Settings mSettings;
712
713    /**
714     * Set of package names that are currently "frozen", which means active
715     * surgery is being done on the code/data for that package. The platform
716     * will refuse to launch frozen packages to avoid race conditions.
717     *
718     * @see PackageFreezer
719     */
720    @GuardedBy("mPackages")
721    final ArraySet<String> mFrozenPackages = new ArraySet<>();
722
723    final ProtectedPackages mProtectedPackages;
724
725    boolean mFirstBoot;
726
727    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
728
729    // System configuration read by SystemConfig.
730    final int[] mGlobalGids;
731    final SparseArray<ArraySet<String>> mSystemPermissions;
732    @GuardedBy("mAvailableFeatures")
733    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
734
735    // If mac_permissions.xml was found for seinfo labeling.
736    boolean mFoundPolicyFile;
737
738    private final InstantAppRegistry mInstantAppRegistry;
739
740    @GuardedBy("mPackages")
741    int mChangedPackagesSequenceNumber;
742    /**
743     * List of changed [installed, removed or updated] packages.
744     * mapping from user id -> sequence number -> package name
745     */
746    @GuardedBy("mPackages")
747    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
748    /**
749     * The sequence number of the last change to a package.
750     * mapping from user id -> package name -> sequence number
751     */
752    @GuardedBy("mPackages")
753    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
754
755    class PackageParserCallback implements PackageParser.Callback {
756        @Override public final boolean hasFeature(String feature) {
757            return PackageManagerService.this.hasSystemFeature(feature, 0);
758        }
759
760        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
761                Collection<PackageParser.Package> allPackages, String targetPackageName) {
762            List<PackageParser.Package> overlayPackages = null;
763            for (PackageParser.Package p : allPackages) {
764                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
765                    if (overlayPackages == null) {
766                        overlayPackages = new ArrayList<PackageParser.Package>();
767                    }
768                    overlayPackages.add(p);
769                }
770            }
771            if (overlayPackages != null) {
772                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
773                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
774                        return p1.mOverlayPriority - p2.mOverlayPriority;
775                    }
776                };
777                Collections.sort(overlayPackages, cmp);
778            }
779            return overlayPackages;
780        }
781
782        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
783                String targetPackageName, String targetPath) {
784            if ("android".equals(targetPackageName)) {
785                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
786                // native AssetManager.
787                return null;
788            }
789            List<PackageParser.Package> overlayPackages =
790                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
791            if (overlayPackages == null || overlayPackages.isEmpty()) {
792                return null;
793            }
794            List<String> overlayPathList = null;
795            for (PackageParser.Package overlayPackage : overlayPackages) {
796                if (targetPath == null) {
797                    if (overlayPathList == null) {
798                        overlayPathList = new ArrayList<String>();
799                    }
800                    overlayPathList.add(overlayPackage.baseCodePath);
801                    continue;
802                }
803
804                try {
805                    // Creates idmaps for system to parse correctly the Android manifest of the
806                    // target package.
807                    //
808                    // OverlayManagerService will update each of them with a correct gid from its
809                    // target package app id.
810                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
811                            UserHandle.getSharedAppGid(
812                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
813                    if (overlayPathList == null) {
814                        overlayPathList = new ArrayList<String>();
815                    }
816                    overlayPathList.add(overlayPackage.baseCodePath);
817                } catch (InstallerException e) {
818                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
819                            overlayPackage.baseCodePath);
820                }
821            }
822            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
823        }
824
825        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
826            synchronized (mPackages) {
827                return getStaticOverlayPathsLocked(
828                        mPackages.values(), targetPackageName, targetPath);
829            }
830        }
831
832        @Override public final String[] getOverlayApks(String targetPackageName) {
833            return getStaticOverlayPaths(targetPackageName, null);
834        }
835
836        @Override public final String[] getOverlayPaths(String targetPackageName,
837                String targetPath) {
838            return getStaticOverlayPaths(targetPackageName, targetPath);
839        }
840    };
841
842    class ParallelPackageParserCallback extends PackageParserCallback {
843        List<PackageParser.Package> mOverlayPackages = null;
844
845        void findStaticOverlayPackages() {
846            synchronized (mPackages) {
847                for (PackageParser.Package p : mPackages.values()) {
848                    if (p.mIsStaticOverlay) {
849                        if (mOverlayPackages == null) {
850                            mOverlayPackages = new ArrayList<PackageParser.Package>();
851                        }
852                        mOverlayPackages.add(p);
853                    }
854                }
855            }
856        }
857
858        @Override
859        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
860            // We can trust mOverlayPackages without holding mPackages because package uninstall
861            // can't happen while running parallel parsing.
862            // Moreover holding mPackages on each parsing thread causes dead-lock.
863            return mOverlayPackages == null ? null :
864                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
865        }
866    }
867
868    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
869    final ParallelPackageParserCallback mParallelPackageParserCallback =
870            new ParallelPackageParserCallback();
871
872    public static final class SharedLibraryEntry {
873        public final @Nullable String path;
874        public final @Nullable String apk;
875        public final @NonNull SharedLibraryInfo info;
876
877        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
878                String declaringPackageName, int declaringPackageVersionCode) {
879            path = _path;
880            apk = _apk;
881            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
882                    declaringPackageName, declaringPackageVersionCode), null);
883        }
884    }
885
886    // Currently known shared libraries.
887    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
888    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
889            new ArrayMap<>();
890
891    // All available activities, for your resolving pleasure.
892    final ActivityIntentResolver mActivities =
893            new ActivityIntentResolver();
894
895    // All available receivers, for your resolving pleasure.
896    final ActivityIntentResolver mReceivers =
897            new ActivityIntentResolver();
898
899    // All available services, for your resolving pleasure.
900    final ServiceIntentResolver mServices = new ServiceIntentResolver();
901
902    // All available providers, for your resolving pleasure.
903    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
904
905    // Mapping from provider base names (first directory in content URI codePath)
906    // to the provider information.
907    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
908            new ArrayMap<String, PackageParser.Provider>();
909
910    // Mapping from instrumentation class names to info about them.
911    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
912            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
913
914    // Mapping from permission names to info about them.
915    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
916            new ArrayMap<String, PackageParser.PermissionGroup>();
917
918    // Packages whose data we have transfered into another package, thus
919    // should no longer exist.
920    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
921
922    // Broadcast actions that are only available to the system.
923    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
924
925    /** List of packages waiting for verification. */
926    final SparseArray<PackageVerificationState> mPendingVerification
927            = new SparseArray<PackageVerificationState>();
928
929    /** Set of packages associated with each app op permission. */
930    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
931
932    final PackageInstallerService mInstallerService;
933
934    private final PackageDexOptimizer mPackageDexOptimizer;
935    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
936    // is used by other apps).
937    private final DexManager mDexManager;
938
939    private AtomicInteger mNextMoveId = new AtomicInteger();
940    private final MoveCallbacks mMoveCallbacks;
941
942    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
943
944    // Cache of users who need badging.
945    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
946
947    /** Token for keys in mPendingVerification. */
948    private int mPendingVerificationToken = 0;
949
950    volatile boolean mSystemReady;
951    volatile boolean mSafeMode;
952    volatile boolean mHasSystemUidErrors;
953    private volatile boolean mEphemeralAppsDisabled;
954
955    ApplicationInfo mAndroidApplication;
956    final ActivityInfo mResolveActivity = new ActivityInfo();
957    final ResolveInfo mResolveInfo = new ResolveInfo();
958    ComponentName mResolveComponentName;
959    PackageParser.Package mPlatformPackage;
960    ComponentName mCustomResolverComponentName;
961
962    boolean mResolverReplaced = false;
963
964    private final @Nullable ComponentName mIntentFilterVerifierComponent;
965    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
966
967    private int mIntentFilterVerificationToken = 0;
968
969    /** The service connection to the ephemeral resolver */
970    final EphemeralResolverConnection mInstantAppResolverConnection;
971    /** Component used to show resolver settings for Instant Apps */
972    final ComponentName mInstantAppResolverSettingsComponent;
973
974    /** Activity used to install instant applications */
975    ActivityInfo mInstantAppInstallerActivity;
976    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
977
978    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
979            = new SparseArray<IntentFilterVerificationState>();
980
981    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
982
983    // List of packages names to keep cached, even if they are uninstalled for all users
984    private List<String> mKeepUninstalledPackages;
985
986    private UserManagerInternal mUserManagerInternal;
987
988    private DeviceIdleController.LocalService mDeviceIdleController;
989
990    private File mCacheDir;
991
992    private ArraySet<String> mPrivappPermissionsViolations;
993
994    private Future<?> mPrepareAppDataFuture;
995
996    private static class IFVerificationParams {
997        PackageParser.Package pkg;
998        boolean replacing;
999        int userId;
1000        int verifierUid;
1001
1002        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1003                int _userId, int _verifierUid) {
1004            pkg = _pkg;
1005            replacing = _replacing;
1006            userId = _userId;
1007            replacing = _replacing;
1008            verifierUid = _verifierUid;
1009        }
1010    }
1011
1012    private interface IntentFilterVerifier<T extends IntentFilter> {
1013        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1014                                               T filter, String packageName);
1015        void startVerifications(int userId);
1016        void receiveVerificationResponse(int verificationId);
1017    }
1018
1019    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1020        private Context mContext;
1021        private ComponentName mIntentFilterVerifierComponent;
1022        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1023
1024        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1025            mContext = context;
1026            mIntentFilterVerifierComponent = verifierComponent;
1027        }
1028
1029        private String getDefaultScheme() {
1030            return IntentFilter.SCHEME_HTTPS;
1031        }
1032
1033        @Override
1034        public void startVerifications(int userId) {
1035            // Launch verifications requests
1036            int count = mCurrentIntentFilterVerifications.size();
1037            for (int n=0; n<count; n++) {
1038                int verificationId = mCurrentIntentFilterVerifications.get(n);
1039                final IntentFilterVerificationState ivs =
1040                        mIntentFilterVerificationStates.get(verificationId);
1041
1042                String packageName = ivs.getPackageName();
1043
1044                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1045                final int filterCount = filters.size();
1046                ArraySet<String> domainsSet = new ArraySet<>();
1047                for (int m=0; m<filterCount; m++) {
1048                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1049                    domainsSet.addAll(filter.getHostsList());
1050                }
1051                synchronized (mPackages) {
1052                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1053                            packageName, domainsSet) != null) {
1054                        scheduleWriteSettingsLocked();
1055                    }
1056                }
1057                sendVerificationRequest(userId, verificationId, ivs);
1058            }
1059            mCurrentIntentFilterVerifications.clear();
1060        }
1061
1062        private void sendVerificationRequest(int userId, int verificationId,
1063                IntentFilterVerificationState ivs) {
1064
1065            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1066            verificationIntent.putExtra(
1067                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1068                    verificationId);
1069            verificationIntent.putExtra(
1070                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1071                    getDefaultScheme());
1072            verificationIntent.putExtra(
1073                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1074                    ivs.getHostsString());
1075            verificationIntent.putExtra(
1076                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1077                    ivs.getPackageName());
1078            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1079            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1080
1081            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1082            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1083                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1084                    userId, false, "intent filter verifier");
1085
1086            UserHandle user = new UserHandle(userId);
1087            mContext.sendBroadcastAsUser(verificationIntent, user);
1088            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1089                    "Sending IntentFilter verification broadcast");
1090        }
1091
1092        public void receiveVerificationResponse(int verificationId) {
1093            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1094
1095            final boolean verified = ivs.isVerified();
1096
1097            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1098            final int count = filters.size();
1099            if (DEBUG_DOMAIN_VERIFICATION) {
1100                Slog.i(TAG, "Received verification response " + verificationId
1101                        + " for " + count + " filters, verified=" + verified);
1102            }
1103            for (int n=0; n<count; n++) {
1104                PackageParser.ActivityIntentInfo filter = filters.get(n);
1105                filter.setVerified(verified);
1106
1107                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1108                        + " verified with result:" + verified + " and hosts:"
1109                        + ivs.getHostsString());
1110            }
1111
1112            mIntentFilterVerificationStates.remove(verificationId);
1113
1114            final String packageName = ivs.getPackageName();
1115            IntentFilterVerificationInfo ivi = null;
1116
1117            synchronized (mPackages) {
1118                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1119            }
1120            if (ivi == null) {
1121                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1122                        + verificationId + " packageName:" + packageName);
1123                return;
1124            }
1125            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1126                    "Updating IntentFilterVerificationInfo for package " + packageName
1127                            +" verificationId:" + verificationId);
1128
1129            synchronized (mPackages) {
1130                if (verified) {
1131                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1132                } else {
1133                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1134                }
1135                scheduleWriteSettingsLocked();
1136
1137                final int userId = ivs.getUserId();
1138                if (userId != UserHandle.USER_ALL) {
1139                    final int userStatus =
1140                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1141
1142                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1143                    boolean needUpdate = false;
1144
1145                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1146                    // already been set by the User thru the Disambiguation dialog
1147                    switch (userStatus) {
1148                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1149                            if (verified) {
1150                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1151                            } else {
1152                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1153                            }
1154                            needUpdate = true;
1155                            break;
1156
1157                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1158                            if (verified) {
1159                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1160                                needUpdate = true;
1161                            }
1162                            break;
1163
1164                        default:
1165                            // Nothing to do
1166                    }
1167
1168                    if (needUpdate) {
1169                        mSettings.updateIntentFilterVerificationStatusLPw(
1170                                packageName, updatedStatus, userId);
1171                        scheduleWritePackageRestrictionsLocked(userId);
1172                    }
1173                }
1174            }
1175        }
1176
1177        @Override
1178        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1179                    ActivityIntentInfo filter, String packageName) {
1180            if (!hasValidDomains(filter)) {
1181                return false;
1182            }
1183            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1184            if (ivs == null) {
1185                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1186                        packageName);
1187            }
1188            if (DEBUG_DOMAIN_VERIFICATION) {
1189                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1190            }
1191            ivs.addFilter(filter);
1192            return true;
1193        }
1194
1195        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1196                int userId, int verificationId, String packageName) {
1197            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1198                    verifierUid, userId, packageName);
1199            ivs.setPendingState();
1200            synchronized (mPackages) {
1201                mIntentFilterVerificationStates.append(verificationId, ivs);
1202                mCurrentIntentFilterVerifications.add(verificationId);
1203            }
1204            return ivs;
1205        }
1206    }
1207
1208    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1209        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1210                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1211                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1212    }
1213
1214    // Set of pending broadcasts for aggregating enable/disable of components.
1215    static class PendingPackageBroadcasts {
1216        // for each user id, a map of <package name -> components within that package>
1217        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1218
1219        public PendingPackageBroadcasts() {
1220            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1221        }
1222
1223        public ArrayList<String> get(int userId, String packageName) {
1224            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1225            return packages.get(packageName);
1226        }
1227
1228        public void put(int userId, String packageName, ArrayList<String> components) {
1229            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1230            packages.put(packageName, components);
1231        }
1232
1233        public void remove(int userId, String packageName) {
1234            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1235            if (packages != null) {
1236                packages.remove(packageName);
1237            }
1238        }
1239
1240        public void remove(int userId) {
1241            mUidMap.remove(userId);
1242        }
1243
1244        public int userIdCount() {
1245            return mUidMap.size();
1246        }
1247
1248        public int userIdAt(int n) {
1249            return mUidMap.keyAt(n);
1250        }
1251
1252        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1253            return mUidMap.get(userId);
1254        }
1255
1256        public int size() {
1257            // total number of pending broadcast entries across all userIds
1258            int num = 0;
1259            for (int i = 0; i< mUidMap.size(); i++) {
1260                num += mUidMap.valueAt(i).size();
1261            }
1262            return num;
1263        }
1264
1265        public void clear() {
1266            mUidMap.clear();
1267        }
1268
1269        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1270            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1271            if (map == null) {
1272                map = new ArrayMap<String, ArrayList<String>>();
1273                mUidMap.put(userId, map);
1274            }
1275            return map;
1276        }
1277    }
1278    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1279
1280    // Service Connection to remote media container service to copy
1281    // package uri's from external media onto secure containers
1282    // or internal storage.
1283    private IMediaContainerService mContainerService = null;
1284
1285    static final int SEND_PENDING_BROADCAST = 1;
1286    static final int MCS_BOUND = 3;
1287    static final int END_COPY = 4;
1288    static final int INIT_COPY = 5;
1289    static final int MCS_UNBIND = 6;
1290    static final int START_CLEANING_PACKAGE = 7;
1291    static final int FIND_INSTALL_LOC = 8;
1292    static final int POST_INSTALL = 9;
1293    static final int MCS_RECONNECT = 10;
1294    static final int MCS_GIVE_UP = 11;
1295    static final int UPDATED_MEDIA_STATUS = 12;
1296    static final int WRITE_SETTINGS = 13;
1297    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1298    static final int PACKAGE_VERIFIED = 15;
1299    static final int CHECK_PENDING_VERIFICATION = 16;
1300    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1301    static final int INTENT_FILTER_VERIFIED = 18;
1302    static final int WRITE_PACKAGE_LIST = 19;
1303    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1304
1305    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1306
1307    // Delay time in millisecs
1308    static final int BROADCAST_DELAY = 10 * 1000;
1309
1310    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1311            2 * 60 * 60 * 1000L; /* two hours */
1312
1313    static UserManagerService sUserManager;
1314
1315    // Stores a list of users whose package restrictions file needs to be updated
1316    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1317
1318    final private DefaultContainerConnection mDefContainerConn =
1319            new DefaultContainerConnection();
1320    class DefaultContainerConnection implements ServiceConnection {
1321        public void onServiceConnected(ComponentName name, IBinder service) {
1322            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1323            final IMediaContainerService imcs = IMediaContainerService.Stub
1324                    .asInterface(Binder.allowBlocking(service));
1325            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1326        }
1327
1328        public void onServiceDisconnected(ComponentName name) {
1329            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1330        }
1331    }
1332
1333    // Recordkeeping of restore-after-install operations that are currently in flight
1334    // between the Package Manager and the Backup Manager
1335    static class PostInstallData {
1336        public InstallArgs args;
1337        public PackageInstalledInfo res;
1338
1339        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1340            args = _a;
1341            res = _r;
1342        }
1343    }
1344
1345    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1346    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1347
1348    // XML tags for backup/restore of various bits of state
1349    private static final String TAG_PREFERRED_BACKUP = "pa";
1350    private static final String TAG_DEFAULT_APPS = "da";
1351    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1352
1353    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1354    private static final String TAG_ALL_GRANTS = "rt-grants";
1355    private static final String TAG_GRANT = "grant";
1356    private static final String ATTR_PACKAGE_NAME = "pkg";
1357
1358    private static final String TAG_PERMISSION = "perm";
1359    private static final String ATTR_PERMISSION_NAME = "name";
1360    private static final String ATTR_IS_GRANTED = "g";
1361    private static final String ATTR_USER_SET = "set";
1362    private static final String ATTR_USER_FIXED = "fixed";
1363    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1364
1365    // System/policy permission grants are not backed up
1366    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1367            FLAG_PERMISSION_POLICY_FIXED
1368            | FLAG_PERMISSION_SYSTEM_FIXED
1369            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1370
1371    // And we back up these user-adjusted states
1372    private static final int USER_RUNTIME_GRANT_MASK =
1373            FLAG_PERMISSION_USER_SET
1374            | FLAG_PERMISSION_USER_FIXED
1375            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1376
1377    final @Nullable String mRequiredVerifierPackage;
1378    final @NonNull String mRequiredInstallerPackage;
1379    final @NonNull String mRequiredUninstallerPackage;
1380    final @Nullable String mSetupWizardPackage;
1381    final @Nullable String mStorageManagerPackage;
1382    final @NonNull String mServicesSystemSharedLibraryPackageName;
1383    final @NonNull String mSharedSystemSharedLibraryPackageName;
1384
1385    final boolean mPermissionReviewRequired;
1386
1387    private final PackageUsage mPackageUsage = new PackageUsage();
1388    private final CompilerStats mCompilerStats = new CompilerStats();
1389
1390    class PackageHandler extends Handler {
1391        private boolean mBound = false;
1392        final ArrayList<HandlerParams> mPendingInstalls =
1393            new ArrayList<HandlerParams>();
1394
1395        private boolean connectToService() {
1396            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1397                    " DefaultContainerService");
1398            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1399            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1400            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1401                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1402                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1403                mBound = true;
1404                return true;
1405            }
1406            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1407            return false;
1408        }
1409
1410        private void disconnectService() {
1411            mContainerService = null;
1412            mBound = false;
1413            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1414            mContext.unbindService(mDefContainerConn);
1415            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1416        }
1417
1418        PackageHandler(Looper looper) {
1419            super(looper);
1420        }
1421
1422        public void handleMessage(Message msg) {
1423            try {
1424                doHandleMessage(msg);
1425            } finally {
1426                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1427            }
1428        }
1429
1430        void doHandleMessage(Message msg) {
1431            switch (msg.what) {
1432                case INIT_COPY: {
1433                    HandlerParams params = (HandlerParams) msg.obj;
1434                    int idx = mPendingInstalls.size();
1435                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1436                    // If a bind was already initiated we dont really
1437                    // need to do anything. The pending install
1438                    // will be processed later on.
1439                    if (!mBound) {
1440                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1441                                System.identityHashCode(mHandler));
1442                        // If this is the only one pending we might
1443                        // have to bind to the service again.
1444                        if (!connectToService()) {
1445                            Slog.e(TAG, "Failed to bind to media container service");
1446                            params.serviceError();
1447                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1448                                    System.identityHashCode(mHandler));
1449                            if (params.traceMethod != null) {
1450                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1451                                        params.traceCookie);
1452                            }
1453                            return;
1454                        } else {
1455                            // Once we bind to the service, the first
1456                            // pending request will be processed.
1457                            mPendingInstalls.add(idx, params);
1458                        }
1459                    } else {
1460                        mPendingInstalls.add(idx, params);
1461                        // Already bound to the service. Just make
1462                        // sure we trigger off processing the first request.
1463                        if (idx == 0) {
1464                            mHandler.sendEmptyMessage(MCS_BOUND);
1465                        }
1466                    }
1467                    break;
1468                }
1469                case MCS_BOUND: {
1470                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1471                    if (msg.obj != null) {
1472                        mContainerService = (IMediaContainerService) msg.obj;
1473                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1474                                System.identityHashCode(mHandler));
1475                    }
1476                    if (mContainerService == null) {
1477                        if (!mBound) {
1478                            // Something seriously wrong since we are not bound and we are not
1479                            // waiting for connection. Bail out.
1480                            Slog.e(TAG, "Cannot bind to media container service");
1481                            for (HandlerParams params : mPendingInstalls) {
1482                                // Indicate service bind error
1483                                params.serviceError();
1484                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1485                                        System.identityHashCode(params));
1486                                if (params.traceMethod != null) {
1487                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1488                                            params.traceMethod, params.traceCookie);
1489                                }
1490                                return;
1491                            }
1492                            mPendingInstalls.clear();
1493                        } else {
1494                            Slog.w(TAG, "Waiting to connect to media container service");
1495                        }
1496                    } else if (mPendingInstalls.size() > 0) {
1497                        HandlerParams params = mPendingInstalls.get(0);
1498                        if (params != null) {
1499                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1500                                    System.identityHashCode(params));
1501                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1502                            if (params.startCopy()) {
1503                                // We are done...  look for more work or to
1504                                // go idle.
1505                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1506                                        "Checking for more work or unbind...");
1507                                // Delete pending install
1508                                if (mPendingInstalls.size() > 0) {
1509                                    mPendingInstalls.remove(0);
1510                                }
1511                                if (mPendingInstalls.size() == 0) {
1512                                    if (mBound) {
1513                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1514                                                "Posting delayed MCS_UNBIND");
1515                                        removeMessages(MCS_UNBIND);
1516                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1517                                        // Unbind after a little delay, to avoid
1518                                        // continual thrashing.
1519                                        sendMessageDelayed(ubmsg, 10000);
1520                                    }
1521                                } else {
1522                                    // There are more pending requests in queue.
1523                                    // Just post MCS_BOUND message to trigger processing
1524                                    // of next pending install.
1525                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1526                                            "Posting MCS_BOUND for next work");
1527                                    mHandler.sendEmptyMessage(MCS_BOUND);
1528                                }
1529                            }
1530                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1531                        }
1532                    } else {
1533                        // Should never happen ideally.
1534                        Slog.w(TAG, "Empty queue");
1535                    }
1536                    break;
1537                }
1538                case MCS_RECONNECT: {
1539                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1540                    if (mPendingInstalls.size() > 0) {
1541                        if (mBound) {
1542                            disconnectService();
1543                        }
1544                        if (!connectToService()) {
1545                            Slog.e(TAG, "Failed to bind to media container service");
1546                            for (HandlerParams params : mPendingInstalls) {
1547                                // Indicate service bind error
1548                                params.serviceError();
1549                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1550                                        System.identityHashCode(params));
1551                            }
1552                            mPendingInstalls.clear();
1553                        }
1554                    }
1555                    break;
1556                }
1557                case MCS_UNBIND: {
1558                    // If there is no actual work left, then time to unbind.
1559                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1560
1561                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1562                        if (mBound) {
1563                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1564
1565                            disconnectService();
1566                        }
1567                    } else if (mPendingInstalls.size() > 0) {
1568                        // There are more pending requests in queue.
1569                        // Just post MCS_BOUND message to trigger processing
1570                        // of next pending install.
1571                        mHandler.sendEmptyMessage(MCS_BOUND);
1572                    }
1573
1574                    break;
1575                }
1576                case MCS_GIVE_UP: {
1577                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1578                    HandlerParams params = mPendingInstalls.remove(0);
1579                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1580                            System.identityHashCode(params));
1581                    break;
1582                }
1583                case SEND_PENDING_BROADCAST: {
1584                    String packages[];
1585                    ArrayList<String> components[];
1586                    int size = 0;
1587                    int uids[];
1588                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1589                    synchronized (mPackages) {
1590                        if (mPendingBroadcasts == null) {
1591                            return;
1592                        }
1593                        size = mPendingBroadcasts.size();
1594                        if (size <= 0) {
1595                            // Nothing to be done. Just return
1596                            return;
1597                        }
1598                        packages = new String[size];
1599                        components = new ArrayList[size];
1600                        uids = new int[size];
1601                        int i = 0;  // filling out the above arrays
1602
1603                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1604                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1605                            Iterator<Map.Entry<String, ArrayList<String>>> it
1606                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1607                                            .entrySet().iterator();
1608                            while (it.hasNext() && i < size) {
1609                                Map.Entry<String, ArrayList<String>> ent = it.next();
1610                                packages[i] = ent.getKey();
1611                                components[i] = ent.getValue();
1612                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1613                                uids[i] = (ps != null)
1614                                        ? UserHandle.getUid(packageUserId, ps.appId)
1615                                        : -1;
1616                                i++;
1617                            }
1618                        }
1619                        size = i;
1620                        mPendingBroadcasts.clear();
1621                    }
1622                    // Send broadcasts
1623                    for (int i = 0; i < size; i++) {
1624                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1625                    }
1626                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1627                    break;
1628                }
1629                case START_CLEANING_PACKAGE: {
1630                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1631                    final String packageName = (String)msg.obj;
1632                    final int userId = msg.arg1;
1633                    final boolean andCode = msg.arg2 != 0;
1634                    synchronized (mPackages) {
1635                        if (userId == UserHandle.USER_ALL) {
1636                            int[] users = sUserManager.getUserIds();
1637                            for (int user : users) {
1638                                mSettings.addPackageToCleanLPw(
1639                                        new PackageCleanItem(user, packageName, andCode));
1640                            }
1641                        } else {
1642                            mSettings.addPackageToCleanLPw(
1643                                    new PackageCleanItem(userId, packageName, andCode));
1644                        }
1645                    }
1646                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1647                    startCleaningPackages();
1648                } break;
1649                case POST_INSTALL: {
1650                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1651
1652                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1653                    final boolean didRestore = (msg.arg2 != 0);
1654                    mRunningInstalls.delete(msg.arg1);
1655
1656                    if (data != null) {
1657                        InstallArgs args = data.args;
1658                        PackageInstalledInfo parentRes = data.res;
1659
1660                        final boolean grantPermissions = (args.installFlags
1661                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1662                        final boolean killApp = (args.installFlags
1663                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1664                        final String[] grantedPermissions = args.installGrantPermissions;
1665
1666                        // Handle the parent package
1667                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1668                                grantedPermissions, didRestore, args.installerPackageName,
1669                                args.observer);
1670
1671                        // Handle the child packages
1672                        final int childCount = (parentRes.addedChildPackages != null)
1673                                ? parentRes.addedChildPackages.size() : 0;
1674                        for (int i = 0; i < childCount; i++) {
1675                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1676                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1677                                    grantedPermissions, false, args.installerPackageName,
1678                                    args.observer);
1679                        }
1680
1681                        // Log tracing if needed
1682                        if (args.traceMethod != null) {
1683                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1684                                    args.traceCookie);
1685                        }
1686                    } else {
1687                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1688                    }
1689
1690                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1691                } break;
1692                case UPDATED_MEDIA_STATUS: {
1693                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1694                    boolean reportStatus = msg.arg1 == 1;
1695                    boolean doGc = msg.arg2 == 1;
1696                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1697                    if (doGc) {
1698                        // Force a gc to clear up stale containers.
1699                        Runtime.getRuntime().gc();
1700                    }
1701                    if (msg.obj != null) {
1702                        @SuppressWarnings("unchecked")
1703                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1704                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1705                        // Unload containers
1706                        unloadAllContainers(args);
1707                    }
1708                    if (reportStatus) {
1709                        try {
1710                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1711                                    "Invoking StorageManagerService call back");
1712                            PackageHelper.getStorageManager().finishMediaUpdate();
1713                        } catch (RemoteException e) {
1714                            Log.e(TAG, "StorageManagerService not running?");
1715                        }
1716                    }
1717                } break;
1718                case WRITE_SETTINGS: {
1719                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1720                    synchronized (mPackages) {
1721                        removeMessages(WRITE_SETTINGS);
1722                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1723                        mSettings.writeLPr();
1724                        mDirtyUsers.clear();
1725                    }
1726                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1727                } break;
1728                case WRITE_PACKAGE_RESTRICTIONS: {
1729                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1730                    synchronized (mPackages) {
1731                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1732                        for (int userId : mDirtyUsers) {
1733                            mSettings.writePackageRestrictionsLPr(userId);
1734                        }
1735                        mDirtyUsers.clear();
1736                    }
1737                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1738                } break;
1739                case WRITE_PACKAGE_LIST: {
1740                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1741                    synchronized (mPackages) {
1742                        removeMessages(WRITE_PACKAGE_LIST);
1743                        mSettings.writePackageListLPr(msg.arg1);
1744                    }
1745                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1746                } break;
1747                case CHECK_PENDING_VERIFICATION: {
1748                    final int verificationId = msg.arg1;
1749                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1750
1751                    if ((state != null) && !state.timeoutExtended()) {
1752                        final InstallArgs args = state.getInstallArgs();
1753                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1754
1755                        Slog.i(TAG, "Verification timed out for " + originUri);
1756                        mPendingVerification.remove(verificationId);
1757
1758                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1759
1760                        final UserHandle user = args.getUser();
1761                        if (getDefaultVerificationResponse(user)
1762                                == PackageManager.VERIFICATION_ALLOW) {
1763                            Slog.i(TAG, "Continuing with installation of " + originUri);
1764                            state.setVerifierResponse(Binder.getCallingUid(),
1765                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1766                            broadcastPackageVerified(verificationId, originUri,
1767                                    PackageManager.VERIFICATION_ALLOW, user);
1768                            try {
1769                                ret = args.copyApk(mContainerService, true);
1770                            } catch (RemoteException e) {
1771                                Slog.e(TAG, "Could not contact the ContainerService");
1772                            }
1773                        } else {
1774                            broadcastPackageVerified(verificationId, originUri,
1775                                    PackageManager.VERIFICATION_REJECT, user);
1776                        }
1777
1778                        Trace.asyncTraceEnd(
1779                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1780
1781                        processPendingInstall(args, ret);
1782                        mHandler.sendEmptyMessage(MCS_UNBIND);
1783                    }
1784                    break;
1785                }
1786                case PACKAGE_VERIFIED: {
1787                    final int verificationId = msg.arg1;
1788
1789                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1790                    if (state == null) {
1791                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1792                        break;
1793                    }
1794
1795                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1796
1797                    state.setVerifierResponse(response.callerUid, response.code);
1798
1799                    if (state.isVerificationComplete()) {
1800                        mPendingVerification.remove(verificationId);
1801
1802                        final InstallArgs args = state.getInstallArgs();
1803                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1804
1805                        int ret;
1806                        if (state.isInstallAllowed()) {
1807                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1808                            broadcastPackageVerified(verificationId, originUri,
1809                                    response.code, state.getInstallArgs().getUser());
1810                            try {
1811                                ret = args.copyApk(mContainerService, true);
1812                            } catch (RemoteException e) {
1813                                Slog.e(TAG, "Could not contact the ContainerService");
1814                            }
1815                        } else {
1816                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1817                        }
1818
1819                        Trace.asyncTraceEnd(
1820                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1821
1822                        processPendingInstall(args, ret);
1823                        mHandler.sendEmptyMessage(MCS_UNBIND);
1824                    }
1825
1826                    break;
1827                }
1828                case START_INTENT_FILTER_VERIFICATIONS: {
1829                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1830                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1831                            params.replacing, params.pkg);
1832                    break;
1833                }
1834                case INTENT_FILTER_VERIFIED: {
1835                    final int verificationId = msg.arg1;
1836
1837                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1838                            verificationId);
1839                    if (state == null) {
1840                        Slog.w(TAG, "Invalid IntentFilter verification token "
1841                                + verificationId + " received");
1842                        break;
1843                    }
1844
1845                    final int userId = state.getUserId();
1846
1847                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1848                            "Processing IntentFilter verification with token:"
1849                            + verificationId + " and userId:" + userId);
1850
1851                    final IntentFilterVerificationResponse response =
1852                            (IntentFilterVerificationResponse) msg.obj;
1853
1854                    state.setVerifierResponse(response.callerUid, response.code);
1855
1856                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1857                            "IntentFilter verification with token:" + verificationId
1858                            + " and userId:" + userId
1859                            + " is settings verifier response with response code:"
1860                            + response.code);
1861
1862                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1863                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1864                                + response.getFailedDomainsString());
1865                    }
1866
1867                    if (state.isVerificationComplete()) {
1868                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1869                    } else {
1870                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1871                                "IntentFilter verification with token:" + verificationId
1872                                + " was not said to be complete");
1873                    }
1874
1875                    break;
1876                }
1877                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1878                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1879                            mInstantAppResolverConnection,
1880                            (InstantAppRequest) msg.obj,
1881                            mInstantAppInstallerActivity,
1882                            mHandler);
1883                }
1884            }
1885        }
1886    }
1887
1888    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1889            boolean killApp, String[] grantedPermissions,
1890            boolean launchedForRestore, String installerPackage,
1891            IPackageInstallObserver2 installObserver) {
1892        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1893            // Send the removed broadcasts
1894            if (res.removedInfo != null) {
1895                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1896            }
1897
1898            // Now that we successfully installed the package, grant runtime
1899            // permissions if requested before broadcasting the install. Also
1900            // for legacy apps in permission review mode we clear the permission
1901            // review flag which is used to emulate runtime permissions for
1902            // legacy apps.
1903            if (grantPermissions) {
1904                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1905            }
1906
1907            final boolean update = res.removedInfo != null
1908                    && res.removedInfo.removedPackage != null;
1909            final String origInstallerPackageName = res.removedInfo != null
1910                    ? res.removedInfo.installerPackageName : null;
1911
1912            // If this is the first time we have child packages for a disabled privileged
1913            // app that had no children, we grant requested runtime permissions to the new
1914            // children if the parent on the system image had them already granted.
1915            if (res.pkg.parentPackage != null) {
1916                synchronized (mPackages) {
1917                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1918                }
1919            }
1920
1921            synchronized (mPackages) {
1922                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1923            }
1924
1925            final String packageName = res.pkg.applicationInfo.packageName;
1926
1927            // Determine the set of users who are adding this package for
1928            // the first time vs. those who are seeing an update.
1929            int[] firstUsers = EMPTY_INT_ARRAY;
1930            int[] updateUsers = EMPTY_INT_ARRAY;
1931            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1932            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1933            for (int newUser : res.newUsers) {
1934                if (ps.getInstantApp(newUser)) {
1935                    continue;
1936                }
1937                if (allNewUsers) {
1938                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1939                    continue;
1940                }
1941                boolean isNew = true;
1942                for (int origUser : res.origUsers) {
1943                    if (origUser == newUser) {
1944                        isNew = false;
1945                        break;
1946                    }
1947                }
1948                if (isNew) {
1949                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1950                } else {
1951                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1952                }
1953            }
1954
1955            // Send installed broadcasts if the package is not a static shared lib.
1956            if (res.pkg.staticSharedLibName == null) {
1957                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1958
1959                // Send added for users that see the package for the first time
1960                // sendPackageAddedForNewUsers also deals with system apps
1961                int appId = UserHandle.getAppId(res.uid);
1962                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1963                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1964
1965                // Send added for users that don't see the package for the first time
1966                Bundle extras = new Bundle(1);
1967                extras.putInt(Intent.EXTRA_UID, res.uid);
1968                if (update) {
1969                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1970                }
1971                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1972                        extras, 0 /*flags*/,
1973                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1974                if (origInstallerPackageName != null) {
1975                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1976                            extras, 0 /*flags*/,
1977                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1978                }
1979
1980                // Send replaced for users that don't see the package for the first time
1981                if (update) {
1982                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1983                            packageName, extras, 0 /*flags*/,
1984                            null /*targetPackage*/, null /*finishedReceiver*/,
1985                            updateUsers);
1986                    if (origInstallerPackageName != null) {
1987                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1988                                extras, 0 /*flags*/,
1989                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1990                    }
1991                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1992                            null /*package*/, null /*extras*/, 0 /*flags*/,
1993                            packageName /*targetPackage*/,
1994                            null /*finishedReceiver*/, updateUsers);
1995                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1996                    // First-install and we did a restore, so we're responsible for the
1997                    // first-launch broadcast.
1998                    if (DEBUG_BACKUP) {
1999                        Slog.i(TAG, "Post-restore of " + packageName
2000                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2001                    }
2002                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2003                }
2004
2005                // Send broadcast package appeared if forward locked/external for all users
2006                // treat asec-hosted packages like removable media on upgrade
2007                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2008                    if (DEBUG_INSTALL) {
2009                        Slog.i(TAG, "upgrading pkg " + res.pkg
2010                                + " is ASEC-hosted -> AVAILABLE");
2011                    }
2012                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2013                    ArrayList<String> pkgList = new ArrayList<>(1);
2014                    pkgList.add(packageName);
2015                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2016                }
2017            }
2018
2019            // Work that needs to happen on first install within each user
2020            if (firstUsers != null && firstUsers.length > 0) {
2021                synchronized (mPackages) {
2022                    for (int userId : firstUsers) {
2023                        // If this app is a browser and it's newly-installed for some
2024                        // users, clear any default-browser state in those users. The
2025                        // app's nature doesn't depend on the user, so we can just check
2026                        // its browser nature in any user and generalize.
2027                        if (packageIsBrowser(packageName, userId)) {
2028                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2029                        }
2030
2031                        // We may also need to apply pending (restored) runtime
2032                        // permission grants within these users.
2033                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2034                    }
2035                }
2036            }
2037
2038            // Log current value of "unknown sources" setting
2039            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2040                    getUnknownSourcesSettings());
2041
2042            // Remove the replaced package's older resources safely now
2043            // We delete after a gc for applications  on sdcard.
2044            if (res.removedInfo != null && res.removedInfo.args != null) {
2045                Runtime.getRuntime().gc();
2046                synchronized (mInstallLock) {
2047                    res.removedInfo.args.doPostDeleteLI(true);
2048                }
2049            } else {
2050                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2051                // and not block here.
2052                VMRuntime.getRuntime().requestConcurrentGC();
2053            }
2054
2055            // Notify DexManager that the package was installed for new users.
2056            // The updated users should already be indexed and the package code paths
2057            // should not change.
2058            // Don't notify the manager for ephemeral apps as they are not expected to
2059            // survive long enough to benefit of background optimizations.
2060            for (int userId : firstUsers) {
2061                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2062                // There's a race currently where some install events may interleave with an uninstall.
2063                // This can lead to package info being null (b/36642664).
2064                if (info != null) {
2065                    mDexManager.notifyPackageInstalled(info, userId);
2066                }
2067            }
2068        }
2069
2070        // If someone is watching installs - notify them
2071        if (installObserver != null) {
2072            try {
2073                Bundle extras = extrasForInstallResult(res);
2074                installObserver.onPackageInstalled(res.name, res.returnCode,
2075                        res.returnMsg, extras);
2076            } catch (RemoteException e) {
2077                Slog.i(TAG, "Observer no longer exists.");
2078            }
2079        }
2080    }
2081
2082    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2083            PackageParser.Package pkg) {
2084        if (pkg.parentPackage == null) {
2085            return;
2086        }
2087        if (pkg.requestedPermissions == null) {
2088            return;
2089        }
2090        final PackageSetting disabledSysParentPs = mSettings
2091                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2092        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2093                || !disabledSysParentPs.isPrivileged()
2094                || (disabledSysParentPs.childPackageNames != null
2095                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2096            return;
2097        }
2098        final int[] allUserIds = sUserManager.getUserIds();
2099        final int permCount = pkg.requestedPermissions.size();
2100        for (int i = 0; i < permCount; i++) {
2101            String permission = pkg.requestedPermissions.get(i);
2102            BasePermission bp = mSettings.mPermissions.get(permission);
2103            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2104                continue;
2105            }
2106            for (int userId : allUserIds) {
2107                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2108                        permission, userId)) {
2109                    grantRuntimePermission(pkg.packageName, permission, userId);
2110                }
2111            }
2112        }
2113    }
2114
2115    private StorageEventListener mStorageListener = new StorageEventListener() {
2116        @Override
2117        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2118            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2119                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2120                    final String volumeUuid = vol.getFsUuid();
2121
2122                    // Clean up any users or apps that were removed or recreated
2123                    // while this volume was missing
2124                    sUserManager.reconcileUsers(volumeUuid);
2125                    reconcileApps(volumeUuid);
2126
2127                    // Clean up any install sessions that expired or were
2128                    // cancelled while this volume was missing
2129                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2130
2131                    loadPrivatePackages(vol);
2132
2133                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2134                    unloadPrivatePackages(vol);
2135                }
2136            }
2137
2138            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2139                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2140                    updateExternalMediaStatus(true, false);
2141                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2142                    updateExternalMediaStatus(false, false);
2143                }
2144            }
2145        }
2146
2147        @Override
2148        public void onVolumeForgotten(String fsUuid) {
2149            if (TextUtils.isEmpty(fsUuid)) {
2150                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2151                return;
2152            }
2153
2154            // Remove any apps installed on the forgotten volume
2155            synchronized (mPackages) {
2156                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2157                for (PackageSetting ps : packages) {
2158                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2159                    deletePackageVersioned(new VersionedPackage(ps.name,
2160                            PackageManager.VERSION_CODE_HIGHEST),
2161                            new LegacyPackageDeleteObserver(null).getBinder(),
2162                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2163                    // Try very hard to release any references to this package
2164                    // so we don't risk the system server being killed due to
2165                    // open FDs
2166                    AttributeCache.instance().removePackage(ps.name);
2167                }
2168
2169                mSettings.onVolumeForgotten(fsUuid);
2170                mSettings.writeLPr();
2171            }
2172        }
2173    };
2174
2175    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2176            String[] grantedPermissions) {
2177        for (int userId : userIds) {
2178            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2179        }
2180    }
2181
2182    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2183            String[] grantedPermissions) {
2184        PackageSetting ps = (PackageSetting) pkg.mExtras;
2185        if (ps == null) {
2186            return;
2187        }
2188
2189        PermissionsState permissionsState = ps.getPermissionsState();
2190
2191        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2192                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2193
2194        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2195                >= Build.VERSION_CODES.M;
2196
2197        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2198
2199        for (String permission : pkg.requestedPermissions) {
2200            final BasePermission bp;
2201            synchronized (mPackages) {
2202                bp = mSettings.mPermissions.get(permission);
2203            }
2204            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2205                    && (!instantApp || bp.isInstant())
2206                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2207                    && (grantedPermissions == null
2208                           || ArrayUtils.contains(grantedPermissions, permission))) {
2209                final int flags = permissionsState.getPermissionFlags(permission, userId);
2210                if (supportsRuntimePermissions) {
2211                    // Installer cannot change immutable permissions.
2212                    if ((flags & immutableFlags) == 0) {
2213                        grantRuntimePermission(pkg.packageName, permission, userId);
2214                    }
2215                } else if (mPermissionReviewRequired) {
2216                    // In permission review mode we clear the review flag when we
2217                    // are asked to install the app with all permissions granted.
2218                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2219                        updatePermissionFlags(permission, pkg.packageName,
2220                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2221                    }
2222                }
2223            }
2224        }
2225    }
2226
2227    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2228        Bundle extras = null;
2229        switch (res.returnCode) {
2230            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2231                extras = new Bundle();
2232                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2233                        res.origPermission);
2234                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2235                        res.origPackage);
2236                break;
2237            }
2238            case PackageManager.INSTALL_SUCCEEDED: {
2239                extras = new Bundle();
2240                extras.putBoolean(Intent.EXTRA_REPLACING,
2241                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2242                break;
2243            }
2244        }
2245        return extras;
2246    }
2247
2248    void scheduleWriteSettingsLocked() {
2249        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2250            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2251        }
2252    }
2253
2254    void scheduleWritePackageListLocked(int userId) {
2255        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2256            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2257            msg.arg1 = userId;
2258            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2259        }
2260    }
2261
2262    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2263        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2264        scheduleWritePackageRestrictionsLocked(userId);
2265    }
2266
2267    void scheduleWritePackageRestrictionsLocked(int userId) {
2268        final int[] userIds = (userId == UserHandle.USER_ALL)
2269                ? sUserManager.getUserIds() : new int[]{userId};
2270        for (int nextUserId : userIds) {
2271            if (!sUserManager.exists(nextUserId)) return;
2272            mDirtyUsers.add(nextUserId);
2273            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2274                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2275            }
2276        }
2277    }
2278
2279    public static PackageManagerService main(Context context, Installer installer,
2280            boolean factoryTest, boolean onlyCore) {
2281        // Self-check for initial settings.
2282        PackageManagerServiceCompilerMapping.checkProperties();
2283
2284        PackageManagerService m = new PackageManagerService(context, installer,
2285                factoryTest, onlyCore);
2286        m.enableSystemUserPackages();
2287        ServiceManager.addService("package", m);
2288        return m;
2289    }
2290
2291    private void enableSystemUserPackages() {
2292        if (!UserManager.isSplitSystemUser()) {
2293            return;
2294        }
2295        // For system user, enable apps based on the following conditions:
2296        // - app is whitelisted or belong to one of these groups:
2297        //   -- system app which has no launcher icons
2298        //   -- system app which has INTERACT_ACROSS_USERS permission
2299        //   -- system IME app
2300        // - app is not in the blacklist
2301        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2302        Set<String> enableApps = new ArraySet<>();
2303        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2304                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2305                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2306        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2307        enableApps.addAll(wlApps);
2308        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2309                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2310        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2311        enableApps.removeAll(blApps);
2312        Log.i(TAG, "Applications installed for system user: " + enableApps);
2313        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2314                UserHandle.SYSTEM);
2315        final int allAppsSize = allAps.size();
2316        synchronized (mPackages) {
2317            for (int i = 0; i < allAppsSize; i++) {
2318                String pName = allAps.get(i);
2319                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2320                // Should not happen, but we shouldn't be failing if it does
2321                if (pkgSetting == null) {
2322                    continue;
2323                }
2324                boolean install = enableApps.contains(pName);
2325                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2326                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2327                            + " for system user");
2328                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2329                }
2330            }
2331            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2332        }
2333    }
2334
2335    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2336        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2337                Context.DISPLAY_SERVICE);
2338        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2339    }
2340
2341    /**
2342     * Requests that files preopted on a secondary system partition be copied to the data partition
2343     * if possible.  Note that the actual copying of the files is accomplished by init for security
2344     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2345     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2346     */
2347    private static void requestCopyPreoptedFiles() {
2348        final int WAIT_TIME_MS = 100;
2349        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2350        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2351            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2352            // We will wait for up to 100 seconds.
2353            final long timeStart = SystemClock.uptimeMillis();
2354            final long timeEnd = timeStart + 100 * 1000;
2355            long timeNow = timeStart;
2356            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2357                try {
2358                    Thread.sleep(WAIT_TIME_MS);
2359                } catch (InterruptedException e) {
2360                    // Do nothing
2361                }
2362                timeNow = SystemClock.uptimeMillis();
2363                if (timeNow > timeEnd) {
2364                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2365                    Slog.wtf(TAG, "cppreopt did not finish!");
2366                    break;
2367                }
2368            }
2369
2370            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2371        }
2372    }
2373
2374    public PackageManagerService(Context context, Installer installer,
2375            boolean factoryTest, boolean onlyCore) {
2376        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2377        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2378        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2379                SystemClock.uptimeMillis());
2380
2381        if (mSdkVersion <= 0) {
2382            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2383        }
2384
2385        mContext = context;
2386
2387        mPermissionReviewRequired = context.getResources().getBoolean(
2388                R.bool.config_permissionReviewRequired);
2389
2390        mFactoryTest = factoryTest;
2391        mOnlyCore = onlyCore;
2392        mMetrics = new DisplayMetrics();
2393        mSettings = new Settings(mPackages);
2394        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2395                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2396        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2397                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2398        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2399                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2400        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2401                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2402        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2403                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406
2407        String separateProcesses = SystemProperties.get("debug.separate_processes");
2408        if (separateProcesses != null && separateProcesses.length() > 0) {
2409            if ("*".equals(separateProcesses)) {
2410                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2411                mSeparateProcesses = null;
2412                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2413            } else {
2414                mDefParseFlags = 0;
2415                mSeparateProcesses = separateProcesses.split(",");
2416                Slog.w(TAG, "Running with debug.separate_processes: "
2417                        + separateProcesses);
2418            }
2419        } else {
2420            mDefParseFlags = 0;
2421            mSeparateProcesses = null;
2422        }
2423
2424        mInstaller = installer;
2425        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2426                "*dexopt*");
2427        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2428        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2429
2430        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2431                FgThread.get().getLooper());
2432
2433        getDefaultDisplayMetrics(context, mMetrics);
2434
2435        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2436        SystemConfig systemConfig = SystemConfig.getInstance();
2437        mGlobalGids = systemConfig.getGlobalGids();
2438        mSystemPermissions = systemConfig.getSystemPermissions();
2439        mAvailableFeatures = systemConfig.getAvailableFeatures();
2440        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2441
2442        mProtectedPackages = new ProtectedPackages(mContext);
2443
2444        synchronized (mInstallLock) {
2445        // writer
2446        synchronized (mPackages) {
2447            mHandlerThread = new ServiceThread(TAG,
2448                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2449            mHandlerThread.start();
2450            mHandler = new PackageHandler(mHandlerThread.getLooper());
2451            mProcessLoggingHandler = new ProcessLoggingHandler();
2452            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2453
2454            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2455            mInstantAppRegistry = new InstantAppRegistry(this);
2456
2457            File dataDir = Environment.getDataDirectory();
2458            mAppInstallDir = new File(dataDir, "app");
2459            mAppLib32InstallDir = new File(dataDir, "app-lib");
2460            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2461            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2462            sUserManager = new UserManagerService(context, this,
2463                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2464
2465            // Propagate permission configuration in to package manager.
2466            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2467                    = systemConfig.getPermissions();
2468            for (int i=0; i<permConfig.size(); i++) {
2469                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2470                BasePermission bp = mSettings.mPermissions.get(perm.name);
2471                if (bp == null) {
2472                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2473                    mSettings.mPermissions.put(perm.name, bp);
2474                }
2475                if (perm.gids != null) {
2476                    bp.setGids(perm.gids, perm.perUser);
2477                }
2478            }
2479
2480            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2481            final int builtInLibCount = libConfig.size();
2482            for (int i = 0; i < builtInLibCount; i++) {
2483                String name = libConfig.keyAt(i);
2484                String path = libConfig.valueAt(i);
2485                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2486                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2487            }
2488
2489            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2490
2491            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2492            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2493            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2494
2495            // Clean up orphaned packages for which the code path doesn't exist
2496            // and they are an update to a system app - caused by bug/32321269
2497            final int packageSettingCount = mSettings.mPackages.size();
2498            for (int i = packageSettingCount - 1; i >= 0; i--) {
2499                PackageSetting ps = mSettings.mPackages.valueAt(i);
2500                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2501                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2502                    mSettings.mPackages.removeAt(i);
2503                    mSettings.enableSystemPackageLPw(ps.name);
2504                }
2505            }
2506
2507            if (mFirstBoot) {
2508                requestCopyPreoptedFiles();
2509            }
2510
2511            String customResolverActivity = Resources.getSystem().getString(
2512                    R.string.config_customResolverActivity);
2513            if (TextUtils.isEmpty(customResolverActivity)) {
2514                customResolverActivity = null;
2515            } else {
2516                mCustomResolverComponentName = ComponentName.unflattenFromString(
2517                        customResolverActivity);
2518            }
2519
2520            long startTime = SystemClock.uptimeMillis();
2521
2522            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2523                    startTime);
2524
2525            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2526            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2527
2528            if (bootClassPath == null) {
2529                Slog.w(TAG, "No BOOTCLASSPATH found!");
2530            }
2531
2532            if (systemServerClassPath == null) {
2533                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2534            }
2535
2536            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2537
2538            final VersionInfo ver = mSettings.getInternalVersion();
2539            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2540            if (mIsUpgrade) {
2541                logCriticalInfo(Log.INFO,
2542                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2543            }
2544
2545            // when upgrading from pre-M, promote system app permissions from install to runtime
2546            mPromoteSystemApps =
2547                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2548
2549            // When upgrading from pre-N, we need to handle package extraction like first boot,
2550            // as there is no profiling data available.
2551            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2552
2553            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2554
2555            // save off the names of pre-existing system packages prior to scanning; we don't
2556            // want to automatically grant runtime permissions for new system apps
2557            if (mPromoteSystemApps) {
2558                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2559                while (pkgSettingIter.hasNext()) {
2560                    PackageSetting ps = pkgSettingIter.next();
2561                    if (isSystemApp(ps)) {
2562                        mExistingSystemPackages.add(ps.name);
2563                    }
2564                }
2565            }
2566
2567            mCacheDir = preparePackageParserCache(mIsUpgrade);
2568
2569            // Set flag to monitor and not change apk file paths when
2570            // scanning install directories.
2571            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2572
2573            if (mIsUpgrade || mFirstBoot) {
2574                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2575            }
2576
2577            // Collect vendor overlay packages. (Do this before scanning any apps.)
2578            // For security and version matching reason, only consider
2579            // overlay packages if they reside in the right directory.
2580            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2581                    | PackageParser.PARSE_IS_SYSTEM
2582                    | PackageParser.PARSE_IS_SYSTEM_DIR
2583                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2584
2585            mParallelPackageParserCallback.findStaticOverlayPackages();
2586
2587            // Find base frameworks (resource packages without code).
2588            scanDirTracedLI(frameworkDir, mDefParseFlags
2589                    | PackageParser.PARSE_IS_SYSTEM
2590                    | PackageParser.PARSE_IS_SYSTEM_DIR
2591                    | PackageParser.PARSE_IS_PRIVILEGED,
2592                    scanFlags | SCAN_NO_DEX, 0);
2593
2594            // Collected privileged system packages.
2595            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2596            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2597                    | PackageParser.PARSE_IS_SYSTEM
2598                    | PackageParser.PARSE_IS_SYSTEM_DIR
2599                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2600
2601            // Collect ordinary system packages.
2602            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2603            scanDirTracedLI(systemAppDir, mDefParseFlags
2604                    | PackageParser.PARSE_IS_SYSTEM
2605                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2606
2607            // Collect all vendor packages.
2608            File vendorAppDir = new File("/vendor/app");
2609            try {
2610                vendorAppDir = vendorAppDir.getCanonicalFile();
2611            } catch (IOException e) {
2612                // failed to look up canonical path, continue with original one
2613            }
2614            scanDirTracedLI(vendorAppDir, mDefParseFlags
2615                    | PackageParser.PARSE_IS_SYSTEM
2616                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2617
2618            // Collect all OEM packages.
2619            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2620            scanDirTracedLI(oemAppDir, mDefParseFlags
2621                    | PackageParser.PARSE_IS_SYSTEM
2622                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2623
2624            // Prune any system packages that no longer exist.
2625            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2626            if (!mOnlyCore) {
2627                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2628                while (psit.hasNext()) {
2629                    PackageSetting ps = psit.next();
2630
2631                    /*
2632                     * If this is not a system app, it can't be a
2633                     * disable system app.
2634                     */
2635                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2636                        continue;
2637                    }
2638
2639                    /*
2640                     * If the package is scanned, it's not erased.
2641                     */
2642                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2643                    if (scannedPkg != null) {
2644                        /*
2645                         * If the system app is both scanned and in the
2646                         * disabled packages list, then it must have been
2647                         * added via OTA. Remove it from the currently
2648                         * scanned package so the previously user-installed
2649                         * application can be scanned.
2650                         */
2651                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2652                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2653                                    + ps.name + "; removing system app.  Last known codePath="
2654                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2655                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2656                                    + scannedPkg.mVersionCode);
2657                            removePackageLI(scannedPkg, true);
2658                            mExpectingBetter.put(ps.name, ps.codePath);
2659                        }
2660
2661                        continue;
2662                    }
2663
2664                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2665                        psit.remove();
2666                        logCriticalInfo(Log.WARN, "System package " + ps.name
2667                                + " no longer exists; it's data will be wiped");
2668                        // Actual deletion of code and data will be handled by later
2669                        // reconciliation step
2670                    } else {
2671                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2672                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2673                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2674                        }
2675                    }
2676                }
2677            }
2678
2679            //look for any incomplete package installations
2680            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2681            for (int i = 0; i < deletePkgsList.size(); i++) {
2682                // Actual deletion of code and data will be handled by later
2683                // reconciliation step
2684                final String packageName = deletePkgsList.get(i).name;
2685                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2686                synchronized (mPackages) {
2687                    mSettings.removePackageLPw(packageName);
2688                }
2689            }
2690
2691            //delete tmp files
2692            deleteTempPackageFiles();
2693
2694            // Remove any shared userIDs that have no associated packages
2695            mSettings.pruneSharedUsersLPw();
2696
2697            if (!mOnlyCore) {
2698                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2699                        SystemClock.uptimeMillis());
2700                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2701
2702                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2703                        | PackageParser.PARSE_FORWARD_LOCK,
2704                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2705
2706                /**
2707                 * Remove disable package settings for any updated system
2708                 * apps that were removed via an OTA. If they're not a
2709                 * previously-updated app, remove them completely.
2710                 * Otherwise, just revoke their system-level permissions.
2711                 */
2712                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2713                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2714                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2715
2716                    String msg;
2717                    if (deletedPkg == null) {
2718                        msg = "Updated system package " + deletedAppName
2719                                + " no longer exists; it's data will be wiped";
2720                        // Actual deletion of code and data will be handled by later
2721                        // reconciliation step
2722                    } else {
2723                        msg = "Updated system app + " + deletedAppName
2724                                + " no longer present; removing system privileges for "
2725                                + deletedAppName;
2726
2727                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2728
2729                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2730                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2731                    }
2732                    logCriticalInfo(Log.WARN, msg);
2733                }
2734
2735                /**
2736                 * Make sure all system apps that we expected to appear on
2737                 * the userdata partition actually showed up. If they never
2738                 * appeared, crawl back and revive the system version.
2739                 */
2740                for (int i = 0; i < mExpectingBetter.size(); i++) {
2741                    final String packageName = mExpectingBetter.keyAt(i);
2742                    if (!mPackages.containsKey(packageName)) {
2743                        final File scanFile = mExpectingBetter.valueAt(i);
2744
2745                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2746                                + " but never showed up; reverting to system");
2747
2748                        int reparseFlags = mDefParseFlags;
2749                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2750                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2751                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2752                                    | PackageParser.PARSE_IS_PRIVILEGED;
2753                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2754                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2755                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2756                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2757                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2758                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2759                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2760                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2761                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2762                        } else {
2763                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2764                            continue;
2765                        }
2766
2767                        mSettings.enableSystemPackageLPw(packageName);
2768
2769                        try {
2770                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2771                        } catch (PackageManagerException e) {
2772                            Slog.e(TAG, "Failed to parse original system package: "
2773                                    + e.getMessage());
2774                        }
2775                    }
2776                }
2777            }
2778            mExpectingBetter.clear();
2779
2780            // Resolve the storage manager.
2781            mStorageManagerPackage = getStorageManagerPackageName();
2782
2783            // Resolve protected action filters. Only the setup wizard is allowed to
2784            // have a high priority filter for these actions.
2785            mSetupWizardPackage = getSetupWizardPackageName();
2786            if (mProtectedFilters.size() > 0) {
2787                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2788                    Slog.i(TAG, "No setup wizard;"
2789                        + " All protected intents capped to priority 0");
2790                }
2791                for (ActivityIntentInfo filter : mProtectedFilters) {
2792                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2793                        if (DEBUG_FILTERS) {
2794                            Slog.i(TAG, "Found setup wizard;"
2795                                + " allow priority " + filter.getPriority() + ";"
2796                                + " package: " + filter.activity.info.packageName
2797                                + " activity: " + filter.activity.className
2798                                + " priority: " + filter.getPriority());
2799                        }
2800                        // skip setup wizard; allow it to keep the high priority filter
2801                        continue;
2802                    }
2803                    if (DEBUG_FILTERS) {
2804                        Slog.i(TAG, "Protected action; cap priority to 0;"
2805                                + " package: " + filter.activity.info.packageName
2806                                + " activity: " + filter.activity.className
2807                                + " origPrio: " + filter.getPriority());
2808                    }
2809                    filter.setPriority(0);
2810                }
2811            }
2812            mDeferProtectedFilters = false;
2813            mProtectedFilters.clear();
2814
2815            // Now that we know all of the shared libraries, update all clients to have
2816            // the correct library paths.
2817            updateAllSharedLibrariesLPw(null);
2818
2819            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2820                // NOTE: We ignore potential failures here during a system scan (like
2821                // the rest of the commands above) because there's precious little we
2822                // can do about it. A settings error is reported, though.
2823                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2824            }
2825
2826            // Now that we know all the packages we are keeping,
2827            // read and update their last usage times.
2828            mPackageUsage.read(mPackages);
2829            mCompilerStats.read();
2830
2831            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2832                    SystemClock.uptimeMillis());
2833            Slog.i(TAG, "Time to scan packages: "
2834                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2835                    + " seconds");
2836
2837            // If the platform SDK has changed since the last time we booted,
2838            // we need to re-grant app permission to catch any new ones that
2839            // appear.  This is really a hack, and means that apps can in some
2840            // cases get permissions that the user didn't initially explicitly
2841            // allow...  it would be nice to have some better way to handle
2842            // this situation.
2843            int updateFlags = UPDATE_PERMISSIONS_ALL;
2844            if (ver.sdkVersion != mSdkVersion) {
2845                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2846                        + mSdkVersion + "; regranting permissions for internal storage");
2847                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2848            }
2849            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2850            ver.sdkVersion = mSdkVersion;
2851
2852            // If this is the first boot or an update from pre-M, and it is a normal
2853            // boot, then we need to initialize the default preferred apps across
2854            // all defined users.
2855            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2856                for (UserInfo user : sUserManager.getUsers(true)) {
2857                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2858                    applyFactoryDefaultBrowserLPw(user.id);
2859                    primeDomainVerificationsLPw(user.id);
2860                }
2861            }
2862
2863            // Prepare storage for system user really early during boot,
2864            // since core system apps like SettingsProvider and SystemUI
2865            // can't wait for user to start
2866            final int storageFlags;
2867            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2868                storageFlags = StorageManager.FLAG_STORAGE_DE;
2869            } else {
2870                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2871            }
2872            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2873                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2874                    true /* onlyCoreApps */);
2875            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2876                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2877                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2878                traceLog.traceBegin("AppDataFixup");
2879                try {
2880                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2881                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2882                } catch (InstallerException e) {
2883                    Slog.w(TAG, "Trouble fixing GIDs", e);
2884                }
2885                traceLog.traceEnd();
2886
2887                traceLog.traceBegin("AppDataPrepare");
2888                if (deferPackages == null || deferPackages.isEmpty()) {
2889                    return;
2890                }
2891                int count = 0;
2892                for (String pkgName : deferPackages) {
2893                    PackageParser.Package pkg = null;
2894                    synchronized (mPackages) {
2895                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2896                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2897                            pkg = ps.pkg;
2898                        }
2899                    }
2900                    if (pkg != null) {
2901                        synchronized (mInstallLock) {
2902                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2903                                    true /* maybeMigrateAppData */);
2904                        }
2905                        count++;
2906                    }
2907                }
2908                traceLog.traceEnd();
2909                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2910            }, "prepareAppData");
2911
2912            // If this is first boot after an OTA, and a normal boot, then
2913            // we need to clear code cache directories.
2914            // Note that we do *not* clear the application profiles. These remain valid
2915            // across OTAs and are used to drive profile verification (post OTA) and
2916            // profile compilation (without waiting to collect a fresh set of profiles).
2917            if (mIsUpgrade && !onlyCore) {
2918                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2919                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2920                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2921                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2922                        // No apps are running this early, so no need to freeze
2923                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2924                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2925                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2926                    }
2927                }
2928                ver.fingerprint = Build.FINGERPRINT;
2929            }
2930
2931            checkDefaultBrowser();
2932
2933            // clear only after permissions and other defaults have been updated
2934            mExistingSystemPackages.clear();
2935            mPromoteSystemApps = false;
2936
2937            // All the changes are done during package scanning.
2938            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2939
2940            // can downgrade to reader
2941            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2942            mSettings.writeLPr();
2943            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2944
2945            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2946                    SystemClock.uptimeMillis());
2947
2948            if (!mOnlyCore) {
2949                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2950                mRequiredInstallerPackage = getRequiredInstallerLPr();
2951                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2952                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2953                if (mIntentFilterVerifierComponent != null) {
2954                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2955                            mIntentFilterVerifierComponent);
2956                } else {
2957                    mIntentFilterVerifier = null;
2958                }
2959                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2960                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2961                        SharedLibraryInfo.VERSION_UNDEFINED);
2962                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2963                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2964                        SharedLibraryInfo.VERSION_UNDEFINED);
2965            } else {
2966                mRequiredVerifierPackage = null;
2967                mRequiredInstallerPackage = null;
2968                mRequiredUninstallerPackage = null;
2969                mIntentFilterVerifierComponent = null;
2970                mIntentFilterVerifier = null;
2971                mServicesSystemSharedLibraryPackageName = null;
2972                mSharedSystemSharedLibraryPackageName = null;
2973            }
2974
2975            mInstallerService = new PackageInstallerService(context, this);
2976            final Pair<ComponentName, String> instantAppResolverComponent =
2977                    getInstantAppResolverLPr();
2978            if (instantAppResolverComponent != null) {
2979                if (DEBUG_EPHEMERAL) {
2980                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2981                }
2982                mInstantAppResolverConnection = new EphemeralResolverConnection(
2983                        mContext, instantAppResolverComponent.first,
2984                        instantAppResolverComponent.second);
2985                mInstantAppResolverSettingsComponent =
2986                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2987            } else {
2988                mInstantAppResolverConnection = null;
2989                mInstantAppResolverSettingsComponent = null;
2990            }
2991            updateInstantAppInstallerLocked(null);
2992
2993            // Read and update the usage of dex files.
2994            // Do this at the end of PM init so that all the packages have their
2995            // data directory reconciled.
2996            // At this point we know the code paths of the packages, so we can validate
2997            // the disk file and build the internal cache.
2998            // The usage file is expected to be small so loading and verifying it
2999            // should take a fairly small time compare to the other activities (e.g. package
3000            // scanning).
3001            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3002            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3003            for (int userId : currentUserIds) {
3004                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3005            }
3006            mDexManager.load(userPackages);
3007        } // synchronized (mPackages)
3008        } // synchronized (mInstallLock)
3009
3010        // Now after opening every single application zip, make sure they
3011        // are all flushed.  Not really needed, but keeps things nice and
3012        // tidy.
3013        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3014        Runtime.getRuntime().gc();
3015        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3016
3017        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3018        FallbackCategoryProvider.loadFallbacks();
3019        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3020
3021        // The initial scanning above does many calls into installd while
3022        // holding the mPackages lock, but we're mostly interested in yelling
3023        // once we have a booted system.
3024        mInstaller.setWarnIfHeld(mPackages);
3025
3026        // Expose private service for system components to use.
3027        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3028        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3029    }
3030
3031    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3032        // we're only interested in updating the installer appliction when 1) it's not
3033        // already set or 2) the modified package is the installer
3034        if (mInstantAppInstallerActivity != null
3035                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3036                        .equals(modifiedPackage)) {
3037            return;
3038        }
3039        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3040    }
3041
3042    private static File preparePackageParserCache(boolean isUpgrade) {
3043        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3044            return null;
3045        }
3046
3047        // Disable package parsing on eng builds to allow for faster incremental development.
3048        if ("eng".equals(Build.TYPE)) {
3049            return null;
3050        }
3051
3052        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3053            Slog.i(TAG, "Disabling package parser cache due to system property.");
3054            return null;
3055        }
3056
3057        // The base directory for the package parser cache lives under /data/system/.
3058        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3059                "package_cache");
3060        if (cacheBaseDir == null) {
3061            return null;
3062        }
3063
3064        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3065        // This also serves to "GC" unused entries when the package cache version changes (which
3066        // can only happen during upgrades).
3067        if (isUpgrade) {
3068            FileUtils.deleteContents(cacheBaseDir);
3069        }
3070
3071
3072        // Return the versioned package cache directory. This is something like
3073        // "/data/system/package_cache/1"
3074        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3075
3076        // The following is a workaround to aid development on non-numbered userdebug
3077        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3078        // the system partition is newer.
3079        //
3080        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3081        // that starts with "eng." to signify that this is an engineering build and not
3082        // destined for release.
3083        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3084            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3085
3086            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3087            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3088            // in general and should not be used for production changes. In this specific case,
3089            // we know that they will work.
3090            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3091            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3092                FileUtils.deleteContents(cacheBaseDir);
3093                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3094            }
3095        }
3096
3097        return cacheDir;
3098    }
3099
3100    @Override
3101    public boolean isFirstBoot() {
3102        // allow instant applications
3103        return mFirstBoot;
3104    }
3105
3106    @Override
3107    public boolean isOnlyCoreApps() {
3108        // allow instant applications
3109        return mOnlyCore;
3110    }
3111
3112    @Override
3113    public boolean isUpgrade() {
3114        // allow instant applications
3115        return mIsUpgrade;
3116    }
3117
3118    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3119        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3120
3121        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3122                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3123                UserHandle.USER_SYSTEM);
3124        if (matches.size() == 1) {
3125            return matches.get(0).getComponentInfo().packageName;
3126        } else if (matches.size() == 0) {
3127            Log.e(TAG, "There should probably be a verifier, but, none were found");
3128            return null;
3129        }
3130        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3131    }
3132
3133    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3134        synchronized (mPackages) {
3135            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3136            if (libraryEntry == null) {
3137                throw new IllegalStateException("Missing required shared library:" + name);
3138            }
3139            return libraryEntry.apk;
3140        }
3141    }
3142
3143    private @NonNull String getRequiredInstallerLPr() {
3144        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3145        intent.addCategory(Intent.CATEGORY_DEFAULT);
3146        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3147
3148        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3149                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3150                UserHandle.USER_SYSTEM);
3151        if (matches.size() == 1) {
3152            ResolveInfo resolveInfo = matches.get(0);
3153            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3154                throw new RuntimeException("The installer must be a privileged app");
3155            }
3156            return matches.get(0).getComponentInfo().packageName;
3157        } else {
3158            throw new RuntimeException("There must be exactly one installer; found " + matches);
3159        }
3160    }
3161
3162    private @NonNull String getRequiredUninstallerLPr() {
3163        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3164        intent.addCategory(Intent.CATEGORY_DEFAULT);
3165        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3166
3167        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3168                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3169                UserHandle.USER_SYSTEM);
3170        if (resolveInfo == null ||
3171                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3172            throw new RuntimeException("There must be exactly one uninstaller; found "
3173                    + resolveInfo);
3174        }
3175        return resolveInfo.getComponentInfo().packageName;
3176    }
3177
3178    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3179        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3180
3181        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3182                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3183                UserHandle.USER_SYSTEM);
3184        ResolveInfo best = null;
3185        final int N = matches.size();
3186        for (int i = 0; i < N; i++) {
3187            final ResolveInfo cur = matches.get(i);
3188            final String packageName = cur.getComponentInfo().packageName;
3189            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3190                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3191                continue;
3192            }
3193
3194            if (best == null || cur.priority > best.priority) {
3195                best = cur;
3196            }
3197        }
3198
3199        if (best != null) {
3200            return best.getComponentInfo().getComponentName();
3201        }
3202        Slog.w(TAG, "Intent filter verifier not found");
3203        return null;
3204    }
3205
3206    @Override
3207    public @Nullable ComponentName getInstantAppResolverComponent() {
3208        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3209            return null;
3210        }
3211        synchronized (mPackages) {
3212            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3213            if (instantAppResolver == null) {
3214                return null;
3215            }
3216            return instantAppResolver.first;
3217        }
3218    }
3219
3220    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3221        final String[] packageArray =
3222                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3223        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3224            if (DEBUG_EPHEMERAL) {
3225                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3226            }
3227            return null;
3228        }
3229
3230        final int callingUid = Binder.getCallingUid();
3231        final int resolveFlags =
3232                MATCH_DIRECT_BOOT_AWARE
3233                | MATCH_DIRECT_BOOT_UNAWARE
3234                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3235        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3236        final Intent resolverIntent = new Intent(actionName);
3237        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3238                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3239        // temporarily look for the old action
3240        if (resolvers.size() == 0) {
3241            if (DEBUG_EPHEMERAL) {
3242                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3243            }
3244            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3245            resolverIntent.setAction(actionName);
3246            resolvers = queryIntentServicesInternal(resolverIntent, null,
3247                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3248        }
3249        final int N = resolvers.size();
3250        if (N == 0) {
3251            if (DEBUG_EPHEMERAL) {
3252                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3253            }
3254            return null;
3255        }
3256
3257        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3258        for (int i = 0; i < N; i++) {
3259            final ResolveInfo info = resolvers.get(i);
3260
3261            if (info.serviceInfo == null) {
3262                continue;
3263            }
3264
3265            final String packageName = info.serviceInfo.packageName;
3266            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3267                if (DEBUG_EPHEMERAL) {
3268                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3269                            + " pkg: " + packageName + ", info:" + info);
3270                }
3271                continue;
3272            }
3273
3274            if (DEBUG_EPHEMERAL) {
3275                Slog.v(TAG, "Ephemeral resolver found;"
3276                        + " pkg: " + packageName + ", info:" + info);
3277            }
3278            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3279        }
3280        if (DEBUG_EPHEMERAL) {
3281            Slog.v(TAG, "Ephemeral resolver NOT found");
3282        }
3283        return null;
3284    }
3285
3286    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3287        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3288        intent.addCategory(Intent.CATEGORY_DEFAULT);
3289        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3290
3291        final int resolveFlags =
3292                MATCH_DIRECT_BOOT_AWARE
3293                | MATCH_DIRECT_BOOT_UNAWARE
3294                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3295        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3296                resolveFlags, UserHandle.USER_SYSTEM);
3297        // temporarily look for the old action
3298        if (matches.isEmpty()) {
3299            if (DEBUG_EPHEMERAL) {
3300                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3301            }
3302            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3303            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3304                    resolveFlags, UserHandle.USER_SYSTEM);
3305        }
3306        Iterator<ResolveInfo> iter = matches.iterator();
3307        while (iter.hasNext()) {
3308            final ResolveInfo rInfo = iter.next();
3309            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3310            if (ps != null) {
3311                final PermissionsState permissionsState = ps.getPermissionsState();
3312                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3313                    continue;
3314                }
3315            }
3316            iter.remove();
3317        }
3318        if (matches.size() == 0) {
3319            return null;
3320        } else if (matches.size() == 1) {
3321            return (ActivityInfo) matches.get(0).getComponentInfo();
3322        } else {
3323            throw new RuntimeException(
3324                    "There must be at most one ephemeral installer; found " + matches);
3325        }
3326    }
3327
3328    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3329            @NonNull ComponentName resolver) {
3330        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3331                .addCategory(Intent.CATEGORY_DEFAULT)
3332                .setPackage(resolver.getPackageName());
3333        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3334        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3335                UserHandle.USER_SYSTEM);
3336        // temporarily look for the old action
3337        if (matches.isEmpty()) {
3338            if (DEBUG_EPHEMERAL) {
3339                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3340            }
3341            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3342            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3343                    UserHandle.USER_SYSTEM);
3344        }
3345        if (matches.isEmpty()) {
3346            return null;
3347        }
3348        return matches.get(0).getComponentInfo().getComponentName();
3349    }
3350
3351    private void primeDomainVerificationsLPw(int userId) {
3352        if (DEBUG_DOMAIN_VERIFICATION) {
3353            Slog.d(TAG, "Priming domain verifications in user " + userId);
3354        }
3355
3356        SystemConfig systemConfig = SystemConfig.getInstance();
3357        ArraySet<String> packages = systemConfig.getLinkedApps();
3358
3359        for (String packageName : packages) {
3360            PackageParser.Package pkg = mPackages.get(packageName);
3361            if (pkg != null) {
3362                if (!pkg.isSystemApp()) {
3363                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3364                    continue;
3365                }
3366
3367                ArraySet<String> domains = null;
3368                for (PackageParser.Activity a : pkg.activities) {
3369                    for (ActivityIntentInfo filter : a.intents) {
3370                        if (hasValidDomains(filter)) {
3371                            if (domains == null) {
3372                                domains = new ArraySet<String>();
3373                            }
3374                            domains.addAll(filter.getHostsList());
3375                        }
3376                    }
3377                }
3378
3379                if (domains != null && domains.size() > 0) {
3380                    if (DEBUG_DOMAIN_VERIFICATION) {
3381                        Slog.v(TAG, "      + " + packageName);
3382                    }
3383                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3384                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3385                    // and then 'always' in the per-user state actually used for intent resolution.
3386                    final IntentFilterVerificationInfo ivi;
3387                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3388                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3389                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3390                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3391                } else {
3392                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3393                            + "' does not handle web links");
3394                }
3395            } else {
3396                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3397            }
3398        }
3399
3400        scheduleWritePackageRestrictionsLocked(userId);
3401        scheduleWriteSettingsLocked();
3402    }
3403
3404    private void applyFactoryDefaultBrowserLPw(int userId) {
3405        // The default browser app's package name is stored in a string resource,
3406        // with a product-specific overlay used for vendor customization.
3407        String browserPkg = mContext.getResources().getString(
3408                com.android.internal.R.string.default_browser);
3409        if (!TextUtils.isEmpty(browserPkg)) {
3410            // non-empty string => required to be a known package
3411            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3412            if (ps == null) {
3413                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3414                browserPkg = null;
3415            } else {
3416                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3417            }
3418        }
3419
3420        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3421        // default.  If there's more than one, just leave everything alone.
3422        if (browserPkg == null) {
3423            calculateDefaultBrowserLPw(userId);
3424        }
3425    }
3426
3427    private void calculateDefaultBrowserLPw(int userId) {
3428        List<String> allBrowsers = resolveAllBrowserApps(userId);
3429        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3430        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3431    }
3432
3433    private List<String> resolveAllBrowserApps(int userId) {
3434        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3435        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3436                PackageManager.MATCH_ALL, userId);
3437
3438        final int count = list.size();
3439        List<String> result = new ArrayList<String>(count);
3440        for (int i=0; i<count; i++) {
3441            ResolveInfo info = list.get(i);
3442            if (info.activityInfo == null
3443                    || !info.handleAllWebDataURI
3444                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3445                    || result.contains(info.activityInfo.packageName)) {
3446                continue;
3447            }
3448            result.add(info.activityInfo.packageName);
3449        }
3450
3451        return result;
3452    }
3453
3454    private boolean packageIsBrowser(String packageName, int userId) {
3455        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3456                PackageManager.MATCH_ALL, userId);
3457        final int N = list.size();
3458        for (int i = 0; i < N; i++) {
3459            ResolveInfo info = list.get(i);
3460            if (packageName.equals(info.activityInfo.packageName)) {
3461                return true;
3462            }
3463        }
3464        return false;
3465    }
3466
3467    private void checkDefaultBrowser() {
3468        final int myUserId = UserHandle.myUserId();
3469        final String packageName = getDefaultBrowserPackageName(myUserId);
3470        if (packageName != null) {
3471            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3472            if (info == null) {
3473                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3474                synchronized (mPackages) {
3475                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3476                }
3477            }
3478        }
3479    }
3480
3481    @Override
3482    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3483            throws RemoteException {
3484        try {
3485            return super.onTransact(code, data, reply, flags);
3486        } catch (RuntimeException e) {
3487            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3488                Slog.wtf(TAG, "Package Manager Crash", e);
3489            }
3490            throw e;
3491        }
3492    }
3493
3494    static int[] appendInts(int[] cur, int[] add) {
3495        if (add == null) return cur;
3496        if (cur == null) return add;
3497        final int N = add.length;
3498        for (int i=0; i<N; i++) {
3499            cur = appendInt(cur, add[i]);
3500        }
3501        return cur;
3502    }
3503
3504    /**
3505     * Returns whether or not a full application can see an instant application.
3506     * <p>
3507     * Currently, there are three cases in which this can occur:
3508     * <ol>
3509     * <li>The calling application is a "special" process. The special
3510     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3511     *     and {@code 0}</li>
3512     * <li>The calling application has the permission
3513     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3514     * <li>The calling application is the default launcher on the
3515     *     system partition.</li>
3516     * </ol>
3517     */
3518    private boolean canViewInstantApps(int callingUid, int userId) {
3519        if (callingUid == Process.SYSTEM_UID
3520                || callingUid == Process.SHELL_UID
3521                || callingUid == Process.ROOT_UID) {
3522            return true;
3523        }
3524        if (mContext.checkCallingOrSelfPermission(
3525                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3526            return true;
3527        }
3528        if (mContext.checkCallingOrSelfPermission(
3529                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3530            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3531            if (homeComponent != null
3532                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3533                return true;
3534            }
3535        }
3536        return false;
3537    }
3538
3539    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3540        if (!sUserManager.exists(userId)) return null;
3541        if (ps == null) {
3542            return null;
3543        }
3544        PackageParser.Package p = ps.pkg;
3545        if (p == null) {
3546            return null;
3547        }
3548        final int callingUid = Binder.getCallingUid();
3549        // Filter out ephemeral app metadata:
3550        //   * The system/shell/root can see metadata for any app
3551        //   * An installed app can see metadata for 1) other installed apps
3552        //     and 2) ephemeral apps that have explicitly interacted with it
3553        //   * Ephemeral apps can only see their own data and exposed installed apps
3554        //   * Holding a signature permission allows seeing instant apps
3555        if (filterAppAccessLPr(ps, callingUid, userId)) {
3556            return null;
3557        }
3558
3559        final PermissionsState permissionsState = ps.getPermissionsState();
3560
3561        // Compute GIDs only if requested
3562        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3563                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3564        // Compute granted permissions only if package has requested permissions
3565        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3566                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3567        final PackageUserState state = ps.readUserState(userId);
3568
3569        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3570                && ps.isSystem()) {
3571            flags |= MATCH_ANY_USER;
3572        }
3573
3574        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3575                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3576
3577        if (packageInfo == null) {
3578            return null;
3579        }
3580
3581        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3582                resolveExternalPackageNameLPr(p);
3583
3584        return packageInfo;
3585    }
3586
3587    @Override
3588    public void checkPackageStartable(String packageName, int userId) {
3589        final int callingUid = Binder.getCallingUid();
3590        if (getInstantAppPackageName(callingUid) != null) {
3591            throw new SecurityException("Instant applications don't have access to this method");
3592        }
3593        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3594        synchronized (mPackages) {
3595            final PackageSetting ps = mSettings.mPackages.get(packageName);
3596            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3597                throw new SecurityException("Package " + packageName + " was not found!");
3598            }
3599
3600            if (!ps.getInstalled(userId)) {
3601                throw new SecurityException(
3602                        "Package " + packageName + " was not installed for user " + userId + "!");
3603            }
3604
3605            if (mSafeMode && !ps.isSystem()) {
3606                throw new SecurityException("Package " + packageName + " not a system app!");
3607            }
3608
3609            if (mFrozenPackages.contains(packageName)) {
3610                throw new SecurityException("Package " + packageName + " is currently frozen!");
3611            }
3612
3613            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3614                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3615                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3616            }
3617        }
3618    }
3619
3620    @Override
3621    public boolean isPackageAvailable(String packageName, int userId) {
3622        if (!sUserManager.exists(userId)) return false;
3623        final int callingUid = Binder.getCallingUid();
3624        enforceCrossUserPermission(callingUid, userId,
3625                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3626        synchronized (mPackages) {
3627            PackageParser.Package p = mPackages.get(packageName);
3628            if (p != null) {
3629                final PackageSetting ps = (PackageSetting) p.mExtras;
3630                if (filterAppAccessLPr(ps, callingUid, userId)) {
3631                    return false;
3632                }
3633                if (ps != null) {
3634                    final PackageUserState state = ps.readUserState(userId);
3635                    if (state != null) {
3636                        return PackageParser.isAvailable(state);
3637                    }
3638                }
3639            }
3640        }
3641        return false;
3642    }
3643
3644    @Override
3645    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3646        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3647                flags, Binder.getCallingUid(), userId);
3648    }
3649
3650    @Override
3651    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3652            int flags, int userId) {
3653        return getPackageInfoInternal(versionedPackage.getPackageName(),
3654                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3655    }
3656
3657    /**
3658     * Important: The provided filterCallingUid is used exclusively to filter out packages
3659     * that can be seen based on user state. It's typically the original caller uid prior
3660     * to clearing. Because it can only be provided by trusted code, it's value can be
3661     * trusted and will be used as-is; unlike userId which will be validated by this method.
3662     */
3663    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3664            int flags, int filterCallingUid, int userId) {
3665        if (!sUserManager.exists(userId)) return null;
3666        flags = updateFlagsForPackage(flags, userId, packageName);
3667        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3668                false /* requireFullPermission */, false /* checkShell */, "get package info");
3669
3670        // reader
3671        synchronized (mPackages) {
3672            // Normalize package name to handle renamed packages and static libs
3673            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3674
3675            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3676            if (matchFactoryOnly) {
3677                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3678                if (ps != null) {
3679                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3680                        return null;
3681                    }
3682                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3683                        return null;
3684                    }
3685                    return generatePackageInfo(ps, flags, userId);
3686                }
3687            }
3688
3689            PackageParser.Package p = mPackages.get(packageName);
3690            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3691                return null;
3692            }
3693            if (DEBUG_PACKAGE_INFO)
3694                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3695            if (p != null) {
3696                final PackageSetting ps = (PackageSetting) p.mExtras;
3697                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3698                    return null;
3699                }
3700                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3701                    return null;
3702                }
3703                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3704            }
3705            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3706                final PackageSetting ps = mSettings.mPackages.get(packageName);
3707                if (ps == null) return null;
3708                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3709                    return null;
3710                }
3711                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3712                    return null;
3713                }
3714                return generatePackageInfo(ps, flags, userId);
3715            }
3716        }
3717        return null;
3718    }
3719
3720    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3721        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3722            return true;
3723        }
3724        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3725            return true;
3726        }
3727        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3728            return true;
3729        }
3730        return false;
3731    }
3732
3733    private boolean isComponentVisibleToInstantApp(
3734            @Nullable ComponentName component, @ComponentType int type) {
3735        if (type == TYPE_ACTIVITY) {
3736            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3737            return activity != null
3738                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3739                    : false;
3740        } else if (type == TYPE_RECEIVER) {
3741            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3742            return activity != null
3743                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3744                    : false;
3745        } else if (type == TYPE_SERVICE) {
3746            final PackageParser.Service service = mServices.mServices.get(component);
3747            return service != null
3748                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3749                    : false;
3750        } else if (type == TYPE_PROVIDER) {
3751            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3752            return provider != null
3753                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3754                    : false;
3755        } else if (type == TYPE_UNKNOWN) {
3756            return isComponentVisibleToInstantApp(component);
3757        }
3758        return false;
3759    }
3760
3761    /**
3762     * Returns whether or not access to the application should be filtered.
3763     * <p>
3764     * Access may be limited based upon whether the calling or target applications
3765     * are instant applications.
3766     *
3767     * @see #canAccessInstantApps(int)
3768     */
3769    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3770            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3771        // if we're in an isolated process, get the real calling UID
3772        if (Process.isIsolated(callingUid)) {
3773            callingUid = mIsolatedOwners.get(callingUid);
3774        }
3775        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3776        final boolean callerIsInstantApp = instantAppPkgName != null;
3777        if (ps == null) {
3778            if (callerIsInstantApp) {
3779                // pretend the application exists, but, needs to be filtered
3780                return true;
3781            }
3782            return false;
3783        }
3784        // if the target and caller are the same application, don't filter
3785        if (isCallerSameApp(ps.name, callingUid)) {
3786            return false;
3787        }
3788        if (callerIsInstantApp) {
3789            // request for a specific component; if it hasn't been explicitly exposed, filter
3790            if (component != null) {
3791                return !isComponentVisibleToInstantApp(component, componentType);
3792            }
3793            // request for application; if no components have been explicitly exposed, filter
3794            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3795        }
3796        if (ps.getInstantApp(userId)) {
3797            // caller can see all components of all instant applications, don't filter
3798            if (canViewInstantApps(callingUid, userId)) {
3799                return false;
3800            }
3801            // request for a specific instant application component, filter
3802            if (component != null) {
3803                return true;
3804            }
3805            // request for an instant application; if the caller hasn't been granted access, filter
3806            return !mInstantAppRegistry.isInstantAccessGranted(
3807                    userId, UserHandle.getAppId(callingUid), ps.appId);
3808        }
3809        return false;
3810    }
3811
3812    /**
3813     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3814     */
3815    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3816        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3817    }
3818
3819    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3820            int flags) {
3821        // Callers can access only the libs they depend on, otherwise they need to explicitly
3822        // ask for the shared libraries given the caller is allowed to access all static libs.
3823        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3824            // System/shell/root get to see all static libs
3825            final int appId = UserHandle.getAppId(uid);
3826            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3827                    || appId == Process.ROOT_UID) {
3828                return false;
3829            }
3830        }
3831
3832        // No package means no static lib as it is always on internal storage
3833        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3834            return false;
3835        }
3836
3837        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3838                ps.pkg.staticSharedLibVersion);
3839        if (libEntry == null) {
3840            return false;
3841        }
3842
3843        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3844        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3845        if (uidPackageNames == null) {
3846            return true;
3847        }
3848
3849        for (String uidPackageName : uidPackageNames) {
3850            if (ps.name.equals(uidPackageName)) {
3851                return false;
3852            }
3853            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3854            if (uidPs != null) {
3855                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3856                        libEntry.info.getName());
3857                if (index < 0) {
3858                    continue;
3859                }
3860                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3861                    return false;
3862                }
3863            }
3864        }
3865        return true;
3866    }
3867
3868    @Override
3869    public String[] currentToCanonicalPackageNames(String[] names) {
3870        final int callingUid = Binder.getCallingUid();
3871        if (getInstantAppPackageName(callingUid) != null) {
3872            return names;
3873        }
3874        final String[] out = new String[names.length];
3875        // reader
3876        synchronized (mPackages) {
3877            final int callingUserId = UserHandle.getUserId(callingUid);
3878            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3879            for (int i=names.length-1; i>=0; i--) {
3880                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3881                boolean translateName = false;
3882                if (ps != null && ps.realName != null) {
3883                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3884                    translateName = !targetIsInstantApp
3885                            || canViewInstantApps
3886                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3887                                    UserHandle.getAppId(callingUid), ps.appId);
3888                }
3889                out[i] = translateName ? ps.realName : names[i];
3890            }
3891        }
3892        return out;
3893    }
3894
3895    @Override
3896    public String[] canonicalToCurrentPackageNames(String[] names) {
3897        final int callingUid = Binder.getCallingUid();
3898        if (getInstantAppPackageName(callingUid) != null) {
3899            return names;
3900        }
3901        final String[] out = new String[names.length];
3902        // reader
3903        synchronized (mPackages) {
3904            final int callingUserId = UserHandle.getUserId(callingUid);
3905            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3906            for (int i=names.length-1; i>=0; i--) {
3907                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3908                boolean translateName = false;
3909                if (cur != null) {
3910                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3911                    final boolean targetIsInstantApp =
3912                            ps != null && ps.getInstantApp(callingUserId);
3913                    translateName = !targetIsInstantApp
3914                            || canViewInstantApps
3915                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3916                                    UserHandle.getAppId(callingUid), ps.appId);
3917                }
3918                out[i] = translateName ? cur : names[i];
3919            }
3920        }
3921        return out;
3922    }
3923
3924    @Override
3925    public int getPackageUid(String packageName, int flags, int userId) {
3926        if (!sUserManager.exists(userId)) return -1;
3927        final int callingUid = Binder.getCallingUid();
3928        flags = updateFlagsForPackage(flags, userId, packageName);
3929        enforceCrossUserPermission(callingUid, userId,
3930                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3931
3932        // reader
3933        synchronized (mPackages) {
3934            final PackageParser.Package p = mPackages.get(packageName);
3935            if (p != null && p.isMatch(flags)) {
3936                PackageSetting ps = (PackageSetting) p.mExtras;
3937                if (filterAppAccessLPr(ps, callingUid, userId)) {
3938                    return -1;
3939                }
3940                return UserHandle.getUid(userId, p.applicationInfo.uid);
3941            }
3942            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3943                final PackageSetting ps = mSettings.mPackages.get(packageName);
3944                if (ps != null && ps.isMatch(flags)
3945                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3946                    return UserHandle.getUid(userId, ps.appId);
3947                }
3948            }
3949        }
3950
3951        return -1;
3952    }
3953
3954    @Override
3955    public int[] getPackageGids(String packageName, int flags, int userId) {
3956        if (!sUserManager.exists(userId)) return null;
3957        final int callingUid = Binder.getCallingUid();
3958        flags = updateFlagsForPackage(flags, userId, packageName);
3959        enforceCrossUserPermission(callingUid, userId,
3960                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3961
3962        // reader
3963        synchronized (mPackages) {
3964            final PackageParser.Package p = mPackages.get(packageName);
3965            if (p != null && p.isMatch(flags)) {
3966                PackageSetting ps = (PackageSetting) p.mExtras;
3967                if (filterAppAccessLPr(ps, callingUid, userId)) {
3968                    return null;
3969                }
3970                // TODO: Shouldn't this be checking for package installed state for userId and
3971                // return null?
3972                return ps.getPermissionsState().computeGids(userId);
3973            }
3974            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3975                final PackageSetting ps = mSettings.mPackages.get(packageName);
3976                if (ps != null && ps.isMatch(flags)
3977                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3978                    return ps.getPermissionsState().computeGids(userId);
3979                }
3980            }
3981        }
3982
3983        return null;
3984    }
3985
3986    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3987        if (bp.perm != null) {
3988            return PackageParser.generatePermissionInfo(bp.perm, flags);
3989        }
3990        PermissionInfo pi = new PermissionInfo();
3991        pi.name = bp.name;
3992        pi.packageName = bp.sourcePackage;
3993        pi.nonLocalizedLabel = bp.name;
3994        pi.protectionLevel = bp.protectionLevel;
3995        return pi;
3996    }
3997
3998    @Override
3999    public PermissionInfo getPermissionInfo(String name, int flags) {
4000        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4001            return null;
4002        }
4003        // reader
4004        synchronized (mPackages) {
4005            final BasePermission p = mSettings.mPermissions.get(name);
4006            if (p != null) {
4007                return generatePermissionInfo(p, flags);
4008            }
4009            return null;
4010        }
4011    }
4012
4013    @Override
4014    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4015            int flags) {
4016        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4017            return null;
4018        }
4019        // reader
4020        synchronized (mPackages) {
4021            if (group != null && !mPermissionGroups.containsKey(group)) {
4022                // This is thrown as NameNotFoundException
4023                return null;
4024            }
4025
4026            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4027            for (BasePermission p : mSettings.mPermissions.values()) {
4028                if (group == null) {
4029                    if (p.perm == null || p.perm.info.group == null) {
4030                        out.add(generatePermissionInfo(p, flags));
4031                    }
4032                } else {
4033                    if (p.perm != null && group.equals(p.perm.info.group)) {
4034                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4035                    }
4036                }
4037            }
4038            return new ParceledListSlice<>(out);
4039        }
4040    }
4041
4042    @Override
4043    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4044        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4045            return null;
4046        }
4047        // reader
4048        synchronized (mPackages) {
4049            return PackageParser.generatePermissionGroupInfo(
4050                    mPermissionGroups.get(name), flags);
4051        }
4052    }
4053
4054    @Override
4055    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4056        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4057            return ParceledListSlice.emptyList();
4058        }
4059        // reader
4060        synchronized (mPackages) {
4061            final int N = mPermissionGroups.size();
4062            ArrayList<PermissionGroupInfo> out
4063                    = new ArrayList<PermissionGroupInfo>(N);
4064            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4065                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4066            }
4067            return new ParceledListSlice<>(out);
4068        }
4069    }
4070
4071    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4072            int filterCallingUid, int userId) {
4073        if (!sUserManager.exists(userId)) return null;
4074        PackageSetting ps = mSettings.mPackages.get(packageName);
4075        if (ps != null) {
4076            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4077                return null;
4078            }
4079            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4080                return null;
4081            }
4082            if (ps.pkg == null) {
4083                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4084                if (pInfo != null) {
4085                    return pInfo.applicationInfo;
4086                }
4087                return null;
4088            }
4089            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4090                    ps.readUserState(userId), userId);
4091            if (ai != null) {
4092                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4093            }
4094            return ai;
4095        }
4096        return null;
4097    }
4098
4099    @Override
4100    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4101        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4102    }
4103
4104    /**
4105     * Important: The provided filterCallingUid is used exclusively to filter out applications
4106     * that can be seen based on user state. It's typically the original caller uid prior
4107     * to clearing. Because it can only be provided by trusted code, it's value can be
4108     * trusted and will be used as-is; unlike userId which will be validated by this method.
4109     */
4110    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4111            int filterCallingUid, int userId) {
4112        if (!sUserManager.exists(userId)) return null;
4113        flags = updateFlagsForApplication(flags, userId, packageName);
4114        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4115                false /* requireFullPermission */, false /* checkShell */, "get application info");
4116
4117        // writer
4118        synchronized (mPackages) {
4119            // Normalize package name to handle renamed packages and static libs
4120            packageName = resolveInternalPackageNameLPr(packageName,
4121                    PackageManager.VERSION_CODE_HIGHEST);
4122
4123            PackageParser.Package p = mPackages.get(packageName);
4124            if (DEBUG_PACKAGE_INFO) Log.v(
4125                    TAG, "getApplicationInfo " + packageName
4126                    + ": " + p);
4127            if (p != null) {
4128                PackageSetting ps = mSettings.mPackages.get(packageName);
4129                if (ps == null) return null;
4130                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4131                    return null;
4132                }
4133                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4134                    return null;
4135                }
4136                // Note: isEnabledLP() does not apply here - always return info
4137                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4138                        p, flags, ps.readUserState(userId), userId);
4139                if (ai != null) {
4140                    ai.packageName = resolveExternalPackageNameLPr(p);
4141                }
4142                return ai;
4143            }
4144            if ("android".equals(packageName)||"system".equals(packageName)) {
4145                return mAndroidApplication;
4146            }
4147            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4148                // Already generates the external package name
4149                return generateApplicationInfoFromSettingsLPw(packageName,
4150                        flags, filterCallingUid, userId);
4151            }
4152        }
4153        return null;
4154    }
4155
4156    private String normalizePackageNameLPr(String packageName) {
4157        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4158        return normalizedPackageName != null ? normalizedPackageName : packageName;
4159    }
4160
4161    @Override
4162    public void deletePreloadsFileCache() {
4163        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4164            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4165        }
4166        File dir = Environment.getDataPreloadsFileCacheDirectory();
4167        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4168        FileUtils.deleteContents(dir);
4169    }
4170
4171    @Override
4172    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4173            final int storageFlags, final IPackageDataObserver observer) {
4174        mContext.enforceCallingOrSelfPermission(
4175                android.Manifest.permission.CLEAR_APP_CACHE, null);
4176        mHandler.post(() -> {
4177            boolean success = false;
4178            try {
4179                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4180                success = true;
4181            } catch (IOException e) {
4182                Slog.w(TAG, e);
4183            }
4184            if (observer != null) {
4185                try {
4186                    observer.onRemoveCompleted(null, success);
4187                } catch (RemoteException e) {
4188                    Slog.w(TAG, e);
4189                }
4190            }
4191        });
4192    }
4193
4194    @Override
4195    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4196            final int storageFlags, final IntentSender pi) {
4197        mContext.enforceCallingOrSelfPermission(
4198                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4199        mHandler.post(() -> {
4200            boolean success = false;
4201            try {
4202                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4203                success = true;
4204            } catch (IOException e) {
4205                Slog.w(TAG, e);
4206            }
4207            if (pi != null) {
4208                try {
4209                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4210                } catch (SendIntentException e) {
4211                    Slog.w(TAG, e);
4212                }
4213            }
4214        });
4215    }
4216
4217    /**
4218     * Blocking call to clear various types of cached data across the system
4219     * until the requested bytes are available.
4220     */
4221    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4222        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4223        final File file = storage.findPathForUuid(volumeUuid);
4224        if (file.getUsableSpace() >= bytes) return;
4225
4226        if (ENABLE_FREE_CACHE_V2) {
4227            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4228                    volumeUuid);
4229            final boolean aggressive = (storageFlags
4230                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4231            final boolean defyReserved = (storageFlags
4232                    & StorageManager.FLAG_ALLOCATE_DEFY_RESERVED) != 0;
4233            final long reservedBytes = (aggressive || defyReserved) ? 0
4234                    : storage.getStorageCacheBytes(file);
4235
4236            // 1. Pre-flight to determine if we have any chance to succeed
4237            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4238            if (internalVolume && (aggressive || SystemProperties
4239                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4240                deletePreloadsFileCache();
4241                if (file.getUsableSpace() >= bytes) return;
4242            }
4243
4244            // 3. Consider parsed APK data (aggressive only)
4245            if (internalVolume && aggressive) {
4246                FileUtils.deleteContents(mCacheDir);
4247                if (file.getUsableSpace() >= bytes) return;
4248            }
4249
4250            // 4. Consider cached app data (above quotas)
4251            try {
4252                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4253                        Installer.FLAG_FREE_CACHE_V2);
4254            } catch (InstallerException ignored) {
4255            }
4256            if (file.getUsableSpace() >= bytes) return;
4257
4258            // 5. Consider shared libraries with refcount=0 and age>min cache period
4259            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4260                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4261                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4262                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4263                return;
4264            }
4265
4266            // 6. Consider dexopt output (aggressive only)
4267            // TODO: Implement
4268
4269            // 7. Consider installed instant apps unused longer than min cache period
4270            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4271                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4272                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4273                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4274                return;
4275            }
4276
4277            // 8. Consider cached app data (below quotas)
4278            try {
4279                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4280                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4281            } catch (InstallerException ignored) {
4282            }
4283            if (file.getUsableSpace() >= bytes) return;
4284
4285            // 9. Consider DropBox entries
4286            // TODO: Implement
4287
4288            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4289            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4290                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4291                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4292                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4293                return;
4294            }
4295        } else {
4296            try {
4297                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4298            } catch (InstallerException ignored) {
4299            }
4300            if (file.getUsableSpace() >= bytes) return;
4301        }
4302
4303        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4304    }
4305
4306    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4307            throws IOException {
4308        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4309        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4310
4311        List<VersionedPackage> packagesToDelete = null;
4312        final long now = System.currentTimeMillis();
4313
4314        synchronized (mPackages) {
4315            final int[] allUsers = sUserManager.getUserIds();
4316            final int libCount = mSharedLibraries.size();
4317            for (int i = 0; i < libCount; i++) {
4318                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4319                if (versionedLib == null) {
4320                    continue;
4321                }
4322                final int versionCount = versionedLib.size();
4323                for (int j = 0; j < versionCount; j++) {
4324                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4325                    // Skip packages that are not static shared libs.
4326                    if (!libInfo.isStatic()) {
4327                        break;
4328                    }
4329                    // Important: We skip static shared libs used for some user since
4330                    // in such a case we need to keep the APK on the device. The check for
4331                    // a lib being used for any user is performed by the uninstall call.
4332                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4333                    // Resolve the package name - we use synthetic package names internally
4334                    final String internalPackageName = resolveInternalPackageNameLPr(
4335                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4336                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4337                    // Skip unused static shared libs cached less than the min period
4338                    // to prevent pruning a lib needed by a subsequently installed package.
4339                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4340                        continue;
4341                    }
4342                    if (packagesToDelete == null) {
4343                        packagesToDelete = new ArrayList<>();
4344                    }
4345                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4346                            declaringPackage.getVersionCode()));
4347                }
4348            }
4349        }
4350
4351        if (packagesToDelete != null) {
4352            final int packageCount = packagesToDelete.size();
4353            for (int i = 0; i < packageCount; i++) {
4354                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4355                // Delete the package synchronously (will fail of the lib used for any user).
4356                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4357                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4358                                == PackageManager.DELETE_SUCCEEDED) {
4359                    if (volume.getUsableSpace() >= neededSpace) {
4360                        return true;
4361                    }
4362                }
4363            }
4364        }
4365
4366        return false;
4367    }
4368
4369    /**
4370     * Update given flags based on encryption status of current user.
4371     */
4372    private int updateFlags(int flags, int userId) {
4373        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4374                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4375            // Caller expressed an explicit opinion about what encryption
4376            // aware/unaware components they want to see, so fall through and
4377            // give them what they want
4378        } else {
4379            // Caller expressed no opinion, so match based on user state
4380            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4381                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4382            } else {
4383                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4384            }
4385        }
4386        return flags;
4387    }
4388
4389    private UserManagerInternal getUserManagerInternal() {
4390        if (mUserManagerInternal == null) {
4391            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4392        }
4393        return mUserManagerInternal;
4394    }
4395
4396    private DeviceIdleController.LocalService getDeviceIdleController() {
4397        if (mDeviceIdleController == null) {
4398            mDeviceIdleController =
4399                    LocalServices.getService(DeviceIdleController.LocalService.class);
4400        }
4401        return mDeviceIdleController;
4402    }
4403
4404    /**
4405     * Update given flags when being used to request {@link PackageInfo}.
4406     */
4407    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4408        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4409        boolean triaged = true;
4410        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4411                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4412            // Caller is asking for component details, so they'd better be
4413            // asking for specific encryption matching behavior, or be triaged
4414            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4415                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4416                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4417                triaged = false;
4418            }
4419        }
4420        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4421                | PackageManager.MATCH_SYSTEM_ONLY
4422                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4423            triaged = false;
4424        }
4425        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4426            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4427                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4428                    + Debug.getCallers(5));
4429        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4430                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4431            // If the caller wants all packages and has a restricted profile associated with it,
4432            // then match all users. This is to make sure that launchers that need to access work
4433            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4434            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4435            flags |= PackageManager.MATCH_ANY_USER;
4436        }
4437        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4438            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4439                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4440        }
4441        return updateFlags(flags, userId);
4442    }
4443
4444    /**
4445     * Update given flags when being used to request {@link ApplicationInfo}.
4446     */
4447    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4448        return updateFlagsForPackage(flags, userId, cookie);
4449    }
4450
4451    /**
4452     * Update given flags when being used to request {@link ComponentInfo}.
4453     */
4454    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4455        if (cookie instanceof Intent) {
4456            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4457                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4458            }
4459        }
4460
4461        boolean triaged = true;
4462        // Caller is asking for component details, so they'd better be
4463        // asking for specific encryption matching behavior, or be triaged
4464        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4465                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4466                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4467            triaged = false;
4468        }
4469        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4470            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4471                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4472        }
4473
4474        return updateFlags(flags, userId);
4475    }
4476
4477    /**
4478     * Update given intent when being used to request {@link ResolveInfo}.
4479     */
4480    private Intent updateIntentForResolve(Intent intent) {
4481        if (intent.getSelector() != null) {
4482            intent = intent.getSelector();
4483        }
4484        if (DEBUG_PREFERRED) {
4485            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4486        }
4487        return intent;
4488    }
4489
4490    /**
4491     * Update given flags when being used to request {@link ResolveInfo}.
4492     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4493     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4494     * flag set. However, this flag is only honoured in three circumstances:
4495     * <ul>
4496     * <li>when called from a system process</li>
4497     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4498     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4499     * action and a {@code android.intent.category.BROWSABLE} category</li>
4500     * </ul>
4501     */
4502    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4503        return updateFlagsForResolve(flags, userId, intent, callingUid,
4504                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4505    }
4506    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4507            boolean wantInstantApps) {
4508        return updateFlagsForResolve(flags, userId, intent, callingUid,
4509                wantInstantApps, false /*onlyExposedExplicitly*/);
4510    }
4511    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4512            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4513        // Safe mode means we shouldn't match any third-party components
4514        if (mSafeMode) {
4515            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4516        }
4517        if (getInstantAppPackageName(callingUid) != null) {
4518            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4519            if (onlyExposedExplicitly) {
4520                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4521            }
4522            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4523            flags |= PackageManager.MATCH_INSTANT;
4524        } else {
4525            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4526            final boolean allowMatchInstant =
4527                    (wantInstantApps
4528                            && Intent.ACTION_VIEW.equals(intent.getAction())
4529                            && hasWebURI(intent))
4530                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4531            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4532                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4533            if (!allowMatchInstant) {
4534                flags &= ~PackageManager.MATCH_INSTANT;
4535            }
4536        }
4537        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4538    }
4539
4540    @Override
4541    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4542        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4543    }
4544
4545    /**
4546     * Important: The provided filterCallingUid is used exclusively to filter out activities
4547     * that can be seen based on user state. It's typically the original caller uid prior
4548     * to clearing. Because it can only be provided by trusted code, it's value can be
4549     * trusted and will be used as-is; unlike userId which will be validated by this method.
4550     */
4551    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4552            int filterCallingUid, int userId) {
4553        if (!sUserManager.exists(userId)) return null;
4554        flags = updateFlagsForComponent(flags, userId, component);
4555        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4556                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4557        synchronized (mPackages) {
4558            PackageParser.Activity a = mActivities.mActivities.get(component);
4559
4560            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4561            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4562                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4563                if (ps == null) return null;
4564                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4565                    return null;
4566                }
4567                return PackageParser.generateActivityInfo(
4568                        a, flags, ps.readUserState(userId), userId);
4569            }
4570            if (mResolveComponentName.equals(component)) {
4571                return PackageParser.generateActivityInfo(
4572                        mResolveActivity, flags, new PackageUserState(), userId);
4573            }
4574        }
4575        return null;
4576    }
4577
4578    @Override
4579    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4580            String resolvedType) {
4581        synchronized (mPackages) {
4582            if (component.equals(mResolveComponentName)) {
4583                // The resolver supports EVERYTHING!
4584                return true;
4585            }
4586            final int callingUid = Binder.getCallingUid();
4587            final int callingUserId = UserHandle.getUserId(callingUid);
4588            PackageParser.Activity a = mActivities.mActivities.get(component);
4589            if (a == null) {
4590                return false;
4591            }
4592            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4593            if (ps == null) {
4594                return false;
4595            }
4596            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4597                return false;
4598            }
4599            for (int i=0; i<a.intents.size(); i++) {
4600                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4601                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4602                    return true;
4603                }
4604            }
4605            return false;
4606        }
4607    }
4608
4609    @Override
4610    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4611        if (!sUserManager.exists(userId)) return null;
4612        final int callingUid = Binder.getCallingUid();
4613        flags = updateFlagsForComponent(flags, userId, component);
4614        enforceCrossUserPermission(callingUid, userId,
4615                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4616        synchronized (mPackages) {
4617            PackageParser.Activity a = mReceivers.mActivities.get(component);
4618            if (DEBUG_PACKAGE_INFO) Log.v(
4619                TAG, "getReceiverInfo " + component + ": " + a);
4620            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4621                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4622                if (ps == null) return null;
4623                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4624                    return null;
4625                }
4626                return PackageParser.generateActivityInfo(
4627                        a, flags, ps.readUserState(userId), userId);
4628            }
4629        }
4630        return null;
4631    }
4632
4633    @Override
4634    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4635            int flags, int userId) {
4636        if (!sUserManager.exists(userId)) return null;
4637        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4638        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4639            return null;
4640        }
4641
4642        flags = updateFlagsForPackage(flags, userId, null);
4643
4644        final boolean canSeeStaticLibraries =
4645                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4646                        == PERMISSION_GRANTED
4647                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4648                        == PERMISSION_GRANTED
4649                || canRequestPackageInstallsInternal(packageName,
4650                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4651                        false  /* throwIfPermNotDeclared*/)
4652                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4653                        == PERMISSION_GRANTED;
4654
4655        synchronized (mPackages) {
4656            List<SharedLibraryInfo> result = null;
4657
4658            final int libCount = mSharedLibraries.size();
4659            for (int i = 0; i < libCount; i++) {
4660                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4661                if (versionedLib == null) {
4662                    continue;
4663                }
4664
4665                final int versionCount = versionedLib.size();
4666                for (int j = 0; j < versionCount; j++) {
4667                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4668                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4669                        break;
4670                    }
4671                    final long identity = Binder.clearCallingIdentity();
4672                    try {
4673                        PackageInfo packageInfo = getPackageInfoVersioned(
4674                                libInfo.getDeclaringPackage(), flags
4675                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4676                        if (packageInfo == null) {
4677                            continue;
4678                        }
4679                    } finally {
4680                        Binder.restoreCallingIdentity(identity);
4681                    }
4682
4683                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4684                            libInfo.getVersion(), libInfo.getType(),
4685                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4686                            flags, userId));
4687
4688                    if (result == null) {
4689                        result = new ArrayList<>();
4690                    }
4691                    result.add(resLibInfo);
4692                }
4693            }
4694
4695            return result != null ? new ParceledListSlice<>(result) : null;
4696        }
4697    }
4698
4699    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4700            SharedLibraryInfo libInfo, int flags, int userId) {
4701        List<VersionedPackage> versionedPackages = null;
4702        final int packageCount = mSettings.mPackages.size();
4703        for (int i = 0; i < packageCount; i++) {
4704            PackageSetting ps = mSettings.mPackages.valueAt(i);
4705
4706            if (ps == null) {
4707                continue;
4708            }
4709
4710            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4711                continue;
4712            }
4713
4714            final String libName = libInfo.getName();
4715            if (libInfo.isStatic()) {
4716                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4717                if (libIdx < 0) {
4718                    continue;
4719                }
4720                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4721                    continue;
4722                }
4723                if (versionedPackages == null) {
4724                    versionedPackages = new ArrayList<>();
4725                }
4726                // If the dependent is a static shared lib, use the public package name
4727                String dependentPackageName = ps.name;
4728                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4729                    dependentPackageName = ps.pkg.manifestPackageName;
4730                }
4731                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4732            } else if (ps.pkg != null) {
4733                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4734                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4735                    if (versionedPackages == null) {
4736                        versionedPackages = new ArrayList<>();
4737                    }
4738                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4739                }
4740            }
4741        }
4742
4743        return versionedPackages;
4744    }
4745
4746    @Override
4747    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4748        if (!sUserManager.exists(userId)) return null;
4749        final int callingUid = Binder.getCallingUid();
4750        flags = updateFlagsForComponent(flags, userId, component);
4751        enforceCrossUserPermission(callingUid, userId,
4752                false /* requireFullPermission */, false /* checkShell */, "get service info");
4753        synchronized (mPackages) {
4754            PackageParser.Service s = mServices.mServices.get(component);
4755            if (DEBUG_PACKAGE_INFO) Log.v(
4756                TAG, "getServiceInfo " + component + ": " + s);
4757            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4758                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4759                if (ps == null) return null;
4760                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4761                    return null;
4762                }
4763                return PackageParser.generateServiceInfo(
4764                        s, flags, ps.readUserState(userId), userId);
4765            }
4766        }
4767        return null;
4768    }
4769
4770    @Override
4771    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4772        if (!sUserManager.exists(userId)) return null;
4773        final int callingUid = Binder.getCallingUid();
4774        flags = updateFlagsForComponent(flags, userId, component);
4775        enforceCrossUserPermission(callingUid, userId,
4776                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4777        synchronized (mPackages) {
4778            PackageParser.Provider p = mProviders.mProviders.get(component);
4779            if (DEBUG_PACKAGE_INFO) Log.v(
4780                TAG, "getProviderInfo " + component + ": " + p);
4781            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4782                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4783                if (ps == null) return null;
4784                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4785                    return null;
4786                }
4787                return PackageParser.generateProviderInfo(
4788                        p, flags, ps.readUserState(userId), userId);
4789            }
4790        }
4791        return null;
4792    }
4793
4794    @Override
4795    public String[] getSystemSharedLibraryNames() {
4796        // allow instant applications
4797        synchronized (mPackages) {
4798            Set<String> libs = null;
4799            final int libCount = mSharedLibraries.size();
4800            for (int i = 0; i < libCount; i++) {
4801                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4802                if (versionedLib == null) {
4803                    continue;
4804                }
4805                final int versionCount = versionedLib.size();
4806                for (int j = 0; j < versionCount; j++) {
4807                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4808                    if (!libEntry.info.isStatic()) {
4809                        if (libs == null) {
4810                            libs = new ArraySet<>();
4811                        }
4812                        libs.add(libEntry.info.getName());
4813                        break;
4814                    }
4815                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4816                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4817                            UserHandle.getUserId(Binder.getCallingUid()),
4818                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4819                        if (libs == null) {
4820                            libs = new ArraySet<>();
4821                        }
4822                        libs.add(libEntry.info.getName());
4823                        break;
4824                    }
4825                }
4826            }
4827
4828            if (libs != null) {
4829                String[] libsArray = new String[libs.size()];
4830                libs.toArray(libsArray);
4831                return libsArray;
4832            }
4833
4834            return null;
4835        }
4836    }
4837
4838    @Override
4839    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4840        // allow instant applications
4841        synchronized (mPackages) {
4842            return mServicesSystemSharedLibraryPackageName;
4843        }
4844    }
4845
4846    @Override
4847    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4848        // allow instant applications
4849        synchronized (mPackages) {
4850            return mSharedSystemSharedLibraryPackageName;
4851        }
4852    }
4853
4854    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4855        for (int i = userList.length - 1; i >= 0; --i) {
4856            final int userId = userList[i];
4857            // don't add instant app to the list of updates
4858            if (pkgSetting.getInstantApp(userId)) {
4859                continue;
4860            }
4861            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4862            if (changedPackages == null) {
4863                changedPackages = new SparseArray<>();
4864                mChangedPackages.put(userId, changedPackages);
4865            }
4866            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4867            if (sequenceNumbers == null) {
4868                sequenceNumbers = new HashMap<>();
4869                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4870            }
4871            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4872            if (sequenceNumber != null) {
4873                changedPackages.remove(sequenceNumber);
4874            }
4875            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4876            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4877        }
4878        mChangedPackagesSequenceNumber++;
4879    }
4880
4881    @Override
4882    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4883        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4884            return null;
4885        }
4886        synchronized (mPackages) {
4887            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4888                return null;
4889            }
4890            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4891            if (changedPackages == null) {
4892                return null;
4893            }
4894            final List<String> packageNames =
4895                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4896            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4897                final String packageName = changedPackages.get(i);
4898                if (packageName != null) {
4899                    packageNames.add(packageName);
4900                }
4901            }
4902            return packageNames.isEmpty()
4903                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4904        }
4905    }
4906
4907    @Override
4908    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4909        // allow instant applications
4910        ArrayList<FeatureInfo> res;
4911        synchronized (mAvailableFeatures) {
4912            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4913            res.addAll(mAvailableFeatures.values());
4914        }
4915        final FeatureInfo fi = new FeatureInfo();
4916        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4917                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4918        res.add(fi);
4919
4920        return new ParceledListSlice<>(res);
4921    }
4922
4923    @Override
4924    public boolean hasSystemFeature(String name, int version) {
4925        // allow instant applications
4926        synchronized (mAvailableFeatures) {
4927            final FeatureInfo feat = mAvailableFeatures.get(name);
4928            if (feat == null) {
4929                return false;
4930            } else {
4931                return feat.version >= version;
4932            }
4933        }
4934    }
4935
4936    @Override
4937    public int checkPermission(String permName, String pkgName, int userId) {
4938        if (!sUserManager.exists(userId)) {
4939            return PackageManager.PERMISSION_DENIED;
4940        }
4941        final int callingUid = Binder.getCallingUid();
4942
4943        synchronized (mPackages) {
4944            final PackageParser.Package p = mPackages.get(pkgName);
4945            if (p != null && p.mExtras != null) {
4946                final PackageSetting ps = (PackageSetting) p.mExtras;
4947                if (filterAppAccessLPr(ps, callingUid, userId)) {
4948                    return PackageManager.PERMISSION_DENIED;
4949                }
4950                final boolean instantApp = ps.getInstantApp(userId);
4951                final PermissionsState permissionsState = ps.getPermissionsState();
4952                if (permissionsState.hasPermission(permName, userId)) {
4953                    if (instantApp) {
4954                        BasePermission bp = mSettings.mPermissions.get(permName);
4955                        if (bp != null && bp.isInstant()) {
4956                            return PackageManager.PERMISSION_GRANTED;
4957                        }
4958                    } else {
4959                        return PackageManager.PERMISSION_GRANTED;
4960                    }
4961                }
4962                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4963                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4964                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4965                    return PackageManager.PERMISSION_GRANTED;
4966                }
4967            }
4968        }
4969
4970        return PackageManager.PERMISSION_DENIED;
4971    }
4972
4973    @Override
4974    public int checkUidPermission(String permName, int uid) {
4975        final int callingUid = Binder.getCallingUid();
4976        final int callingUserId = UserHandle.getUserId(callingUid);
4977        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
4978        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
4979        final int userId = UserHandle.getUserId(uid);
4980        if (!sUserManager.exists(userId)) {
4981            return PackageManager.PERMISSION_DENIED;
4982        }
4983
4984        synchronized (mPackages) {
4985            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4986            if (obj != null) {
4987                if (obj instanceof SharedUserSetting) {
4988                    if (isCallerInstantApp) {
4989                        return PackageManager.PERMISSION_DENIED;
4990                    }
4991                } else if (obj instanceof PackageSetting) {
4992                    final PackageSetting ps = (PackageSetting) obj;
4993                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
4994                        return PackageManager.PERMISSION_DENIED;
4995                    }
4996                }
4997                final SettingBase settingBase = (SettingBase) obj;
4998                final PermissionsState permissionsState = settingBase.getPermissionsState();
4999                if (permissionsState.hasPermission(permName, userId)) {
5000                    if (isUidInstantApp) {
5001                        BasePermission bp = mSettings.mPermissions.get(permName);
5002                        if (bp != null && bp.isInstant()) {
5003                            return PackageManager.PERMISSION_GRANTED;
5004                        }
5005                    } else {
5006                        return PackageManager.PERMISSION_GRANTED;
5007                    }
5008                }
5009                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5010                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5011                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5012                    return PackageManager.PERMISSION_GRANTED;
5013                }
5014            } else {
5015                ArraySet<String> perms = mSystemPermissions.get(uid);
5016                if (perms != null) {
5017                    if (perms.contains(permName)) {
5018                        return PackageManager.PERMISSION_GRANTED;
5019                    }
5020                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5021                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5022                        return PackageManager.PERMISSION_GRANTED;
5023                    }
5024                }
5025            }
5026        }
5027
5028        return PackageManager.PERMISSION_DENIED;
5029    }
5030
5031    @Override
5032    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5033        if (UserHandle.getCallingUserId() != userId) {
5034            mContext.enforceCallingPermission(
5035                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5036                    "isPermissionRevokedByPolicy for user " + userId);
5037        }
5038
5039        if (checkPermission(permission, packageName, userId)
5040                == PackageManager.PERMISSION_GRANTED) {
5041            return false;
5042        }
5043
5044        final int callingUid = Binder.getCallingUid();
5045        if (getInstantAppPackageName(callingUid) != null) {
5046            if (!isCallerSameApp(packageName, callingUid)) {
5047                return false;
5048            }
5049        } else {
5050            if (isInstantApp(packageName, userId)) {
5051                return false;
5052            }
5053        }
5054
5055        final long identity = Binder.clearCallingIdentity();
5056        try {
5057            final int flags = getPermissionFlags(permission, packageName, userId);
5058            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5059        } finally {
5060            Binder.restoreCallingIdentity(identity);
5061        }
5062    }
5063
5064    @Override
5065    public String getPermissionControllerPackageName() {
5066        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5067            throw new SecurityException("Instant applications don't have access to this method");
5068        }
5069        synchronized (mPackages) {
5070            return mRequiredInstallerPackage;
5071        }
5072    }
5073
5074    /**
5075     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5076     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5077     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5078     * @param message the message to log on security exception
5079     */
5080    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5081            boolean checkShell, String message) {
5082        if (userId < 0) {
5083            throw new IllegalArgumentException("Invalid userId " + userId);
5084        }
5085        if (checkShell) {
5086            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5087        }
5088        if (userId == UserHandle.getUserId(callingUid)) return;
5089        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5090            if (requireFullPermission) {
5091                mContext.enforceCallingOrSelfPermission(
5092                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5093            } else {
5094                try {
5095                    mContext.enforceCallingOrSelfPermission(
5096                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5097                } catch (SecurityException se) {
5098                    mContext.enforceCallingOrSelfPermission(
5099                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5100                }
5101            }
5102        }
5103    }
5104
5105    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5106        if (callingUid == Process.SHELL_UID) {
5107            if (userHandle >= 0
5108                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5109                throw new SecurityException("Shell does not have permission to access user "
5110                        + userHandle);
5111            } else if (userHandle < 0) {
5112                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5113                        + Debug.getCallers(3));
5114            }
5115        }
5116    }
5117
5118    private BasePermission findPermissionTreeLP(String permName) {
5119        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5120            if (permName.startsWith(bp.name) &&
5121                    permName.length() > bp.name.length() &&
5122                    permName.charAt(bp.name.length()) == '.') {
5123                return bp;
5124            }
5125        }
5126        return null;
5127    }
5128
5129    private BasePermission checkPermissionTreeLP(String permName) {
5130        if (permName != null) {
5131            BasePermission bp = findPermissionTreeLP(permName);
5132            if (bp != null) {
5133                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5134                    return bp;
5135                }
5136                throw new SecurityException("Calling uid "
5137                        + Binder.getCallingUid()
5138                        + " is not allowed to add to permission tree "
5139                        + bp.name + " owned by uid " + bp.uid);
5140            }
5141        }
5142        throw new SecurityException("No permission tree found for " + permName);
5143    }
5144
5145    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5146        if (s1 == null) {
5147            return s2 == null;
5148        }
5149        if (s2 == null) {
5150            return false;
5151        }
5152        if (s1.getClass() != s2.getClass()) {
5153            return false;
5154        }
5155        return s1.equals(s2);
5156    }
5157
5158    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5159        if (pi1.icon != pi2.icon) return false;
5160        if (pi1.logo != pi2.logo) return false;
5161        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5162        if (!compareStrings(pi1.name, pi2.name)) return false;
5163        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5164        // We'll take care of setting this one.
5165        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5166        // These are not currently stored in settings.
5167        //if (!compareStrings(pi1.group, pi2.group)) return false;
5168        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5169        //if (pi1.labelRes != pi2.labelRes) return false;
5170        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5171        return true;
5172    }
5173
5174    int permissionInfoFootprint(PermissionInfo info) {
5175        int size = info.name.length();
5176        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5177        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5178        return size;
5179    }
5180
5181    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5182        int size = 0;
5183        for (BasePermission perm : mSettings.mPermissions.values()) {
5184            if (perm.uid == tree.uid) {
5185                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5186            }
5187        }
5188        return size;
5189    }
5190
5191    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5192        // We calculate the max size of permissions defined by this uid and throw
5193        // if that plus the size of 'info' would exceed our stated maximum.
5194        if (tree.uid != Process.SYSTEM_UID) {
5195            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5196            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5197                throw new SecurityException("Permission tree size cap exceeded");
5198            }
5199        }
5200    }
5201
5202    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5203        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5204            throw new SecurityException("Instant apps can't add permissions");
5205        }
5206        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5207            throw new SecurityException("Label must be specified in permission");
5208        }
5209        BasePermission tree = checkPermissionTreeLP(info.name);
5210        BasePermission bp = mSettings.mPermissions.get(info.name);
5211        boolean added = bp == null;
5212        boolean changed = true;
5213        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5214        if (added) {
5215            enforcePermissionCapLocked(info, tree);
5216            bp = new BasePermission(info.name, tree.sourcePackage,
5217                    BasePermission.TYPE_DYNAMIC);
5218        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5219            throw new SecurityException(
5220                    "Not allowed to modify non-dynamic permission "
5221                    + info.name);
5222        } else {
5223            if (bp.protectionLevel == fixedLevel
5224                    && bp.perm.owner.equals(tree.perm.owner)
5225                    && bp.uid == tree.uid
5226                    && comparePermissionInfos(bp.perm.info, info)) {
5227                changed = false;
5228            }
5229        }
5230        bp.protectionLevel = fixedLevel;
5231        info = new PermissionInfo(info);
5232        info.protectionLevel = fixedLevel;
5233        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5234        bp.perm.info.packageName = tree.perm.info.packageName;
5235        bp.uid = tree.uid;
5236        if (added) {
5237            mSettings.mPermissions.put(info.name, bp);
5238        }
5239        if (changed) {
5240            if (!async) {
5241                mSettings.writeLPr();
5242            } else {
5243                scheduleWriteSettingsLocked();
5244            }
5245        }
5246        return added;
5247    }
5248
5249    @Override
5250    public boolean addPermission(PermissionInfo info) {
5251        synchronized (mPackages) {
5252            return addPermissionLocked(info, false);
5253        }
5254    }
5255
5256    @Override
5257    public boolean addPermissionAsync(PermissionInfo info) {
5258        synchronized (mPackages) {
5259            return addPermissionLocked(info, true);
5260        }
5261    }
5262
5263    @Override
5264    public void removePermission(String name) {
5265        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5266            throw new SecurityException("Instant applications don't have access to this method");
5267        }
5268        synchronized (mPackages) {
5269            checkPermissionTreeLP(name);
5270            BasePermission bp = mSettings.mPermissions.get(name);
5271            if (bp != null) {
5272                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5273                    throw new SecurityException(
5274                            "Not allowed to modify non-dynamic permission "
5275                            + name);
5276                }
5277                mSettings.mPermissions.remove(name);
5278                mSettings.writeLPr();
5279            }
5280        }
5281    }
5282
5283    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5284            PackageParser.Package pkg, BasePermission bp) {
5285        int index = pkg.requestedPermissions.indexOf(bp.name);
5286        if (index == -1) {
5287            throw new SecurityException("Package " + pkg.packageName
5288                    + " has not requested permission " + bp.name);
5289        }
5290        if (!bp.isRuntime() && !bp.isDevelopment()) {
5291            throw new SecurityException("Permission " + bp.name
5292                    + " is not a changeable permission type");
5293        }
5294    }
5295
5296    @Override
5297    public void grantRuntimePermission(String packageName, String name, final int userId) {
5298        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5299    }
5300
5301    private void grantRuntimePermission(String packageName, String name, final int userId,
5302            boolean overridePolicy) {
5303        if (!sUserManager.exists(userId)) {
5304            Log.e(TAG, "No such user:" + userId);
5305            return;
5306        }
5307        final int callingUid = Binder.getCallingUid();
5308
5309        mContext.enforceCallingOrSelfPermission(
5310                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5311                "grantRuntimePermission");
5312
5313        enforceCrossUserPermission(callingUid, userId,
5314                true /* requireFullPermission */, true /* checkShell */,
5315                "grantRuntimePermission");
5316
5317        final int uid;
5318        final PackageSetting ps;
5319
5320        synchronized (mPackages) {
5321            final PackageParser.Package pkg = mPackages.get(packageName);
5322            if (pkg == null) {
5323                throw new IllegalArgumentException("Unknown package: " + packageName);
5324            }
5325            final BasePermission bp = mSettings.mPermissions.get(name);
5326            if (bp == null) {
5327                throw new IllegalArgumentException("Unknown permission: " + name);
5328            }
5329            ps = (PackageSetting) pkg.mExtras;
5330            if (ps == null
5331                    || filterAppAccessLPr(ps, callingUid, userId)) {
5332                throw new IllegalArgumentException("Unknown package: " + packageName);
5333            }
5334
5335            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5336
5337            // If a permission review is required for legacy apps we represent
5338            // their permissions as always granted runtime ones since we need
5339            // to keep the review required permission flag per user while an
5340            // install permission's state is shared across all users.
5341            if (mPermissionReviewRequired
5342                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5343                    && bp.isRuntime()) {
5344                return;
5345            }
5346
5347            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5348
5349            final PermissionsState permissionsState = ps.getPermissionsState();
5350
5351            final int flags = permissionsState.getPermissionFlags(name, userId);
5352            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5353                throw new SecurityException("Cannot grant system fixed permission "
5354                        + name + " for package " + packageName);
5355            }
5356            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5357                throw new SecurityException("Cannot grant policy fixed permission "
5358                        + name + " for package " + packageName);
5359            }
5360
5361            if (bp.isDevelopment()) {
5362                // Development permissions must be handled specially, since they are not
5363                // normal runtime permissions.  For now they apply to all users.
5364                if (permissionsState.grantInstallPermission(bp) !=
5365                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5366                    scheduleWriteSettingsLocked();
5367                }
5368                return;
5369            }
5370
5371            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5372                throw new SecurityException("Cannot grant non-ephemeral permission"
5373                        + name + " for package " + packageName);
5374            }
5375
5376            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5377                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5378                return;
5379            }
5380
5381            final int result = permissionsState.grantRuntimePermission(bp, userId);
5382            switch (result) {
5383                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5384                    return;
5385                }
5386
5387                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5388                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5389                    mHandler.post(new Runnable() {
5390                        @Override
5391                        public void run() {
5392                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5393                        }
5394                    });
5395                }
5396                break;
5397            }
5398
5399            if (bp.isRuntime()) {
5400                logPermissionGranted(mContext, name, packageName);
5401            }
5402
5403            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5404
5405            // Not critical if that is lost - app has to request again.
5406            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5407        }
5408
5409        // Only need to do this if user is initialized. Otherwise it's a new user
5410        // and there are no processes running as the user yet and there's no need
5411        // to make an expensive call to remount processes for the changed permissions.
5412        if (READ_EXTERNAL_STORAGE.equals(name)
5413                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5414            final long token = Binder.clearCallingIdentity();
5415            try {
5416                if (sUserManager.isInitialized(userId)) {
5417                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5418                            StorageManagerInternal.class);
5419                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5420                }
5421            } finally {
5422                Binder.restoreCallingIdentity(token);
5423            }
5424        }
5425    }
5426
5427    @Override
5428    public void revokeRuntimePermission(String packageName, String name, int userId) {
5429        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5430    }
5431
5432    private void revokeRuntimePermission(String packageName, String name, int userId,
5433            boolean overridePolicy) {
5434        if (!sUserManager.exists(userId)) {
5435            Log.e(TAG, "No such user:" + userId);
5436            return;
5437        }
5438
5439        mContext.enforceCallingOrSelfPermission(
5440                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5441                "revokeRuntimePermission");
5442
5443        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5444                true /* requireFullPermission */, true /* checkShell */,
5445                "revokeRuntimePermission");
5446
5447        final int appId;
5448
5449        synchronized (mPackages) {
5450            final PackageParser.Package pkg = mPackages.get(packageName);
5451            if (pkg == null) {
5452                throw new IllegalArgumentException("Unknown package: " + packageName);
5453            }
5454            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5455            if (ps == null
5456                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5457                throw new IllegalArgumentException("Unknown package: " + packageName);
5458            }
5459            final BasePermission bp = mSettings.mPermissions.get(name);
5460            if (bp == null) {
5461                throw new IllegalArgumentException("Unknown permission: " + name);
5462            }
5463
5464            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5465
5466            // If a permission review is required for legacy apps we represent
5467            // their permissions as always granted runtime ones since we need
5468            // to keep the review required permission flag per user while an
5469            // install permission's state is shared across all users.
5470            if (mPermissionReviewRequired
5471                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5472                    && bp.isRuntime()) {
5473                return;
5474            }
5475
5476            final PermissionsState permissionsState = ps.getPermissionsState();
5477
5478            final int flags = permissionsState.getPermissionFlags(name, userId);
5479            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5480                throw new SecurityException("Cannot revoke system fixed permission "
5481                        + name + " for package " + packageName);
5482            }
5483            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5484                throw new SecurityException("Cannot revoke policy fixed permission "
5485                        + name + " for package " + packageName);
5486            }
5487
5488            if (bp.isDevelopment()) {
5489                // Development permissions must be handled specially, since they are not
5490                // normal runtime permissions.  For now they apply to all users.
5491                if (permissionsState.revokeInstallPermission(bp) !=
5492                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5493                    scheduleWriteSettingsLocked();
5494                }
5495                return;
5496            }
5497
5498            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5499                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5500                return;
5501            }
5502
5503            if (bp.isRuntime()) {
5504                logPermissionRevoked(mContext, name, packageName);
5505            }
5506
5507            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5508
5509            // Critical, after this call app should never have the permission.
5510            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5511
5512            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5513        }
5514
5515        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5516    }
5517
5518    /**
5519     * Get the first event id for the permission.
5520     *
5521     * <p>There are four events for each permission: <ul>
5522     *     <li>Request permission: first id + 0</li>
5523     *     <li>Grant permission: first id + 1</li>
5524     *     <li>Request for permission denied: first id + 2</li>
5525     *     <li>Revoke permission: first id + 3</li>
5526     * </ul></p>
5527     *
5528     * @param name name of the permission
5529     *
5530     * @return The first event id for the permission
5531     */
5532    private static int getBaseEventId(@NonNull String name) {
5533        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5534
5535        if (eventIdIndex == -1) {
5536            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5537                    || "user".equals(Build.TYPE)) {
5538                Log.i(TAG, "Unknown permission " + name);
5539
5540                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5541            } else {
5542                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5543                //
5544                // Also update
5545                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5546                // - metrics_constants.proto
5547                throw new IllegalStateException("Unknown permission " + name);
5548            }
5549        }
5550
5551        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5552    }
5553
5554    /**
5555     * Log that a permission was revoked.
5556     *
5557     * @param context Context of the caller
5558     * @param name name of the permission
5559     * @param packageName package permission if for
5560     */
5561    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5562            @NonNull String packageName) {
5563        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5564    }
5565
5566    /**
5567     * Log that a permission request was granted.
5568     *
5569     * @param context Context of the caller
5570     * @param name name of the permission
5571     * @param packageName package permission if for
5572     */
5573    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5574            @NonNull String packageName) {
5575        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5576    }
5577
5578    @Override
5579    public void resetRuntimePermissions() {
5580        mContext.enforceCallingOrSelfPermission(
5581                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5582                "revokeRuntimePermission");
5583
5584        int callingUid = Binder.getCallingUid();
5585        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5586            mContext.enforceCallingOrSelfPermission(
5587                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5588                    "resetRuntimePermissions");
5589        }
5590
5591        synchronized (mPackages) {
5592            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5593            for (int userId : UserManagerService.getInstance().getUserIds()) {
5594                final int packageCount = mPackages.size();
5595                for (int i = 0; i < packageCount; i++) {
5596                    PackageParser.Package pkg = mPackages.valueAt(i);
5597                    if (!(pkg.mExtras instanceof PackageSetting)) {
5598                        continue;
5599                    }
5600                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5601                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5602                }
5603            }
5604        }
5605    }
5606
5607    @Override
5608    public int getPermissionFlags(String name, String packageName, int userId) {
5609        if (!sUserManager.exists(userId)) {
5610            return 0;
5611        }
5612
5613        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5614
5615        final int callingUid = Binder.getCallingUid();
5616        enforceCrossUserPermission(callingUid, userId,
5617                true /* requireFullPermission */, false /* checkShell */,
5618                "getPermissionFlags");
5619
5620        synchronized (mPackages) {
5621            final PackageParser.Package pkg = mPackages.get(packageName);
5622            if (pkg == null) {
5623                return 0;
5624            }
5625            final BasePermission bp = mSettings.mPermissions.get(name);
5626            if (bp == null) {
5627                return 0;
5628            }
5629            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5630            if (ps == null
5631                    || filterAppAccessLPr(ps, callingUid, userId)) {
5632                return 0;
5633            }
5634            PermissionsState permissionsState = ps.getPermissionsState();
5635            return permissionsState.getPermissionFlags(name, userId);
5636        }
5637    }
5638
5639    @Override
5640    public void updatePermissionFlags(String name, String packageName, int flagMask,
5641            int flagValues, int userId) {
5642        if (!sUserManager.exists(userId)) {
5643            return;
5644        }
5645
5646        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5647
5648        final int callingUid = Binder.getCallingUid();
5649        enforceCrossUserPermission(callingUid, userId,
5650                true /* requireFullPermission */, true /* checkShell */,
5651                "updatePermissionFlags");
5652
5653        // Only the system can change these flags and nothing else.
5654        if (getCallingUid() != Process.SYSTEM_UID) {
5655            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5656            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5657            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5658            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5659            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5660        }
5661
5662        synchronized (mPackages) {
5663            final PackageParser.Package pkg = mPackages.get(packageName);
5664            if (pkg == null) {
5665                throw new IllegalArgumentException("Unknown package: " + packageName);
5666            }
5667            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5668            if (ps == null
5669                    || filterAppAccessLPr(ps, callingUid, userId)) {
5670                throw new IllegalArgumentException("Unknown package: " + packageName);
5671            }
5672
5673            final BasePermission bp = mSettings.mPermissions.get(name);
5674            if (bp == null) {
5675                throw new IllegalArgumentException("Unknown permission: " + name);
5676            }
5677
5678            PermissionsState permissionsState = ps.getPermissionsState();
5679
5680            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5681
5682            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5683                // Install and runtime permissions are stored in different places,
5684                // so figure out what permission changed and persist the change.
5685                if (permissionsState.getInstallPermissionState(name) != null) {
5686                    scheduleWriteSettingsLocked();
5687                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5688                        || hadState) {
5689                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5690                }
5691            }
5692        }
5693    }
5694
5695    /**
5696     * Update the permission flags for all packages and runtime permissions of a user in order
5697     * to allow device or profile owner to remove POLICY_FIXED.
5698     */
5699    @Override
5700    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5701        if (!sUserManager.exists(userId)) {
5702            return;
5703        }
5704
5705        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5706
5707        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5708                true /* requireFullPermission */, true /* checkShell */,
5709                "updatePermissionFlagsForAllApps");
5710
5711        // Only the system can change system fixed flags.
5712        if (getCallingUid() != Process.SYSTEM_UID) {
5713            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5714            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5715        }
5716
5717        synchronized (mPackages) {
5718            boolean changed = false;
5719            final int packageCount = mPackages.size();
5720            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5721                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5722                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5723                if (ps == null) {
5724                    continue;
5725                }
5726                PermissionsState permissionsState = ps.getPermissionsState();
5727                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5728                        userId, flagMask, flagValues);
5729            }
5730            if (changed) {
5731                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5732            }
5733        }
5734    }
5735
5736    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5737        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5738                != PackageManager.PERMISSION_GRANTED
5739            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5740                != PackageManager.PERMISSION_GRANTED) {
5741            throw new SecurityException(message + " requires "
5742                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5743                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5744        }
5745    }
5746
5747    @Override
5748    public boolean shouldShowRequestPermissionRationale(String permissionName,
5749            String packageName, int userId) {
5750        if (UserHandle.getCallingUserId() != userId) {
5751            mContext.enforceCallingPermission(
5752                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5753                    "canShowRequestPermissionRationale for user " + userId);
5754        }
5755
5756        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5757        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5758            return false;
5759        }
5760
5761        if (checkPermission(permissionName, packageName, userId)
5762                == PackageManager.PERMISSION_GRANTED) {
5763            return false;
5764        }
5765
5766        final int flags;
5767
5768        final long identity = Binder.clearCallingIdentity();
5769        try {
5770            flags = getPermissionFlags(permissionName,
5771                    packageName, userId);
5772        } finally {
5773            Binder.restoreCallingIdentity(identity);
5774        }
5775
5776        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5777                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5778                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5779
5780        if ((flags & fixedFlags) != 0) {
5781            return false;
5782        }
5783
5784        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5785    }
5786
5787    @Override
5788    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5789        mContext.enforceCallingOrSelfPermission(
5790                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5791                "addOnPermissionsChangeListener");
5792
5793        synchronized (mPackages) {
5794            mOnPermissionChangeListeners.addListenerLocked(listener);
5795        }
5796    }
5797
5798    @Override
5799    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5800        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5801            throw new SecurityException("Instant applications don't have access to this method");
5802        }
5803        synchronized (mPackages) {
5804            mOnPermissionChangeListeners.removeListenerLocked(listener);
5805        }
5806    }
5807
5808    @Override
5809    public boolean isProtectedBroadcast(String actionName) {
5810        // allow instant applications
5811        synchronized (mPackages) {
5812            if (mProtectedBroadcasts.contains(actionName)) {
5813                return true;
5814            } else if (actionName != null) {
5815                // TODO: remove these terrible hacks
5816                if (actionName.startsWith("android.net.netmon.lingerExpired")
5817                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5818                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5819                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5820                    return true;
5821                }
5822            }
5823        }
5824        return false;
5825    }
5826
5827    @Override
5828    public int checkSignatures(String pkg1, String pkg2) {
5829        synchronized (mPackages) {
5830            final PackageParser.Package p1 = mPackages.get(pkg1);
5831            final PackageParser.Package p2 = mPackages.get(pkg2);
5832            if (p1 == null || p1.mExtras == null
5833                    || p2 == null || p2.mExtras == null) {
5834                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5835            }
5836            final int callingUid = Binder.getCallingUid();
5837            final int callingUserId = UserHandle.getUserId(callingUid);
5838            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5839            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5840            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5841                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5842                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5843            }
5844            return compareSignatures(p1.mSignatures, p2.mSignatures);
5845        }
5846    }
5847
5848    @Override
5849    public int checkUidSignatures(int uid1, int uid2) {
5850        final int callingUid = Binder.getCallingUid();
5851        final int callingUserId = UserHandle.getUserId(callingUid);
5852        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5853        // Map to base uids.
5854        uid1 = UserHandle.getAppId(uid1);
5855        uid2 = UserHandle.getAppId(uid2);
5856        // reader
5857        synchronized (mPackages) {
5858            Signature[] s1;
5859            Signature[] s2;
5860            Object obj = mSettings.getUserIdLPr(uid1);
5861            if (obj != null) {
5862                if (obj instanceof SharedUserSetting) {
5863                    if (isCallerInstantApp) {
5864                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5865                    }
5866                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5867                } else if (obj instanceof PackageSetting) {
5868                    final PackageSetting ps = (PackageSetting) obj;
5869                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5870                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5871                    }
5872                    s1 = ps.signatures.mSignatures;
5873                } else {
5874                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5875                }
5876            } else {
5877                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5878            }
5879            obj = mSettings.getUserIdLPr(uid2);
5880            if (obj != null) {
5881                if (obj instanceof SharedUserSetting) {
5882                    if (isCallerInstantApp) {
5883                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5884                    }
5885                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5886                } else if (obj instanceof PackageSetting) {
5887                    final PackageSetting ps = (PackageSetting) obj;
5888                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5889                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5890                    }
5891                    s2 = ps.signatures.mSignatures;
5892                } else {
5893                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5894                }
5895            } else {
5896                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5897            }
5898            return compareSignatures(s1, s2);
5899        }
5900    }
5901
5902    /**
5903     * This method should typically only be used when granting or revoking
5904     * permissions, since the app may immediately restart after this call.
5905     * <p>
5906     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5907     * guard your work against the app being relaunched.
5908     */
5909    private void killUid(int appId, int userId, String reason) {
5910        final long identity = Binder.clearCallingIdentity();
5911        try {
5912            IActivityManager am = ActivityManager.getService();
5913            if (am != null) {
5914                try {
5915                    am.killUid(appId, userId, reason);
5916                } catch (RemoteException e) {
5917                    /* ignore - same process */
5918                }
5919            }
5920        } finally {
5921            Binder.restoreCallingIdentity(identity);
5922        }
5923    }
5924
5925    /**
5926     * Compares two sets of signatures. Returns:
5927     * <br />
5928     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5929     * <br />
5930     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5931     * <br />
5932     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5933     * <br />
5934     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5935     * <br />
5936     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5937     */
5938    static int compareSignatures(Signature[] s1, Signature[] s2) {
5939        if (s1 == null) {
5940            return s2 == null
5941                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5942                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5943        }
5944
5945        if (s2 == null) {
5946            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5947        }
5948
5949        if (s1.length != s2.length) {
5950            return PackageManager.SIGNATURE_NO_MATCH;
5951        }
5952
5953        // Since both signature sets are of size 1, we can compare without HashSets.
5954        if (s1.length == 1) {
5955            return s1[0].equals(s2[0]) ?
5956                    PackageManager.SIGNATURE_MATCH :
5957                    PackageManager.SIGNATURE_NO_MATCH;
5958        }
5959
5960        ArraySet<Signature> set1 = new ArraySet<Signature>();
5961        for (Signature sig : s1) {
5962            set1.add(sig);
5963        }
5964        ArraySet<Signature> set2 = new ArraySet<Signature>();
5965        for (Signature sig : s2) {
5966            set2.add(sig);
5967        }
5968        // Make sure s2 contains all signatures in s1.
5969        if (set1.equals(set2)) {
5970            return PackageManager.SIGNATURE_MATCH;
5971        }
5972        return PackageManager.SIGNATURE_NO_MATCH;
5973    }
5974
5975    /**
5976     * If the database version for this type of package (internal storage or
5977     * external storage) is less than the version where package signatures
5978     * were updated, return true.
5979     */
5980    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5981        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5982        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5983    }
5984
5985    /**
5986     * Used for backward compatibility to make sure any packages with
5987     * certificate chains get upgraded to the new style. {@code existingSigs}
5988     * will be in the old format (since they were stored on disk from before the
5989     * system upgrade) and {@code scannedSigs} will be in the newer format.
5990     */
5991    private int compareSignaturesCompat(PackageSignatures existingSigs,
5992            PackageParser.Package scannedPkg) {
5993        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5994            return PackageManager.SIGNATURE_NO_MATCH;
5995        }
5996
5997        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5998        for (Signature sig : existingSigs.mSignatures) {
5999            existingSet.add(sig);
6000        }
6001        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6002        for (Signature sig : scannedPkg.mSignatures) {
6003            try {
6004                Signature[] chainSignatures = sig.getChainSignatures();
6005                for (Signature chainSig : chainSignatures) {
6006                    scannedCompatSet.add(chainSig);
6007                }
6008            } catch (CertificateEncodingException e) {
6009                scannedCompatSet.add(sig);
6010            }
6011        }
6012        /*
6013         * Make sure the expanded scanned set contains all signatures in the
6014         * existing one.
6015         */
6016        if (scannedCompatSet.equals(existingSet)) {
6017            // Migrate the old signatures to the new scheme.
6018            existingSigs.assignSignatures(scannedPkg.mSignatures);
6019            // The new KeySets will be re-added later in the scanning process.
6020            synchronized (mPackages) {
6021                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6022            }
6023            return PackageManager.SIGNATURE_MATCH;
6024        }
6025        return PackageManager.SIGNATURE_NO_MATCH;
6026    }
6027
6028    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6029        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6030        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6031    }
6032
6033    private int compareSignaturesRecover(PackageSignatures existingSigs,
6034            PackageParser.Package scannedPkg) {
6035        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6036            return PackageManager.SIGNATURE_NO_MATCH;
6037        }
6038
6039        String msg = null;
6040        try {
6041            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6042                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6043                        + scannedPkg.packageName);
6044                return PackageManager.SIGNATURE_MATCH;
6045            }
6046        } catch (CertificateException e) {
6047            msg = e.getMessage();
6048        }
6049
6050        logCriticalInfo(Log.INFO,
6051                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6052        return PackageManager.SIGNATURE_NO_MATCH;
6053    }
6054
6055    @Override
6056    public List<String> getAllPackages() {
6057        final int callingUid = Binder.getCallingUid();
6058        final int callingUserId = UserHandle.getUserId(callingUid);
6059        synchronized (mPackages) {
6060            if (canViewInstantApps(callingUid, callingUserId)) {
6061                return new ArrayList<String>(mPackages.keySet());
6062            }
6063            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6064            final List<String> result = new ArrayList<>();
6065            if (instantAppPkgName != null) {
6066                // caller is an instant application; filter unexposed applications
6067                for (PackageParser.Package pkg : mPackages.values()) {
6068                    if (!pkg.visibleToInstantApps) {
6069                        continue;
6070                    }
6071                    result.add(pkg.packageName);
6072                }
6073            } else {
6074                // caller is a normal application; filter instant applications
6075                for (PackageParser.Package pkg : mPackages.values()) {
6076                    final PackageSetting ps =
6077                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6078                    if (ps != null
6079                            && ps.getInstantApp(callingUserId)
6080                            && !mInstantAppRegistry.isInstantAccessGranted(
6081                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6082                        continue;
6083                    }
6084                    result.add(pkg.packageName);
6085                }
6086            }
6087            return result;
6088        }
6089    }
6090
6091    @Override
6092    public String[] getPackagesForUid(int uid) {
6093        final int callingUid = Binder.getCallingUid();
6094        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6095        final int userId = UserHandle.getUserId(uid);
6096        uid = UserHandle.getAppId(uid);
6097        // reader
6098        synchronized (mPackages) {
6099            Object obj = mSettings.getUserIdLPr(uid);
6100            if (obj instanceof SharedUserSetting) {
6101                if (isCallerInstantApp) {
6102                    return null;
6103                }
6104                final SharedUserSetting sus = (SharedUserSetting) obj;
6105                final int N = sus.packages.size();
6106                String[] res = new String[N];
6107                final Iterator<PackageSetting> it = sus.packages.iterator();
6108                int i = 0;
6109                while (it.hasNext()) {
6110                    PackageSetting ps = it.next();
6111                    if (ps.getInstalled(userId)) {
6112                        res[i++] = ps.name;
6113                    } else {
6114                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6115                    }
6116                }
6117                return res;
6118            } else if (obj instanceof PackageSetting) {
6119                final PackageSetting ps = (PackageSetting) obj;
6120                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6121                    return new String[]{ps.name};
6122                }
6123            }
6124        }
6125        return null;
6126    }
6127
6128    @Override
6129    public String getNameForUid(int uid) {
6130        final int callingUid = Binder.getCallingUid();
6131        if (getInstantAppPackageName(callingUid) != null) {
6132            return null;
6133        }
6134        synchronized (mPackages) {
6135            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6136            if (obj instanceof SharedUserSetting) {
6137                final SharedUserSetting sus = (SharedUserSetting) obj;
6138                return sus.name + ":" + sus.userId;
6139            } else if (obj instanceof PackageSetting) {
6140                final PackageSetting ps = (PackageSetting) obj;
6141                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6142                    return null;
6143                }
6144                return ps.name;
6145            }
6146        }
6147        return null;
6148    }
6149
6150    @Override
6151    public int getUidForSharedUser(String sharedUserName) {
6152        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6153            return -1;
6154        }
6155        if (sharedUserName == null) {
6156            return -1;
6157        }
6158        // reader
6159        synchronized (mPackages) {
6160            SharedUserSetting suid;
6161            try {
6162                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6163                if (suid != null) {
6164                    return suid.userId;
6165                }
6166            } catch (PackageManagerException ignore) {
6167                // can't happen, but, still need to catch it
6168            }
6169            return -1;
6170        }
6171    }
6172
6173    @Override
6174    public int getFlagsForUid(int uid) {
6175        final int callingUid = Binder.getCallingUid();
6176        if (getInstantAppPackageName(callingUid) != null) {
6177            return 0;
6178        }
6179        synchronized (mPackages) {
6180            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6181            if (obj instanceof SharedUserSetting) {
6182                final SharedUserSetting sus = (SharedUserSetting) obj;
6183                return sus.pkgFlags;
6184            } else if (obj instanceof PackageSetting) {
6185                final PackageSetting ps = (PackageSetting) obj;
6186                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6187                    return 0;
6188                }
6189                return ps.pkgFlags;
6190            }
6191        }
6192        return 0;
6193    }
6194
6195    @Override
6196    public int getPrivateFlagsForUid(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.pkgPrivateFlags;
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.pkgPrivateFlags;
6212            }
6213        }
6214        return 0;
6215    }
6216
6217    @Override
6218    public boolean isUidPrivileged(int uid) {
6219        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6220            return false;
6221        }
6222        uid = UserHandle.getAppId(uid);
6223        // reader
6224        synchronized (mPackages) {
6225            Object obj = mSettings.getUserIdLPr(uid);
6226            if (obj instanceof SharedUserSetting) {
6227                final SharedUserSetting sus = (SharedUserSetting) obj;
6228                final Iterator<PackageSetting> it = sus.packages.iterator();
6229                while (it.hasNext()) {
6230                    if (it.next().isPrivileged()) {
6231                        return true;
6232                    }
6233                }
6234            } else if (obj instanceof PackageSetting) {
6235                final PackageSetting ps = (PackageSetting) obj;
6236                return ps.isPrivileged();
6237            }
6238        }
6239        return false;
6240    }
6241
6242    @Override
6243    public String[] getAppOpPermissionPackages(String permissionName) {
6244        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6245            return null;
6246        }
6247        synchronized (mPackages) {
6248            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6249            if (pkgs == null) {
6250                return null;
6251            }
6252            return pkgs.toArray(new String[pkgs.size()]);
6253        }
6254    }
6255
6256    @Override
6257    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6258            int flags, int userId) {
6259        return resolveIntentInternal(
6260                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6261    }
6262
6263    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6264            int flags, int userId, boolean resolveForStart) {
6265        try {
6266            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6267
6268            if (!sUserManager.exists(userId)) return null;
6269            final int callingUid = Binder.getCallingUid();
6270            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6271            enforceCrossUserPermission(callingUid, userId,
6272                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6273
6274            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6275            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6276                    flags, callingUid, userId, resolveForStart);
6277            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6278
6279            final ResolveInfo bestChoice =
6280                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6281            return bestChoice;
6282        } finally {
6283            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6284        }
6285    }
6286
6287    @Override
6288    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6289        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6290            throw new SecurityException(
6291                    "findPersistentPreferredActivity can only be run by the system");
6292        }
6293        if (!sUserManager.exists(userId)) {
6294            return null;
6295        }
6296        final int callingUid = Binder.getCallingUid();
6297        intent = updateIntentForResolve(intent);
6298        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6299        final int flags = updateFlagsForResolve(
6300                0, userId, intent, callingUid, false /*includeInstantApps*/);
6301        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6302                userId);
6303        synchronized (mPackages) {
6304            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6305                    userId);
6306        }
6307    }
6308
6309    @Override
6310    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6311            IntentFilter filter, int match, ComponentName activity) {
6312        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6313            return;
6314        }
6315        final int userId = UserHandle.getCallingUserId();
6316        if (DEBUG_PREFERRED) {
6317            Log.v(TAG, "setLastChosenActivity intent=" + intent
6318                + " resolvedType=" + resolvedType
6319                + " flags=" + flags
6320                + " filter=" + filter
6321                + " match=" + match
6322                + " activity=" + activity);
6323            filter.dump(new PrintStreamPrinter(System.out), "    ");
6324        }
6325        intent.setComponent(null);
6326        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6327                userId);
6328        // Find any earlier preferred or last chosen entries and nuke them
6329        findPreferredActivity(intent, resolvedType,
6330                flags, query, 0, false, true, false, userId);
6331        // Add the new activity as the last chosen for this filter
6332        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6333                "Setting last chosen");
6334    }
6335
6336    @Override
6337    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6338        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6339            return null;
6340        }
6341        final int userId = UserHandle.getCallingUserId();
6342        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6343        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6344                userId);
6345        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6346                false, false, false, userId);
6347    }
6348
6349    /**
6350     * Returns whether or not instant apps have been disabled remotely.
6351     */
6352    private boolean isEphemeralDisabled() {
6353        return mEphemeralAppsDisabled;
6354    }
6355
6356    private boolean isInstantAppAllowed(
6357            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6358            boolean skipPackageCheck) {
6359        if (mInstantAppResolverConnection == null) {
6360            return false;
6361        }
6362        if (mInstantAppInstallerActivity == null) {
6363            return false;
6364        }
6365        if (intent.getComponent() != null) {
6366            return false;
6367        }
6368        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6369            return false;
6370        }
6371        if (!skipPackageCheck && intent.getPackage() != null) {
6372            return false;
6373        }
6374        final boolean isWebUri = hasWebURI(intent);
6375        if (!isWebUri || intent.getData().getHost() == null) {
6376            return false;
6377        }
6378        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6379        // Or if there's already an ephemeral app installed that handles the action
6380        synchronized (mPackages) {
6381            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6382            for (int n = 0; n < count; n++) {
6383                final ResolveInfo info = resolvedActivities.get(n);
6384                final String packageName = info.activityInfo.packageName;
6385                final PackageSetting ps = mSettings.mPackages.get(packageName);
6386                if (ps != null) {
6387                    // only check domain verification status if the app is not a browser
6388                    if (!info.handleAllWebDataURI) {
6389                        // Try to get the status from User settings first
6390                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6391                        final int status = (int) (packedStatus >> 32);
6392                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6393                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6394                            if (DEBUG_EPHEMERAL) {
6395                                Slog.v(TAG, "DENY instant app;"
6396                                    + " pkg: " + packageName + ", status: " + status);
6397                            }
6398                            return false;
6399                        }
6400                    }
6401                    if (ps.getInstantApp(userId)) {
6402                        if (DEBUG_EPHEMERAL) {
6403                            Slog.v(TAG, "DENY instant app installed;"
6404                                    + " pkg: " + packageName);
6405                        }
6406                        return false;
6407                    }
6408                }
6409            }
6410        }
6411        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6412        return true;
6413    }
6414
6415    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6416            Intent origIntent, String resolvedType, String callingPackage,
6417            Bundle verificationBundle, int userId) {
6418        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6419                new InstantAppRequest(responseObj, origIntent, resolvedType,
6420                        callingPackage, userId, verificationBundle));
6421        mHandler.sendMessage(msg);
6422    }
6423
6424    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6425            int flags, List<ResolveInfo> query, int userId) {
6426        if (query != null) {
6427            final int N = query.size();
6428            if (N == 1) {
6429                return query.get(0);
6430            } else if (N > 1) {
6431                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6432                // If there is more than one activity with the same priority,
6433                // then let the user decide between them.
6434                ResolveInfo r0 = query.get(0);
6435                ResolveInfo r1 = query.get(1);
6436                if (DEBUG_INTENT_MATCHING || debug) {
6437                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6438                            + r1.activityInfo.name + "=" + r1.priority);
6439                }
6440                // If the first activity has a higher priority, or a different
6441                // default, then it is always desirable to pick it.
6442                if (r0.priority != r1.priority
6443                        || r0.preferredOrder != r1.preferredOrder
6444                        || r0.isDefault != r1.isDefault) {
6445                    return query.get(0);
6446                }
6447                // If we have saved a preference for a preferred activity for
6448                // this Intent, use that.
6449                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6450                        flags, query, r0.priority, true, false, debug, userId);
6451                if (ri != null) {
6452                    return ri;
6453                }
6454                // If we have an ephemeral app, use it
6455                for (int i = 0; i < N; i++) {
6456                    ri = query.get(i);
6457                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6458                        final String packageName = ri.activityInfo.packageName;
6459                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6460                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6461                        final int status = (int)(packedStatus >> 32);
6462                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6463                            return ri;
6464                        }
6465                    }
6466                }
6467                ri = new ResolveInfo(mResolveInfo);
6468                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6469                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6470                // If all of the options come from the same package, show the application's
6471                // label and icon instead of the generic resolver's.
6472                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6473                // and then throw away the ResolveInfo itself, meaning that the caller loses
6474                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6475                // a fallback for this case; we only set the target package's resources on
6476                // the ResolveInfo, not the ActivityInfo.
6477                final String intentPackage = intent.getPackage();
6478                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6479                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6480                    ri.resolvePackageName = intentPackage;
6481                    if (userNeedsBadging(userId)) {
6482                        ri.noResourceId = true;
6483                    } else {
6484                        ri.icon = appi.icon;
6485                    }
6486                    ri.iconResourceId = appi.icon;
6487                    ri.labelRes = appi.labelRes;
6488                }
6489                ri.activityInfo.applicationInfo = new ApplicationInfo(
6490                        ri.activityInfo.applicationInfo);
6491                if (userId != 0) {
6492                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6493                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6494                }
6495                // Make sure that the resolver is displayable in car mode
6496                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6497                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6498                return ri;
6499            }
6500        }
6501        return null;
6502    }
6503
6504    /**
6505     * Return true if the given list is not empty and all of its contents have
6506     * an activityInfo with the given package name.
6507     */
6508    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6509        if (ArrayUtils.isEmpty(list)) {
6510            return false;
6511        }
6512        for (int i = 0, N = list.size(); i < N; i++) {
6513            final ResolveInfo ri = list.get(i);
6514            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6515            if (ai == null || !packageName.equals(ai.packageName)) {
6516                return false;
6517            }
6518        }
6519        return true;
6520    }
6521
6522    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6523            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6524        final int N = query.size();
6525        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6526                .get(userId);
6527        // Get the list of persistent preferred activities that handle the intent
6528        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6529        List<PersistentPreferredActivity> pprefs = ppir != null
6530                ? ppir.queryIntent(intent, resolvedType,
6531                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6532                        userId)
6533                : null;
6534        if (pprefs != null && pprefs.size() > 0) {
6535            final int M = pprefs.size();
6536            for (int i=0; i<M; i++) {
6537                final PersistentPreferredActivity ppa = pprefs.get(i);
6538                if (DEBUG_PREFERRED || debug) {
6539                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6540                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6541                            + "\n  component=" + ppa.mComponent);
6542                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6543                }
6544                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6545                        flags | MATCH_DISABLED_COMPONENTS, userId);
6546                if (DEBUG_PREFERRED || debug) {
6547                    Slog.v(TAG, "Found persistent preferred activity:");
6548                    if (ai != null) {
6549                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6550                    } else {
6551                        Slog.v(TAG, "  null");
6552                    }
6553                }
6554                if (ai == null) {
6555                    // This previously registered persistent preferred activity
6556                    // component is no longer known. Ignore it and do NOT remove it.
6557                    continue;
6558                }
6559                for (int j=0; j<N; j++) {
6560                    final ResolveInfo ri = query.get(j);
6561                    if (!ri.activityInfo.applicationInfo.packageName
6562                            .equals(ai.applicationInfo.packageName)) {
6563                        continue;
6564                    }
6565                    if (!ri.activityInfo.name.equals(ai.name)) {
6566                        continue;
6567                    }
6568                    //  Found a persistent preference that can handle the intent.
6569                    if (DEBUG_PREFERRED || debug) {
6570                        Slog.v(TAG, "Returning persistent preferred activity: " +
6571                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6572                    }
6573                    return ri;
6574                }
6575            }
6576        }
6577        return null;
6578    }
6579
6580    // TODO: handle preferred activities missing while user has amnesia
6581    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6582            List<ResolveInfo> query, int priority, boolean always,
6583            boolean removeMatches, boolean debug, int userId) {
6584        if (!sUserManager.exists(userId)) return null;
6585        final int callingUid = Binder.getCallingUid();
6586        flags = updateFlagsForResolve(
6587                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6588        intent = updateIntentForResolve(intent);
6589        // writer
6590        synchronized (mPackages) {
6591            // Try to find a matching persistent preferred activity.
6592            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6593                    debug, userId);
6594
6595            // If a persistent preferred activity matched, use it.
6596            if (pri != null) {
6597                return pri;
6598            }
6599
6600            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6601            // Get the list of preferred activities that handle the intent
6602            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6603            List<PreferredActivity> prefs = pir != null
6604                    ? pir.queryIntent(intent, resolvedType,
6605                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6606                            userId)
6607                    : null;
6608            if (prefs != null && prefs.size() > 0) {
6609                boolean changed = false;
6610                try {
6611                    // First figure out how good the original match set is.
6612                    // We will only allow preferred activities that came
6613                    // from the same match quality.
6614                    int match = 0;
6615
6616                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6617
6618                    final int N = query.size();
6619                    for (int j=0; j<N; j++) {
6620                        final ResolveInfo ri = query.get(j);
6621                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6622                                + ": 0x" + Integer.toHexString(match));
6623                        if (ri.match > match) {
6624                            match = ri.match;
6625                        }
6626                    }
6627
6628                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6629                            + Integer.toHexString(match));
6630
6631                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6632                    final int M = prefs.size();
6633                    for (int i=0; i<M; i++) {
6634                        final PreferredActivity pa = prefs.get(i);
6635                        if (DEBUG_PREFERRED || debug) {
6636                            Slog.v(TAG, "Checking PreferredActivity ds="
6637                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6638                                    + "\n  component=" + pa.mPref.mComponent);
6639                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6640                        }
6641                        if (pa.mPref.mMatch != match) {
6642                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6643                                    + Integer.toHexString(pa.mPref.mMatch));
6644                            continue;
6645                        }
6646                        // If it's not an "always" type preferred activity and that's what we're
6647                        // looking for, skip it.
6648                        if (always && !pa.mPref.mAlways) {
6649                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6650                            continue;
6651                        }
6652                        final ActivityInfo ai = getActivityInfo(
6653                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6654                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6655                                userId);
6656                        if (DEBUG_PREFERRED || debug) {
6657                            Slog.v(TAG, "Found preferred activity:");
6658                            if (ai != null) {
6659                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6660                            } else {
6661                                Slog.v(TAG, "  null");
6662                            }
6663                        }
6664                        if (ai == null) {
6665                            // This previously registered preferred activity
6666                            // component is no longer known.  Most likely an update
6667                            // to the app was installed and in the new version this
6668                            // component no longer exists.  Clean it up by removing
6669                            // it from the preferred activities list, and skip it.
6670                            Slog.w(TAG, "Removing dangling preferred activity: "
6671                                    + pa.mPref.mComponent);
6672                            pir.removeFilter(pa);
6673                            changed = true;
6674                            continue;
6675                        }
6676                        for (int j=0; j<N; j++) {
6677                            final ResolveInfo ri = query.get(j);
6678                            if (!ri.activityInfo.applicationInfo.packageName
6679                                    .equals(ai.applicationInfo.packageName)) {
6680                                continue;
6681                            }
6682                            if (!ri.activityInfo.name.equals(ai.name)) {
6683                                continue;
6684                            }
6685
6686                            if (removeMatches) {
6687                                pir.removeFilter(pa);
6688                                changed = true;
6689                                if (DEBUG_PREFERRED) {
6690                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6691                                }
6692                                break;
6693                            }
6694
6695                            // Okay we found a previously set preferred or last chosen app.
6696                            // If the result set is different from when this
6697                            // was created, we need to clear it and re-ask the
6698                            // user their preference, if we're looking for an "always" type entry.
6699                            if (always && !pa.mPref.sameSet(query)) {
6700                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6701                                        + intent + " type " + resolvedType);
6702                                if (DEBUG_PREFERRED) {
6703                                    Slog.v(TAG, "Removing preferred activity since set changed "
6704                                            + pa.mPref.mComponent);
6705                                }
6706                                pir.removeFilter(pa);
6707                                // Re-add the filter as a "last chosen" entry (!always)
6708                                PreferredActivity lastChosen = new PreferredActivity(
6709                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6710                                pir.addFilter(lastChosen);
6711                                changed = true;
6712                                return null;
6713                            }
6714
6715                            // Yay! Either the set matched or we're looking for the last chosen
6716                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6717                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6718                            return ri;
6719                        }
6720                    }
6721                } finally {
6722                    if (changed) {
6723                        if (DEBUG_PREFERRED) {
6724                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6725                        }
6726                        scheduleWritePackageRestrictionsLocked(userId);
6727                    }
6728                }
6729            }
6730        }
6731        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6732        return null;
6733    }
6734
6735    /*
6736     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6737     */
6738    @Override
6739    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6740            int targetUserId) {
6741        mContext.enforceCallingOrSelfPermission(
6742                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6743        List<CrossProfileIntentFilter> matches =
6744                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6745        if (matches != null) {
6746            int size = matches.size();
6747            for (int i = 0; i < size; i++) {
6748                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6749            }
6750        }
6751        if (hasWebURI(intent)) {
6752            // cross-profile app linking works only towards the parent.
6753            final int callingUid = Binder.getCallingUid();
6754            final UserInfo parent = getProfileParent(sourceUserId);
6755            synchronized(mPackages) {
6756                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6757                        false /*includeInstantApps*/);
6758                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6759                        intent, resolvedType, flags, sourceUserId, parent.id);
6760                return xpDomainInfo != null;
6761            }
6762        }
6763        return false;
6764    }
6765
6766    private UserInfo getProfileParent(int userId) {
6767        final long identity = Binder.clearCallingIdentity();
6768        try {
6769            return sUserManager.getProfileParent(userId);
6770        } finally {
6771            Binder.restoreCallingIdentity(identity);
6772        }
6773    }
6774
6775    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6776            String resolvedType, int userId) {
6777        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6778        if (resolver != null) {
6779            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6780        }
6781        return null;
6782    }
6783
6784    @Override
6785    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6786            String resolvedType, int flags, int userId) {
6787        try {
6788            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6789
6790            return new ParceledListSlice<>(
6791                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6792        } finally {
6793            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6794        }
6795    }
6796
6797    /**
6798     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6799     * instant, returns {@code null}.
6800     */
6801    private String getInstantAppPackageName(int callingUid) {
6802        synchronized (mPackages) {
6803            // If the caller is an isolated app use the owner's uid for the lookup.
6804            if (Process.isIsolated(callingUid)) {
6805                callingUid = mIsolatedOwners.get(callingUid);
6806            }
6807            final int appId = UserHandle.getAppId(callingUid);
6808            final Object obj = mSettings.getUserIdLPr(appId);
6809            if (obj instanceof PackageSetting) {
6810                final PackageSetting ps = (PackageSetting) obj;
6811                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6812                return isInstantApp ? ps.pkg.packageName : null;
6813            }
6814        }
6815        return null;
6816    }
6817
6818    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6819            String resolvedType, int flags, int userId) {
6820        return queryIntentActivitiesInternal(
6821                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6822    }
6823
6824    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6825            String resolvedType, int flags, int filterCallingUid, int userId,
6826            boolean resolveForStart) {
6827        if (!sUserManager.exists(userId)) return Collections.emptyList();
6828        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6829        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6830                false /* requireFullPermission */, false /* checkShell */,
6831                "query intent activities");
6832        final String pkgName = intent.getPackage();
6833        ComponentName comp = intent.getComponent();
6834        if (comp == null) {
6835            if (intent.getSelector() != null) {
6836                intent = intent.getSelector();
6837                comp = intent.getComponent();
6838            }
6839        }
6840
6841        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6842                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6843        if (comp != null) {
6844            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6845            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6846            if (ai != null) {
6847                // When specifying an explicit component, we prevent the activity from being
6848                // used when either 1) the calling package is normal and the activity is within
6849                // an ephemeral application or 2) the calling package is ephemeral and the
6850                // activity is not visible to ephemeral applications.
6851                final boolean matchInstantApp =
6852                        (flags & PackageManager.MATCH_INSTANT) != 0;
6853                final boolean matchVisibleToInstantAppOnly =
6854                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6855                final boolean matchExplicitlyVisibleOnly =
6856                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6857                final boolean isCallerInstantApp =
6858                        instantAppPkgName != null;
6859                final boolean isTargetSameInstantApp =
6860                        comp.getPackageName().equals(instantAppPkgName);
6861                final boolean isTargetInstantApp =
6862                        (ai.applicationInfo.privateFlags
6863                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6864                final boolean isTargetVisibleToInstantApp =
6865                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6866                final boolean isTargetExplicitlyVisibleToInstantApp =
6867                        isTargetVisibleToInstantApp
6868                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6869                final boolean isTargetHiddenFromInstantApp =
6870                        !isTargetVisibleToInstantApp
6871                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6872                final boolean blockResolution =
6873                        !isTargetSameInstantApp
6874                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6875                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6876                                        && isTargetHiddenFromInstantApp));
6877                if (!blockResolution) {
6878                    final ResolveInfo ri = new ResolveInfo();
6879                    ri.activityInfo = ai;
6880                    list.add(ri);
6881                }
6882            }
6883            return applyPostResolutionFilter(list, instantAppPkgName);
6884        }
6885
6886        // reader
6887        boolean sortResult = false;
6888        boolean addEphemeral = false;
6889        List<ResolveInfo> result;
6890        final boolean ephemeralDisabled = isEphemeralDisabled();
6891        synchronized (mPackages) {
6892            if (pkgName == null) {
6893                List<CrossProfileIntentFilter> matchingFilters =
6894                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6895                // Check for results that need to skip the current profile.
6896                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6897                        resolvedType, flags, userId);
6898                if (xpResolveInfo != null) {
6899                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6900                    xpResult.add(xpResolveInfo);
6901                    return applyPostResolutionFilter(
6902                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6903                }
6904
6905                // Check for results in the current profile.
6906                result = filterIfNotSystemUser(mActivities.queryIntent(
6907                        intent, resolvedType, flags, userId), userId);
6908                addEphemeral = !ephemeralDisabled
6909                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6910                // Check for cross profile results.
6911                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6912                xpResolveInfo = queryCrossProfileIntents(
6913                        matchingFilters, intent, resolvedType, flags, userId,
6914                        hasNonNegativePriorityResult);
6915                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6916                    boolean isVisibleToUser = filterIfNotSystemUser(
6917                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6918                    if (isVisibleToUser) {
6919                        result.add(xpResolveInfo);
6920                        sortResult = true;
6921                    }
6922                }
6923                if (hasWebURI(intent)) {
6924                    CrossProfileDomainInfo xpDomainInfo = null;
6925                    final UserInfo parent = getProfileParent(userId);
6926                    if (parent != null) {
6927                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6928                                flags, userId, parent.id);
6929                    }
6930                    if (xpDomainInfo != null) {
6931                        if (xpResolveInfo != null) {
6932                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6933                            // in the result.
6934                            result.remove(xpResolveInfo);
6935                        }
6936                        if (result.size() == 0 && !addEphemeral) {
6937                            // No result in current profile, but found candidate in parent user.
6938                            // And we are not going to add emphemeral app, so we can return the
6939                            // result straight away.
6940                            result.add(xpDomainInfo.resolveInfo);
6941                            return applyPostResolutionFilter(result, instantAppPkgName);
6942                        }
6943                    } else if (result.size() <= 1 && !addEphemeral) {
6944                        // No result in parent user and <= 1 result in current profile, and we
6945                        // are not going to add emphemeral app, so we can return the result without
6946                        // further processing.
6947                        return applyPostResolutionFilter(result, instantAppPkgName);
6948                    }
6949                    // We have more than one candidate (combining results from current and parent
6950                    // profile), so we need filtering and sorting.
6951                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6952                            intent, flags, result, xpDomainInfo, userId);
6953                    sortResult = true;
6954                }
6955            } else {
6956                final PackageParser.Package pkg = mPackages.get(pkgName);
6957                result = null;
6958                if (pkg != null) {
6959                    result = filterIfNotSystemUser(
6960                            mActivities.queryIntentForPackage(
6961                                    intent, resolvedType, flags, pkg.activities, userId),
6962                            userId);
6963                }
6964                if (result == null || result.size() == 0) {
6965                    // the caller wants to resolve for a particular package; however, there
6966                    // were no installed results, so, try to find an ephemeral result
6967                    addEphemeral = !ephemeralDisabled
6968                            && isInstantAppAllowed(
6969                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6970                    if (result == null) {
6971                        result = new ArrayList<>();
6972                    }
6973                }
6974            }
6975        }
6976        if (addEphemeral) {
6977            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
6978        }
6979        if (sortResult) {
6980            Collections.sort(result, mResolvePrioritySorter);
6981        }
6982        return applyPostResolutionFilter(result, instantAppPkgName);
6983    }
6984
6985    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6986            String resolvedType, int flags, int userId) {
6987        // first, check to see if we've got an instant app already installed
6988        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6989        ResolveInfo localInstantApp = null;
6990        boolean blockResolution = false;
6991        if (!alreadyResolvedLocally) {
6992            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6993                    flags
6994                        | PackageManager.GET_RESOLVED_FILTER
6995                        | PackageManager.MATCH_INSTANT
6996                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6997                    userId);
6998            for (int i = instantApps.size() - 1; i >= 0; --i) {
6999                final ResolveInfo info = instantApps.get(i);
7000                final String packageName = info.activityInfo.packageName;
7001                final PackageSetting ps = mSettings.mPackages.get(packageName);
7002                if (ps.getInstantApp(userId)) {
7003                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7004                    final int status = (int)(packedStatus >> 32);
7005                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7006                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7007                        // there's a local instant application installed, but, the user has
7008                        // chosen to never use it; skip resolution and don't acknowledge
7009                        // an instant application is even available
7010                        if (DEBUG_EPHEMERAL) {
7011                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7012                        }
7013                        blockResolution = true;
7014                        break;
7015                    } else {
7016                        // we have a locally installed instant application; skip resolution
7017                        // but acknowledge there's an instant application available
7018                        if (DEBUG_EPHEMERAL) {
7019                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7020                        }
7021                        localInstantApp = info;
7022                        break;
7023                    }
7024                }
7025            }
7026        }
7027        // no app installed, let's see if one's available
7028        AuxiliaryResolveInfo auxiliaryResponse = null;
7029        if (!blockResolution) {
7030            if (localInstantApp == null) {
7031                // we don't have an instant app locally, resolve externally
7032                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7033                final InstantAppRequest requestObject = new InstantAppRequest(
7034                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7035                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7036                auxiliaryResponse =
7037                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7038                                mContext, mInstantAppResolverConnection, requestObject);
7039                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7040            } else {
7041                // we have an instant application locally, but, we can't admit that since
7042                // callers shouldn't be able to determine prior browsing. create a dummy
7043                // auxiliary response so the downstream code behaves as if there's an
7044                // instant application available externally. when it comes time to start
7045                // the instant application, we'll do the right thing.
7046                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7047                auxiliaryResponse = new AuxiliaryResolveInfo(
7048                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7049            }
7050        }
7051        if (auxiliaryResponse != null) {
7052            if (DEBUG_EPHEMERAL) {
7053                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7054            }
7055            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7056            final PackageSetting ps =
7057                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7058            if (ps != null) {
7059                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7060                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7061                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7062                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7063                // make sure this resolver is the default
7064                ephemeralInstaller.isDefault = true;
7065                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7066                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7067                // add a non-generic filter
7068                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7069                ephemeralInstaller.filter.addDataPath(
7070                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7071                ephemeralInstaller.isInstantAppAvailable = true;
7072                result.add(ephemeralInstaller);
7073            }
7074        }
7075        return result;
7076    }
7077
7078    private static class CrossProfileDomainInfo {
7079        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7080        ResolveInfo resolveInfo;
7081        /* Best domain verification status of the activities found in the other profile */
7082        int bestDomainVerificationStatus;
7083    }
7084
7085    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7086            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7087        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7088                sourceUserId)) {
7089            return null;
7090        }
7091        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7092                resolvedType, flags, parentUserId);
7093
7094        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7095            return null;
7096        }
7097        CrossProfileDomainInfo result = null;
7098        int size = resultTargetUser.size();
7099        for (int i = 0; i < size; i++) {
7100            ResolveInfo riTargetUser = resultTargetUser.get(i);
7101            // Intent filter verification is only for filters that specify a host. So don't return
7102            // those that handle all web uris.
7103            if (riTargetUser.handleAllWebDataURI) {
7104                continue;
7105            }
7106            String packageName = riTargetUser.activityInfo.packageName;
7107            PackageSetting ps = mSettings.mPackages.get(packageName);
7108            if (ps == null) {
7109                continue;
7110            }
7111            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7112            int status = (int)(verificationState >> 32);
7113            if (result == null) {
7114                result = new CrossProfileDomainInfo();
7115                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7116                        sourceUserId, parentUserId);
7117                result.bestDomainVerificationStatus = status;
7118            } else {
7119                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7120                        result.bestDomainVerificationStatus);
7121            }
7122        }
7123        // Don't consider matches with status NEVER across profiles.
7124        if (result != null && result.bestDomainVerificationStatus
7125                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7126            return null;
7127        }
7128        return result;
7129    }
7130
7131    /**
7132     * Verification statuses are ordered from the worse to the best, except for
7133     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7134     */
7135    private int bestDomainVerificationStatus(int status1, int status2) {
7136        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7137            return status2;
7138        }
7139        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7140            return status1;
7141        }
7142        return (int) MathUtils.max(status1, status2);
7143    }
7144
7145    private boolean isUserEnabled(int userId) {
7146        long callingId = Binder.clearCallingIdentity();
7147        try {
7148            UserInfo userInfo = sUserManager.getUserInfo(userId);
7149            return userInfo != null && userInfo.isEnabled();
7150        } finally {
7151            Binder.restoreCallingIdentity(callingId);
7152        }
7153    }
7154
7155    /**
7156     * Filter out activities with systemUserOnly flag set, when current user is not System.
7157     *
7158     * @return filtered list
7159     */
7160    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7161        if (userId == UserHandle.USER_SYSTEM) {
7162            return resolveInfos;
7163        }
7164        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7165            ResolveInfo info = resolveInfos.get(i);
7166            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7167                resolveInfos.remove(i);
7168            }
7169        }
7170        return resolveInfos;
7171    }
7172
7173    /**
7174     * Filters out ephemeral activities.
7175     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7176     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7177     *
7178     * @param resolveInfos The pre-filtered list of resolved activities
7179     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7180     *          is performed.
7181     * @return A filtered list of resolved activities.
7182     */
7183    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7184            String ephemeralPkgName) {
7185        // TODO: When adding on-demand split support for non-instant apps, remove this check
7186        // and always apply post filtering
7187        if (ephemeralPkgName == null) {
7188            return resolveInfos;
7189        }
7190        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7191            final ResolveInfo info = resolveInfos.get(i);
7192            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7193            // allow activities that are defined in the provided package
7194            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
7195                if (info.activityInfo.splitName != null
7196                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7197                                info.activityInfo.splitName)) {
7198                    // requested activity is defined in a split that hasn't been installed yet.
7199                    // add the installer to the resolve list
7200                    if (DEBUG_EPHEMERAL) {
7201                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7202                    }
7203                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7204                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7205                            info.activityInfo.packageName, info.activityInfo.splitName,
7206                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7207                    // make sure this resolver is the default
7208                    installerInfo.isDefault = true;
7209                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7210                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7211                    // add a non-generic filter
7212                    installerInfo.filter = new IntentFilter();
7213                    // load resources from the correct package
7214                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7215                    resolveInfos.set(i, installerInfo);
7216                }
7217                continue;
7218            }
7219            // allow activities that have been explicitly exposed to ephemeral apps
7220            if (!isEphemeralApp
7221                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7222                continue;
7223            }
7224            resolveInfos.remove(i);
7225        }
7226        return resolveInfos;
7227    }
7228
7229    /**
7230     * @param resolveInfos list of resolve infos in descending priority order
7231     * @return if the list contains a resolve info with non-negative priority
7232     */
7233    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7234        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7235    }
7236
7237    private static boolean hasWebURI(Intent intent) {
7238        if (intent.getData() == null) {
7239            return false;
7240        }
7241        final String scheme = intent.getScheme();
7242        if (TextUtils.isEmpty(scheme)) {
7243            return false;
7244        }
7245        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7246    }
7247
7248    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7249            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7250            int userId) {
7251        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7252
7253        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7254            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7255                    candidates.size());
7256        }
7257
7258        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7259        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7260        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7261        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7262        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7263        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7264
7265        synchronized (mPackages) {
7266            final int count = candidates.size();
7267            // First, try to use linked apps. Partition the candidates into four lists:
7268            // one for the final results, one for the "do not use ever", one for "undefined status"
7269            // and finally one for "browser app type".
7270            for (int n=0; n<count; n++) {
7271                ResolveInfo info = candidates.get(n);
7272                String packageName = info.activityInfo.packageName;
7273                PackageSetting ps = mSettings.mPackages.get(packageName);
7274                if (ps != null) {
7275                    // Add to the special match all list (Browser use case)
7276                    if (info.handleAllWebDataURI) {
7277                        matchAllList.add(info);
7278                        continue;
7279                    }
7280                    // Try to get the status from User settings first
7281                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7282                    int status = (int)(packedStatus >> 32);
7283                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7284                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7285                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7286                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7287                                    + " : linkgen=" + linkGeneration);
7288                        }
7289                        // Use link-enabled generation as preferredOrder, i.e.
7290                        // prefer newly-enabled over earlier-enabled.
7291                        info.preferredOrder = linkGeneration;
7292                        alwaysList.add(info);
7293                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7294                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7295                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7296                        }
7297                        neverList.add(info);
7298                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7299                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7300                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7301                        }
7302                        alwaysAskList.add(info);
7303                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7304                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7305                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7306                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7307                        }
7308                        undefinedList.add(info);
7309                    }
7310                }
7311            }
7312
7313            // We'll want to include browser possibilities in a few cases
7314            boolean includeBrowser = false;
7315
7316            // First try to add the "always" resolution(s) for the current user, if any
7317            if (alwaysList.size() > 0) {
7318                result.addAll(alwaysList);
7319            } else {
7320                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7321                result.addAll(undefinedList);
7322                // Maybe add one for the other profile.
7323                if (xpDomainInfo != null && (
7324                        xpDomainInfo.bestDomainVerificationStatus
7325                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7326                    result.add(xpDomainInfo.resolveInfo);
7327                }
7328                includeBrowser = true;
7329            }
7330
7331            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7332            // If there were 'always' entries their preferred order has been set, so we also
7333            // back that off to make the alternatives equivalent
7334            if (alwaysAskList.size() > 0) {
7335                for (ResolveInfo i : result) {
7336                    i.preferredOrder = 0;
7337                }
7338                result.addAll(alwaysAskList);
7339                includeBrowser = true;
7340            }
7341
7342            if (includeBrowser) {
7343                // Also add browsers (all of them or only the default one)
7344                if (DEBUG_DOMAIN_VERIFICATION) {
7345                    Slog.v(TAG, "   ...including browsers in candidate set");
7346                }
7347                if ((matchFlags & MATCH_ALL) != 0) {
7348                    result.addAll(matchAllList);
7349                } else {
7350                    // Browser/generic handling case.  If there's a default browser, go straight
7351                    // to that (but only if there is no other higher-priority match).
7352                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7353                    int maxMatchPrio = 0;
7354                    ResolveInfo defaultBrowserMatch = null;
7355                    final int numCandidates = matchAllList.size();
7356                    for (int n = 0; n < numCandidates; n++) {
7357                        ResolveInfo info = matchAllList.get(n);
7358                        // track the highest overall match priority...
7359                        if (info.priority > maxMatchPrio) {
7360                            maxMatchPrio = info.priority;
7361                        }
7362                        // ...and the highest-priority default browser match
7363                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7364                            if (defaultBrowserMatch == null
7365                                    || (defaultBrowserMatch.priority < info.priority)) {
7366                                if (debug) {
7367                                    Slog.v(TAG, "Considering default browser match " + info);
7368                                }
7369                                defaultBrowserMatch = info;
7370                            }
7371                        }
7372                    }
7373                    if (defaultBrowserMatch != null
7374                            && defaultBrowserMatch.priority >= maxMatchPrio
7375                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7376                    {
7377                        if (debug) {
7378                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7379                        }
7380                        result.add(defaultBrowserMatch);
7381                    } else {
7382                        result.addAll(matchAllList);
7383                    }
7384                }
7385
7386                // If there is nothing selected, add all candidates and remove the ones that the user
7387                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7388                if (result.size() == 0) {
7389                    result.addAll(candidates);
7390                    result.removeAll(neverList);
7391                }
7392            }
7393        }
7394        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7395            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7396                    result.size());
7397            for (ResolveInfo info : result) {
7398                Slog.v(TAG, "  + " + info.activityInfo);
7399            }
7400        }
7401        return result;
7402    }
7403
7404    // Returns a packed value as a long:
7405    //
7406    // high 'int'-sized word: link status: undefined/ask/never/always.
7407    // low 'int'-sized word: relative priority among 'always' results.
7408    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7409        long result = ps.getDomainVerificationStatusForUser(userId);
7410        // if none available, get the master status
7411        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7412            if (ps.getIntentFilterVerificationInfo() != null) {
7413                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7414            }
7415        }
7416        return result;
7417    }
7418
7419    private ResolveInfo querySkipCurrentProfileIntents(
7420            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7421            int flags, int sourceUserId) {
7422        if (matchingFilters != null) {
7423            int size = matchingFilters.size();
7424            for (int i = 0; i < size; i ++) {
7425                CrossProfileIntentFilter filter = matchingFilters.get(i);
7426                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7427                    // Checking if there are activities in the target user that can handle the
7428                    // intent.
7429                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7430                            resolvedType, flags, sourceUserId);
7431                    if (resolveInfo != null) {
7432                        return resolveInfo;
7433                    }
7434                }
7435            }
7436        }
7437        return null;
7438    }
7439
7440    // Return matching ResolveInfo in target user if any.
7441    private ResolveInfo queryCrossProfileIntents(
7442            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7443            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7444        if (matchingFilters != null) {
7445            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7446            // match the same intent. For performance reasons, it is better not to
7447            // run queryIntent twice for the same userId
7448            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7449            int size = matchingFilters.size();
7450            for (int i = 0; i < size; i++) {
7451                CrossProfileIntentFilter filter = matchingFilters.get(i);
7452                int targetUserId = filter.getTargetUserId();
7453                boolean skipCurrentProfile =
7454                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7455                boolean skipCurrentProfileIfNoMatchFound =
7456                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7457                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7458                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7459                    // Checking if there are activities in the target user that can handle the
7460                    // intent.
7461                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7462                            resolvedType, flags, sourceUserId);
7463                    if (resolveInfo != null) return resolveInfo;
7464                    alreadyTriedUserIds.put(targetUserId, true);
7465                }
7466            }
7467        }
7468        return null;
7469    }
7470
7471    /**
7472     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7473     * will forward the intent to the filter's target user.
7474     * Otherwise, returns null.
7475     */
7476    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7477            String resolvedType, int flags, int sourceUserId) {
7478        int targetUserId = filter.getTargetUserId();
7479        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7480                resolvedType, flags, targetUserId);
7481        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7482            // If all the matches in the target profile are suspended, return null.
7483            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7484                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7485                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7486                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7487                            targetUserId);
7488                }
7489            }
7490        }
7491        return null;
7492    }
7493
7494    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7495            int sourceUserId, int targetUserId) {
7496        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7497        long ident = Binder.clearCallingIdentity();
7498        boolean targetIsProfile;
7499        try {
7500            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7501        } finally {
7502            Binder.restoreCallingIdentity(ident);
7503        }
7504        String className;
7505        if (targetIsProfile) {
7506            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7507        } else {
7508            className = FORWARD_INTENT_TO_PARENT;
7509        }
7510        ComponentName forwardingActivityComponentName = new ComponentName(
7511                mAndroidApplication.packageName, className);
7512        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7513                sourceUserId);
7514        if (!targetIsProfile) {
7515            forwardingActivityInfo.showUserIcon = targetUserId;
7516            forwardingResolveInfo.noResourceId = true;
7517        }
7518        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7519        forwardingResolveInfo.priority = 0;
7520        forwardingResolveInfo.preferredOrder = 0;
7521        forwardingResolveInfo.match = 0;
7522        forwardingResolveInfo.isDefault = true;
7523        forwardingResolveInfo.filter = filter;
7524        forwardingResolveInfo.targetUserId = targetUserId;
7525        return forwardingResolveInfo;
7526    }
7527
7528    @Override
7529    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7530            Intent[] specifics, String[] specificTypes, Intent intent,
7531            String resolvedType, int flags, int userId) {
7532        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7533                specificTypes, intent, resolvedType, flags, userId));
7534    }
7535
7536    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7537            Intent[] specifics, String[] specificTypes, Intent intent,
7538            String resolvedType, int flags, int userId) {
7539        if (!sUserManager.exists(userId)) return Collections.emptyList();
7540        final int callingUid = Binder.getCallingUid();
7541        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7542                false /*includeInstantApps*/);
7543        enforceCrossUserPermission(callingUid, userId,
7544                false /*requireFullPermission*/, false /*checkShell*/,
7545                "query intent activity options");
7546        final String resultsAction = intent.getAction();
7547
7548        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7549                | PackageManager.GET_RESOLVED_FILTER, userId);
7550
7551        if (DEBUG_INTENT_MATCHING) {
7552            Log.v(TAG, "Query " + intent + ": " + results);
7553        }
7554
7555        int specificsPos = 0;
7556        int N;
7557
7558        // todo: note that the algorithm used here is O(N^2).  This
7559        // isn't a problem in our current environment, but if we start running
7560        // into situations where we have more than 5 or 10 matches then this
7561        // should probably be changed to something smarter...
7562
7563        // First we go through and resolve each of the specific items
7564        // that were supplied, taking care of removing any corresponding
7565        // duplicate items in the generic resolve list.
7566        if (specifics != null) {
7567            for (int i=0; i<specifics.length; i++) {
7568                final Intent sintent = specifics[i];
7569                if (sintent == null) {
7570                    continue;
7571                }
7572
7573                if (DEBUG_INTENT_MATCHING) {
7574                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7575                }
7576
7577                String action = sintent.getAction();
7578                if (resultsAction != null && resultsAction.equals(action)) {
7579                    // If this action was explicitly requested, then don't
7580                    // remove things that have it.
7581                    action = null;
7582                }
7583
7584                ResolveInfo ri = null;
7585                ActivityInfo ai = null;
7586
7587                ComponentName comp = sintent.getComponent();
7588                if (comp == null) {
7589                    ri = resolveIntent(
7590                        sintent,
7591                        specificTypes != null ? specificTypes[i] : null,
7592                            flags, userId);
7593                    if (ri == null) {
7594                        continue;
7595                    }
7596                    if (ri == mResolveInfo) {
7597                        // ACK!  Must do something better with this.
7598                    }
7599                    ai = ri.activityInfo;
7600                    comp = new ComponentName(ai.applicationInfo.packageName,
7601                            ai.name);
7602                } else {
7603                    ai = getActivityInfo(comp, flags, userId);
7604                    if (ai == null) {
7605                        continue;
7606                    }
7607                }
7608
7609                // Look for any generic query activities that are duplicates
7610                // of this specific one, and remove them from the results.
7611                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7612                N = results.size();
7613                int j;
7614                for (j=specificsPos; j<N; j++) {
7615                    ResolveInfo sri = results.get(j);
7616                    if ((sri.activityInfo.name.equals(comp.getClassName())
7617                            && sri.activityInfo.applicationInfo.packageName.equals(
7618                                    comp.getPackageName()))
7619                        || (action != null && sri.filter.matchAction(action))) {
7620                        results.remove(j);
7621                        if (DEBUG_INTENT_MATCHING) Log.v(
7622                            TAG, "Removing duplicate item from " + j
7623                            + " due to specific " + specificsPos);
7624                        if (ri == null) {
7625                            ri = sri;
7626                        }
7627                        j--;
7628                        N--;
7629                    }
7630                }
7631
7632                // Add this specific item to its proper place.
7633                if (ri == null) {
7634                    ri = new ResolveInfo();
7635                    ri.activityInfo = ai;
7636                }
7637                results.add(specificsPos, ri);
7638                ri.specificIndex = i;
7639                specificsPos++;
7640            }
7641        }
7642
7643        // Now we go through the remaining generic results and remove any
7644        // duplicate actions that are found here.
7645        N = results.size();
7646        for (int i=specificsPos; i<N-1; i++) {
7647            final ResolveInfo rii = results.get(i);
7648            if (rii.filter == null) {
7649                continue;
7650            }
7651
7652            // Iterate over all of the actions of this result's intent
7653            // filter...  typically this should be just one.
7654            final Iterator<String> it = rii.filter.actionsIterator();
7655            if (it == null) {
7656                continue;
7657            }
7658            while (it.hasNext()) {
7659                final String action = it.next();
7660                if (resultsAction != null && resultsAction.equals(action)) {
7661                    // If this action was explicitly requested, then don't
7662                    // remove things that have it.
7663                    continue;
7664                }
7665                for (int j=i+1; j<N; j++) {
7666                    final ResolveInfo rij = results.get(j);
7667                    if (rij.filter != null && rij.filter.hasAction(action)) {
7668                        results.remove(j);
7669                        if (DEBUG_INTENT_MATCHING) Log.v(
7670                            TAG, "Removing duplicate item from " + j
7671                            + " due to action " + action + " at " + i);
7672                        j--;
7673                        N--;
7674                    }
7675                }
7676            }
7677
7678            // If the caller didn't request filter information, drop it now
7679            // so we don't have to marshall/unmarshall it.
7680            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7681                rii.filter = null;
7682            }
7683        }
7684
7685        // Filter out the caller activity if so requested.
7686        if (caller != null) {
7687            N = results.size();
7688            for (int i=0; i<N; i++) {
7689                ActivityInfo ainfo = results.get(i).activityInfo;
7690                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7691                        && caller.getClassName().equals(ainfo.name)) {
7692                    results.remove(i);
7693                    break;
7694                }
7695            }
7696        }
7697
7698        // If the caller didn't request filter information,
7699        // drop them now so we don't have to
7700        // marshall/unmarshall it.
7701        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7702            N = results.size();
7703            for (int i=0; i<N; i++) {
7704                results.get(i).filter = null;
7705            }
7706        }
7707
7708        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7709        return results;
7710    }
7711
7712    @Override
7713    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7714            String resolvedType, int flags, int userId) {
7715        return new ParceledListSlice<>(
7716                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7717    }
7718
7719    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7720            String resolvedType, int flags, int userId) {
7721        if (!sUserManager.exists(userId)) return Collections.emptyList();
7722        final int callingUid = Binder.getCallingUid();
7723        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7724        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7725                false /*includeInstantApps*/);
7726        ComponentName comp = intent.getComponent();
7727        if (comp == null) {
7728            if (intent.getSelector() != null) {
7729                intent = intent.getSelector();
7730                comp = intent.getComponent();
7731            }
7732        }
7733        if (comp != null) {
7734            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7735            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7736            if (ai != null) {
7737                // When specifying an explicit component, we prevent the activity from being
7738                // used when either 1) the calling package is normal and the activity is within
7739                // an instant application or 2) the calling package is ephemeral and the
7740                // activity is not visible to instant applications.
7741                final boolean matchInstantApp =
7742                        (flags & PackageManager.MATCH_INSTANT) != 0;
7743                final boolean matchVisibleToInstantAppOnly =
7744                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7745                final boolean matchExplicitlyVisibleOnly =
7746                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7747                final boolean isCallerInstantApp =
7748                        instantAppPkgName != null;
7749                final boolean isTargetSameInstantApp =
7750                        comp.getPackageName().equals(instantAppPkgName);
7751                final boolean isTargetInstantApp =
7752                        (ai.applicationInfo.privateFlags
7753                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7754                final boolean isTargetVisibleToInstantApp =
7755                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7756                final boolean isTargetExplicitlyVisibleToInstantApp =
7757                        isTargetVisibleToInstantApp
7758                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7759                final boolean isTargetHiddenFromInstantApp =
7760                        !isTargetVisibleToInstantApp
7761                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7762                final boolean blockResolution =
7763                        !isTargetSameInstantApp
7764                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7765                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7766                                        && isTargetHiddenFromInstantApp));
7767                if (!blockResolution) {
7768                    ResolveInfo ri = new ResolveInfo();
7769                    ri.activityInfo = ai;
7770                    list.add(ri);
7771                }
7772            }
7773            return applyPostResolutionFilter(list, instantAppPkgName);
7774        }
7775
7776        // reader
7777        synchronized (mPackages) {
7778            String pkgName = intent.getPackage();
7779            if (pkgName == null) {
7780                final List<ResolveInfo> result =
7781                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7782                return applyPostResolutionFilter(result, instantAppPkgName);
7783            }
7784            final PackageParser.Package pkg = mPackages.get(pkgName);
7785            if (pkg != null) {
7786                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7787                        intent, resolvedType, flags, pkg.receivers, userId);
7788                return applyPostResolutionFilter(result, instantAppPkgName);
7789            }
7790            return Collections.emptyList();
7791        }
7792    }
7793
7794    @Override
7795    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7796        final int callingUid = Binder.getCallingUid();
7797        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7798    }
7799
7800    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7801            int userId, int callingUid) {
7802        if (!sUserManager.exists(userId)) return null;
7803        flags = updateFlagsForResolve(
7804                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7805        List<ResolveInfo> query = queryIntentServicesInternal(
7806                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7807        if (query != null) {
7808            if (query.size() >= 1) {
7809                // If there is more than one service with the same priority,
7810                // just arbitrarily pick the first one.
7811                return query.get(0);
7812            }
7813        }
7814        return null;
7815    }
7816
7817    @Override
7818    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7819            String resolvedType, int flags, int userId) {
7820        final int callingUid = Binder.getCallingUid();
7821        return new ParceledListSlice<>(queryIntentServicesInternal(
7822                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7823    }
7824
7825    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7826            String resolvedType, int flags, int userId, int callingUid,
7827            boolean includeInstantApps) {
7828        if (!sUserManager.exists(userId)) return Collections.emptyList();
7829        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7830        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7831        ComponentName comp = intent.getComponent();
7832        if (comp == null) {
7833            if (intent.getSelector() != null) {
7834                intent = intent.getSelector();
7835                comp = intent.getComponent();
7836            }
7837        }
7838        if (comp != null) {
7839            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7840            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7841            if (si != null) {
7842                // When specifying an explicit component, we prevent the service from being
7843                // used when either 1) the service is in an instant application and the
7844                // caller is not the same instant application or 2) the calling package is
7845                // ephemeral and the activity is not visible to ephemeral applications.
7846                final boolean matchInstantApp =
7847                        (flags & PackageManager.MATCH_INSTANT) != 0;
7848                final boolean matchVisibleToInstantAppOnly =
7849                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7850                final boolean isCallerInstantApp =
7851                        instantAppPkgName != null;
7852                final boolean isTargetSameInstantApp =
7853                        comp.getPackageName().equals(instantAppPkgName);
7854                final boolean isTargetInstantApp =
7855                        (si.applicationInfo.privateFlags
7856                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7857                final boolean isTargetHiddenFromInstantApp =
7858                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7859                final boolean blockResolution =
7860                        !isTargetSameInstantApp
7861                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7862                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7863                                        && isTargetHiddenFromInstantApp));
7864                if (!blockResolution) {
7865                    final ResolveInfo ri = new ResolveInfo();
7866                    ri.serviceInfo = si;
7867                    list.add(ri);
7868                }
7869            }
7870            return list;
7871        }
7872
7873        // reader
7874        synchronized (mPackages) {
7875            String pkgName = intent.getPackage();
7876            if (pkgName == null) {
7877                return applyPostServiceResolutionFilter(
7878                        mServices.queryIntent(intent, resolvedType, flags, userId),
7879                        instantAppPkgName);
7880            }
7881            final PackageParser.Package pkg = mPackages.get(pkgName);
7882            if (pkg != null) {
7883                return applyPostServiceResolutionFilter(
7884                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7885                                userId),
7886                        instantAppPkgName);
7887            }
7888            return Collections.emptyList();
7889        }
7890    }
7891
7892    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7893            String instantAppPkgName) {
7894        // TODO: When adding on-demand split support for non-instant apps, remove this check
7895        // and always apply post filtering
7896        if (instantAppPkgName == null) {
7897            return resolveInfos;
7898        }
7899        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7900            final ResolveInfo info = resolveInfos.get(i);
7901            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7902            // allow services that are defined in the provided package
7903            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7904                if (info.serviceInfo.splitName != null
7905                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7906                                info.serviceInfo.splitName)) {
7907                    // requested service is defined in a split that hasn't been installed yet.
7908                    // add the installer to the resolve list
7909                    if (DEBUG_EPHEMERAL) {
7910                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7911                    }
7912                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7913                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7914                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7915                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7916                    // make sure this resolver is the default
7917                    installerInfo.isDefault = true;
7918                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7919                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7920                    // add a non-generic filter
7921                    installerInfo.filter = new IntentFilter();
7922                    // load resources from the correct package
7923                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7924                    resolveInfos.set(i, installerInfo);
7925                }
7926                continue;
7927            }
7928            // allow services that have been explicitly exposed to ephemeral apps
7929            if (!isEphemeralApp
7930                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7931                continue;
7932            }
7933            resolveInfos.remove(i);
7934        }
7935        return resolveInfos;
7936    }
7937
7938    @Override
7939    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7940            String resolvedType, int flags, int userId) {
7941        return new ParceledListSlice<>(
7942                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7943    }
7944
7945    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7946            Intent intent, String resolvedType, int flags, int userId) {
7947        if (!sUserManager.exists(userId)) return Collections.emptyList();
7948        final int callingUid = Binder.getCallingUid();
7949        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7950        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7951                false /*includeInstantApps*/);
7952        ComponentName comp = intent.getComponent();
7953        if (comp == null) {
7954            if (intent.getSelector() != null) {
7955                intent = intent.getSelector();
7956                comp = intent.getComponent();
7957            }
7958        }
7959        if (comp != null) {
7960            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7961            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7962            if (pi != null) {
7963                // When specifying an explicit component, we prevent the provider from being
7964                // used when either 1) the provider is in an instant application and the
7965                // caller is not the same instant application or 2) the calling package is an
7966                // instant application and the provider is not visible to instant applications.
7967                final boolean matchInstantApp =
7968                        (flags & PackageManager.MATCH_INSTANT) != 0;
7969                final boolean matchVisibleToInstantAppOnly =
7970                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7971                final boolean isCallerInstantApp =
7972                        instantAppPkgName != null;
7973                final boolean isTargetSameInstantApp =
7974                        comp.getPackageName().equals(instantAppPkgName);
7975                final boolean isTargetInstantApp =
7976                        (pi.applicationInfo.privateFlags
7977                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7978                final boolean isTargetHiddenFromInstantApp =
7979                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7980                final boolean blockResolution =
7981                        !isTargetSameInstantApp
7982                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7983                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7984                                        && isTargetHiddenFromInstantApp));
7985                if (!blockResolution) {
7986                    final ResolveInfo ri = new ResolveInfo();
7987                    ri.providerInfo = pi;
7988                    list.add(ri);
7989                }
7990            }
7991            return list;
7992        }
7993
7994        // reader
7995        synchronized (mPackages) {
7996            String pkgName = intent.getPackage();
7997            if (pkgName == null) {
7998                return applyPostContentProviderResolutionFilter(
7999                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8000                        instantAppPkgName);
8001            }
8002            final PackageParser.Package pkg = mPackages.get(pkgName);
8003            if (pkg != null) {
8004                return applyPostContentProviderResolutionFilter(
8005                        mProviders.queryIntentForPackage(
8006                        intent, resolvedType, flags, pkg.providers, userId),
8007                        instantAppPkgName);
8008            }
8009            return Collections.emptyList();
8010        }
8011    }
8012
8013    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8014            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8015        // TODO: When adding on-demand split support for non-instant applications, remove
8016        // this check and always apply post filtering
8017        if (instantAppPkgName == null) {
8018            return resolveInfos;
8019        }
8020        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8021            final ResolveInfo info = resolveInfos.get(i);
8022            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8023            // allow providers that are defined in the provided package
8024            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8025                if (info.providerInfo.splitName != null
8026                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8027                                info.providerInfo.splitName)) {
8028                    // requested provider is defined in a split that hasn't been installed yet.
8029                    // add the installer to the resolve list
8030                    if (DEBUG_EPHEMERAL) {
8031                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8032                    }
8033                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8034                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8035                            info.providerInfo.packageName, info.providerInfo.splitName,
8036                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8037                    // make sure this resolver is the default
8038                    installerInfo.isDefault = true;
8039                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8040                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8041                    // add a non-generic filter
8042                    installerInfo.filter = new IntentFilter();
8043                    // load resources from the correct package
8044                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8045                    resolveInfos.set(i, installerInfo);
8046                }
8047                continue;
8048            }
8049            // allow providers that have been explicitly exposed to instant applications
8050            if (!isEphemeralApp
8051                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8052                continue;
8053            }
8054            resolveInfos.remove(i);
8055        }
8056        return resolveInfos;
8057    }
8058
8059    @Override
8060    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8061        final int callingUid = Binder.getCallingUid();
8062        if (getInstantAppPackageName(callingUid) != null) {
8063            return ParceledListSlice.emptyList();
8064        }
8065        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8066        flags = updateFlagsForPackage(flags, userId, null);
8067        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8068        enforceCrossUserPermission(callingUid, userId,
8069                true /* requireFullPermission */, false /* checkShell */,
8070                "get installed packages");
8071
8072        // writer
8073        synchronized (mPackages) {
8074            ArrayList<PackageInfo> list;
8075            if (listUninstalled) {
8076                list = new ArrayList<>(mSettings.mPackages.size());
8077                for (PackageSetting ps : mSettings.mPackages.values()) {
8078                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8079                        continue;
8080                    }
8081                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8082                        return null;
8083                    }
8084                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8085                    if (pi != null) {
8086                        list.add(pi);
8087                    }
8088                }
8089            } else {
8090                list = new ArrayList<>(mPackages.size());
8091                for (PackageParser.Package p : mPackages.values()) {
8092                    final PackageSetting ps = (PackageSetting) p.mExtras;
8093                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8094                        continue;
8095                    }
8096                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8097                        return null;
8098                    }
8099                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8100                            p.mExtras, flags, userId);
8101                    if (pi != null) {
8102                        list.add(pi);
8103                    }
8104                }
8105            }
8106
8107            return new ParceledListSlice<>(list);
8108        }
8109    }
8110
8111    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8112            String[] permissions, boolean[] tmp, int flags, int userId) {
8113        int numMatch = 0;
8114        final PermissionsState permissionsState = ps.getPermissionsState();
8115        for (int i=0; i<permissions.length; i++) {
8116            final String permission = permissions[i];
8117            if (permissionsState.hasPermission(permission, userId)) {
8118                tmp[i] = true;
8119                numMatch++;
8120            } else {
8121                tmp[i] = false;
8122            }
8123        }
8124        if (numMatch == 0) {
8125            return;
8126        }
8127        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8128
8129        // The above might return null in cases of uninstalled apps or install-state
8130        // skew across users/profiles.
8131        if (pi != null) {
8132            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8133                if (numMatch == permissions.length) {
8134                    pi.requestedPermissions = permissions;
8135                } else {
8136                    pi.requestedPermissions = new String[numMatch];
8137                    numMatch = 0;
8138                    for (int i=0; i<permissions.length; i++) {
8139                        if (tmp[i]) {
8140                            pi.requestedPermissions[numMatch] = permissions[i];
8141                            numMatch++;
8142                        }
8143                    }
8144                }
8145            }
8146            list.add(pi);
8147        }
8148    }
8149
8150    @Override
8151    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8152            String[] permissions, int flags, int userId) {
8153        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8154        flags = updateFlagsForPackage(flags, userId, permissions);
8155        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8156                true /* requireFullPermission */, false /* checkShell */,
8157                "get packages holding permissions");
8158        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8159
8160        // writer
8161        synchronized (mPackages) {
8162            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8163            boolean[] tmpBools = new boolean[permissions.length];
8164            if (listUninstalled) {
8165                for (PackageSetting ps : mSettings.mPackages.values()) {
8166                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8167                            userId);
8168                }
8169            } else {
8170                for (PackageParser.Package pkg : mPackages.values()) {
8171                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8172                    if (ps != null) {
8173                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8174                                userId);
8175                    }
8176                }
8177            }
8178
8179            return new ParceledListSlice<PackageInfo>(list);
8180        }
8181    }
8182
8183    @Override
8184    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8185        final int callingUid = Binder.getCallingUid();
8186        if (getInstantAppPackageName(callingUid) != null) {
8187            return ParceledListSlice.emptyList();
8188        }
8189        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8190        flags = updateFlagsForApplication(flags, userId, null);
8191        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8192
8193        // writer
8194        synchronized (mPackages) {
8195            ArrayList<ApplicationInfo> list;
8196            if (listUninstalled) {
8197                list = new ArrayList<>(mSettings.mPackages.size());
8198                for (PackageSetting ps : mSettings.mPackages.values()) {
8199                    ApplicationInfo ai;
8200                    int effectiveFlags = flags;
8201                    if (ps.isSystem()) {
8202                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8203                    }
8204                    if (ps.pkg != null) {
8205                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8206                            continue;
8207                        }
8208                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8209                            return null;
8210                        }
8211                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8212                                ps.readUserState(userId), userId);
8213                        if (ai != null) {
8214                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8215                        }
8216                    } else {
8217                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8218                        // and already converts to externally visible package name
8219                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8220                                callingUid, effectiveFlags, userId);
8221                    }
8222                    if (ai != null) {
8223                        list.add(ai);
8224                    }
8225                }
8226            } else {
8227                list = new ArrayList<>(mPackages.size());
8228                for (PackageParser.Package p : mPackages.values()) {
8229                    if (p.mExtras != null) {
8230                        PackageSetting ps = (PackageSetting) p.mExtras;
8231                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8232                            continue;
8233                        }
8234                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8235                            return null;
8236                        }
8237                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8238                                ps.readUserState(userId), userId);
8239                        if (ai != null) {
8240                            ai.packageName = resolveExternalPackageNameLPr(p);
8241                            list.add(ai);
8242                        }
8243                    }
8244                }
8245            }
8246
8247            return new ParceledListSlice<>(list);
8248        }
8249    }
8250
8251    @Override
8252    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8253        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8254            return null;
8255        }
8256        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8257                "getEphemeralApplications");
8258        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8259                true /* requireFullPermission */, false /* checkShell */,
8260                "getEphemeralApplications");
8261        synchronized (mPackages) {
8262            List<InstantAppInfo> instantApps = mInstantAppRegistry
8263                    .getInstantAppsLPr(userId);
8264            if (instantApps != null) {
8265                return new ParceledListSlice<>(instantApps);
8266            }
8267        }
8268        return null;
8269    }
8270
8271    @Override
8272    public boolean isInstantApp(String packageName, int userId) {
8273        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8274                true /* requireFullPermission */, false /* checkShell */,
8275                "isInstantApp");
8276        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8277            return false;
8278        }
8279        int callingUid = Binder.getCallingUid();
8280        if (Process.isIsolated(callingUid)) {
8281            callingUid = mIsolatedOwners.get(callingUid);
8282        }
8283
8284        synchronized (mPackages) {
8285            final PackageSetting ps = mSettings.mPackages.get(packageName);
8286            PackageParser.Package pkg = mPackages.get(packageName);
8287            final boolean returnAllowed =
8288                    ps != null
8289                    && (isCallerSameApp(packageName, callingUid)
8290                            || canViewInstantApps(callingUid, userId)
8291                            || mInstantAppRegistry.isInstantAccessGranted(
8292                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8293            if (returnAllowed) {
8294                return ps.getInstantApp(userId);
8295            }
8296        }
8297        return false;
8298    }
8299
8300    @Override
8301    public byte[] getInstantAppCookie(String packageName, int userId) {
8302        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8303            return null;
8304        }
8305
8306        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8307                true /* requireFullPermission */, false /* checkShell */,
8308                "getInstantAppCookie");
8309        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8310            return null;
8311        }
8312        synchronized (mPackages) {
8313            return mInstantAppRegistry.getInstantAppCookieLPw(
8314                    packageName, userId);
8315        }
8316    }
8317
8318    @Override
8319    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8320        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8321            return true;
8322        }
8323
8324        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8325                true /* requireFullPermission */, true /* checkShell */,
8326                "setInstantAppCookie");
8327        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8328            return false;
8329        }
8330        synchronized (mPackages) {
8331            return mInstantAppRegistry.setInstantAppCookieLPw(
8332                    packageName, cookie, userId);
8333        }
8334    }
8335
8336    @Override
8337    public Bitmap getInstantAppIcon(String packageName, int userId) {
8338        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8339            return null;
8340        }
8341
8342        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8343                "getInstantAppIcon");
8344
8345        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8346                true /* requireFullPermission */, false /* checkShell */,
8347                "getInstantAppIcon");
8348
8349        synchronized (mPackages) {
8350            return mInstantAppRegistry.getInstantAppIconLPw(
8351                    packageName, userId);
8352        }
8353    }
8354
8355    private boolean isCallerSameApp(String packageName, int uid) {
8356        PackageParser.Package pkg = mPackages.get(packageName);
8357        return pkg != null
8358                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8359    }
8360
8361    @Override
8362    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8363        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8364            return ParceledListSlice.emptyList();
8365        }
8366        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8367    }
8368
8369    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8370        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8371
8372        // reader
8373        synchronized (mPackages) {
8374            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8375            final int userId = UserHandle.getCallingUserId();
8376            while (i.hasNext()) {
8377                final PackageParser.Package p = i.next();
8378                if (p.applicationInfo == null) continue;
8379
8380                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8381                        && !p.applicationInfo.isDirectBootAware();
8382                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8383                        && p.applicationInfo.isDirectBootAware();
8384
8385                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8386                        && (!mSafeMode || isSystemApp(p))
8387                        && (matchesUnaware || matchesAware)) {
8388                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8389                    if (ps != null) {
8390                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8391                                ps.readUserState(userId), userId);
8392                        if (ai != null) {
8393                            finalList.add(ai);
8394                        }
8395                    }
8396                }
8397            }
8398        }
8399
8400        return finalList;
8401    }
8402
8403    @Override
8404    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8405        if (!sUserManager.exists(userId)) return null;
8406        flags = updateFlagsForComponent(flags, userId, name);
8407        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8408        // reader
8409        synchronized (mPackages) {
8410            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8411            PackageSetting ps = provider != null
8412                    ? mSettings.mPackages.get(provider.owner.packageName)
8413                    : null;
8414            if (ps != null) {
8415                final boolean isInstantApp = ps.getInstantApp(userId);
8416                // normal application; filter out instant application provider
8417                if (instantAppPkgName == null && isInstantApp) {
8418                    return null;
8419                }
8420                // instant application; filter out other instant applications
8421                if (instantAppPkgName != null
8422                        && isInstantApp
8423                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8424                    return null;
8425                }
8426                // instant application; filter out non-exposed provider
8427                if (instantAppPkgName != null
8428                        && !isInstantApp
8429                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8430                    return null;
8431                }
8432                // provider not enabled
8433                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8434                    return null;
8435                }
8436                return PackageParser.generateProviderInfo(
8437                        provider, flags, ps.readUserState(userId), userId);
8438            }
8439            return null;
8440        }
8441    }
8442
8443    /**
8444     * @deprecated
8445     */
8446    @Deprecated
8447    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8448        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8449            return;
8450        }
8451        // reader
8452        synchronized (mPackages) {
8453            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8454                    .entrySet().iterator();
8455            final int userId = UserHandle.getCallingUserId();
8456            while (i.hasNext()) {
8457                Map.Entry<String, PackageParser.Provider> entry = i.next();
8458                PackageParser.Provider p = entry.getValue();
8459                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8460
8461                if (ps != null && p.syncable
8462                        && (!mSafeMode || (p.info.applicationInfo.flags
8463                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8464                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8465                            ps.readUserState(userId), userId);
8466                    if (info != null) {
8467                        outNames.add(entry.getKey());
8468                        outInfo.add(info);
8469                    }
8470                }
8471            }
8472        }
8473    }
8474
8475    @Override
8476    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8477            int uid, int flags, String metaDataKey) {
8478        final int callingUid = Binder.getCallingUid();
8479        final int userId = processName != null ? UserHandle.getUserId(uid)
8480                : UserHandle.getCallingUserId();
8481        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8482        flags = updateFlagsForComponent(flags, userId, processName);
8483        ArrayList<ProviderInfo> finalList = null;
8484        // reader
8485        synchronized (mPackages) {
8486            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8487            while (i.hasNext()) {
8488                final PackageParser.Provider p = i.next();
8489                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8490                if (ps != null && p.info.authority != null
8491                        && (processName == null
8492                                || (p.info.processName.equals(processName)
8493                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8494                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8495
8496                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8497                    // parameter.
8498                    if (metaDataKey != null
8499                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8500                        continue;
8501                    }
8502                    final ComponentName component =
8503                            new ComponentName(p.info.packageName, p.info.name);
8504                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8505                        continue;
8506                    }
8507                    if (finalList == null) {
8508                        finalList = new ArrayList<ProviderInfo>(3);
8509                    }
8510                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8511                            ps.readUserState(userId), userId);
8512                    if (info != null) {
8513                        finalList.add(info);
8514                    }
8515                }
8516            }
8517        }
8518
8519        if (finalList != null) {
8520            Collections.sort(finalList, mProviderInitOrderSorter);
8521            return new ParceledListSlice<ProviderInfo>(finalList);
8522        }
8523
8524        return ParceledListSlice.emptyList();
8525    }
8526
8527    @Override
8528    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8529        // reader
8530        synchronized (mPackages) {
8531            final int callingUid = Binder.getCallingUid();
8532            final int callingUserId = UserHandle.getUserId(callingUid);
8533            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8534            if (ps == null) return null;
8535            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8536                return null;
8537            }
8538            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8539            return PackageParser.generateInstrumentationInfo(i, flags);
8540        }
8541    }
8542
8543    @Override
8544    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8545            String targetPackage, int flags) {
8546        final int callingUid = Binder.getCallingUid();
8547        final int callingUserId = UserHandle.getUserId(callingUid);
8548        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8549        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8550            return ParceledListSlice.emptyList();
8551        }
8552        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8553    }
8554
8555    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8556            int flags) {
8557        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8558
8559        // reader
8560        synchronized (mPackages) {
8561            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8562            while (i.hasNext()) {
8563                final PackageParser.Instrumentation p = i.next();
8564                if (targetPackage == null
8565                        || targetPackage.equals(p.info.targetPackage)) {
8566                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8567                            flags);
8568                    if (ii != null) {
8569                        finalList.add(ii);
8570                    }
8571                }
8572            }
8573        }
8574
8575        return finalList;
8576    }
8577
8578    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8579        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8580        try {
8581            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8582        } finally {
8583            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8584        }
8585    }
8586
8587    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8588        final File[] files = dir.listFiles();
8589        if (ArrayUtils.isEmpty(files)) {
8590            Log.d(TAG, "No files in app dir " + dir);
8591            return;
8592        }
8593
8594        if (DEBUG_PACKAGE_SCANNING) {
8595            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8596                    + " flags=0x" + Integer.toHexString(parseFlags));
8597        }
8598        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8599                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8600                mParallelPackageParserCallback);
8601
8602        // Submit files for parsing in parallel
8603        int fileCount = 0;
8604        for (File file : files) {
8605            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8606                    && !PackageInstallerService.isStageName(file.getName());
8607            if (!isPackage) {
8608                // Ignore entries which are not packages
8609                continue;
8610            }
8611            parallelPackageParser.submit(file, parseFlags);
8612            fileCount++;
8613        }
8614
8615        // Process results one by one
8616        for (; fileCount > 0; fileCount--) {
8617            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8618            Throwable throwable = parseResult.throwable;
8619            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8620
8621            if (throwable == null) {
8622                // Static shared libraries have synthetic package names
8623                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8624                    renameStaticSharedLibraryPackage(parseResult.pkg);
8625                }
8626                try {
8627                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8628                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8629                                currentTime, null);
8630                    }
8631                } catch (PackageManagerException e) {
8632                    errorCode = e.error;
8633                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8634                }
8635            } else if (throwable instanceof PackageParser.PackageParserException) {
8636                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8637                        throwable;
8638                errorCode = e.error;
8639                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8640            } else {
8641                throw new IllegalStateException("Unexpected exception occurred while parsing "
8642                        + parseResult.scanFile, throwable);
8643            }
8644
8645            // Delete invalid userdata apps
8646            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8647                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8648                logCriticalInfo(Log.WARN,
8649                        "Deleting invalid package at " + parseResult.scanFile);
8650                removeCodePathLI(parseResult.scanFile);
8651            }
8652        }
8653        parallelPackageParser.close();
8654    }
8655
8656    private static File getSettingsProblemFile() {
8657        File dataDir = Environment.getDataDirectory();
8658        File systemDir = new File(dataDir, "system");
8659        File fname = new File(systemDir, "uiderrors.txt");
8660        return fname;
8661    }
8662
8663    static void reportSettingsProblem(int priority, String msg) {
8664        logCriticalInfo(priority, msg);
8665    }
8666
8667    public static void logCriticalInfo(int priority, String msg) {
8668        Slog.println(priority, TAG, msg);
8669        EventLogTags.writePmCriticalInfo(msg);
8670        try {
8671            File fname = getSettingsProblemFile();
8672            FileOutputStream out = new FileOutputStream(fname, true);
8673            PrintWriter pw = new FastPrintWriter(out);
8674            SimpleDateFormat formatter = new SimpleDateFormat();
8675            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8676            pw.println(dateString + ": " + msg);
8677            pw.close();
8678            FileUtils.setPermissions(
8679                    fname.toString(),
8680                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8681                    -1, -1);
8682        } catch (java.io.IOException e) {
8683        }
8684    }
8685
8686    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8687        if (srcFile.isDirectory()) {
8688            final File baseFile = new File(pkg.baseCodePath);
8689            long maxModifiedTime = baseFile.lastModified();
8690            if (pkg.splitCodePaths != null) {
8691                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8692                    final File splitFile = new File(pkg.splitCodePaths[i]);
8693                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8694                }
8695            }
8696            return maxModifiedTime;
8697        }
8698        return srcFile.lastModified();
8699    }
8700
8701    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8702            final int policyFlags) throws PackageManagerException {
8703        // When upgrading from pre-N MR1, verify the package time stamp using the package
8704        // directory and not the APK file.
8705        final long lastModifiedTime = mIsPreNMR1Upgrade
8706                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8707        if (ps != null
8708                && ps.codePath.equals(srcFile)
8709                && ps.timeStamp == lastModifiedTime
8710                && !isCompatSignatureUpdateNeeded(pkg)
8711                && !isRecoverSignatureUpdateNeeded(pkg)) {
8712            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8713            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8714            ArraySet<PublicKey> signingKs;
8715            synchronized (mPackages) {
8716                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8717            }
8718            if (ps.signatures.mSignatures != null
8719                    && ps.signatures.mSignatures.length != 0
8720                    && signingKs != null) {
8721                // Optimization: reuse the existing cached certificates
8722                // if the package appears to be unchanged.
8723                pkg.mSignatures = ps.signatures.mSignatures;
8724                pkg.mSigningKeys = signingKs;
8725                return;
8726            }
8727
8728            Slog.w(TAG, "PackageSetting for " + ps.name
8729                    + " is missing signatures.  Collecting certs again to recover them.");
8730        } else {
8731            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8732        }
8733
8734        try {
8735            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8736            PackageParser.collectCertificates(pkg, policyFlags);
8737        } catch (PackageParserException e) {
8738            throw PackageManagerException.from(e);
8739        } finally {
8740            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8741        }
8742    }
8743
8744    /**
8745     *  Traces a package scan.
8746     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8747     */
8748    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8749            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8750        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8751        try {
8752            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8753        } finally {
8754            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8755        }
8756    }
8757
8758    /**
8759     *  Scans a package and returns the newly parsed package.
8760     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8761     */
8762    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8763            long currentTime, UserHandle user) throws PackageManagerException {
8764        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8765        PackageParser pp = new PackageParser();
8766        pp.setSeparateProcesses(mSeparateProcesses);
8767        pp.setOnlyCoreApps(mOnlyCore);
8768        pp.setDisplayMetrics(mMetrics);
8769        pp.setCallback(mPackageParserCallback);
8770
8771        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8772            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8773        }
8774
8775        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8776        final PackageParser.Package pkg;
8777        try {
8778            pkg = pp.parsePackage(scanFile, parseFlags);
8779        } catch (PackageParserException e) {
8780            throw PackageManagerException.from(e);
8781        } finally {
8782            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8783        }
8784
8785        // Static shared libraries have synthetic package names
8786        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8787            renameStaticSharedLibraryPackage(pkg);
8788        }
8789
8790        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8791    }
8792
8793    /**
8794     *  Scans a package and returns the newly parsed package.
8795     *  @throws PackageManagerException on a parse error.
8796     */
8797    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8798            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8799            throws PackageManagerException {
8800        // If the package has children and this is the first dive in the function
8801        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8802        // packages (parent and children) would be successfully scanned before the
8803        // actual scan since scanning mutates internal state and we want to atomically
8804        // install the package and its children.
8805        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8806            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8807                scanFlags |= SCAN_CHECK_ONLY;
8808            }
8809        } else {
8810            scanFlags &= ~SCAN_CHECK_ONLY;
8811        }
8812
8813        // Scan the parent
8814        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8815                scanFlags, currentTime, user);
8816
8817        // Scan the children
8818        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8819        for (int i = 0; i < childCount; i++) {
8820            PackageParser.Package childPackage = pkg.childPackages.get(i);
8821            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8822                    currentTime, user);
8823        }
8824
8825
8826        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8827            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8828        }
8829
8830        return scannedPkg;
8831    }
8832
8833    /**
8834     *  Scans a package and returns the newly parsed package.
8835     *  @throws PackageManagerException on a parse error.
8836     */
8837    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8838            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8839            throws PackageManagerException {
8840        PackageSetting ps = null;
8841        PackageSetting updatedPkg;
8842        // reader
8843        synchronized (mPackages) {
8844            // Look to see if we already know about this package.
8845            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8846            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8847                // This package has been renamed to its original name.  Let's
8848                // use that.
8849                ps = mSettings.getPackageLPr(oldName);
8850            }
8851            // If there was no original package, see one for the real package name.
8852            if (ps == null) {
8853                ps = mSettings.getPackageLPr(pkg.packageName);
8854            }
8855            // Check to see if this package could be hiding/updating a system
8856            // package.  Must look for it either under the original or real
8857            // package name depending on our state.
8858            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8859            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8860
8861            // If this is a package we don't know about on the system partition, we
8862            // may need to remove disabled child packages on the system partition
8863            // or may need to not add child packages if the parent apk is updated
8864            // on the data partition and no longer defines this child package.
8865            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8866                // If this is a parent package for an updated system app and this system
8867                // app got an OTA update which no longer defines some of the child packages
8868                // we have to prune them from the disabled system packages.
8869                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8870                if (disabledPs != null) {
8871                    final int scannedChildCount = (pkg.childPackages != null)
8872                            ? pkg.childPackages.size() : 0;
8873                    final int disabledChildCount = disabledPs.childPackageNames != null
8874                            ? disabledPs.childPackageNames.size() : 0;
8875                    for (int i = 0; i < disabledChildCount; i++) {
8876                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8877                        boolean disabledPackageAvailable = false;
8878                        for (int j = 0; j < scannedChildCount; j++) {
8879                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8880                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8881                                disabledPackageAvailable = true;
8882                                break;
8883                            }
8884                         }
8885                         if (!disabledPackageAvailable) {
8886                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8887                         }
8888                    }
8889                }
8890            }
8891        }
8892
8893        boolean updatedPkgBetter = false;
8894        // First check if this is a system package that may involve an update
8895        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8896            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8897            // it needs to drop FLAG_PRIVILEGED.
8898            if (locationIsPrivileged(scanFile)) {
8899                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8900            } else {
8901                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8902            }
8903
8904            if (ps != null && !ps.codePath.equals(scanFile)) {
8905                // The path has changed from what was last scanned...  check the
8906                // version of the new path against what we have stored to determine
8907                // what to do.
8908                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8909                if (pkg.mVersionCode <= ps.versionCode) {
8910                    // The system package has been updated and the code path does not match
8911                    // Ignore entry. Skip it.
8912                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8913                            + " ignored: updated version " + ps.versionCode
8914                            + " better than this " + pkg.mVersionCode);
8915                    if (!updatedPkg.codePath.equals(scanFile)) {
8916                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8917                                + ps.name + " changing from " + updatedPkg.codePathString
8918                                + " to " + scanFile);
8919                        updatedPkg.codePath = scanFile;
8920                        updatedPkg.codePathString = scanFile.toString();
8921                        updatedPkg.resourcePath = scanFile;
8922                        updatedPkg.resourcePathString = scanFile.toString();
8923                    }
8924                    updatedPkg.pkg = pkg;
8925                    updatedPkg.versionCode = pkg.mVersionCode;
8926
8927                    // Update the disabled system child packages to point to the package too.
8928                    final int childCount = updatedPkg.childPackageNames != null
8929                            ? updatedPkg.childPackageNames.size() : 0;
8930                    for (int i = 0; i < childCount; i++) {
8931                        String childPackageName = updatedPkg.childPackageNames.get(i);
8932                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8933                                childPackageName);
8934                        if (updatedChildPkg != null) {
8935                            updatedChildPkg.pkg = pkg;
8936                            updatedChildPkg.versionCode = pkg.mVersionCode;
8937                        }
8938                    }
8939
8940                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8941                            + scanFile + " ignored: updated version " + ps.versionCode
8942                            + " better than this " + pkg.mVersionCode);
8943                } else {
8944                    // The current app on the system partition is better than
8945                    // what we have updated to on the data partition; switch
8946                    // back to the system partition version.
8947                    // At this point, its safely assumed that package installation for
8948                    // apps in system partition will go through. If not there won't be a working
8949                    // version of the app
8950                    // writer
8951                    synchronized (mPackages) {
8952                        // Just remove the loaded entries from package lists.
8953                        mPackages.remove(ps.name);
8954                    }
8955
8956                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8957                            + " reverting from " + ps.codePathString
8958                            + ": new version " + pkg.mVersionCode
8959                            + " better than installed " + ps.versionCode);
8960
8961                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8962                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8963                    synchronized (mInstallLock) {
8964                        args.cleanUpResourcesLI();
8965                    }
8966                    synchronized (mPackages) {
8967                        mSettings.enableSystemPackageLPw(ps.name);
8968                    }
8969                    updatedPkgBetter = true;
8970                }
8971            }
8972        }
8973
8974        if (updatedPkg != null) {
8975            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8976            // initially
8977            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8978
8979            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8980            // flag set initially
8981            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8982                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8983            }
8984        }
8985
8986        // Verify certificates against what was last scanned
8987        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8988
8989        /*
8990         * A new system app appeared, but we already had a non-system one of the
8991         * same name installed earlier.
8992         */
8993        boolean shouldHideSystemApp = false;
8994        if (updatedPkg == null && ps != null
8995                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8996            /*
8997             * Check to make sure the signatures match first. If they don't,
8998             * wipe the installed application and its data.
8999             */
9000            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9001                    != PackageManager.SIGNATURE_MATCH) {
9002                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9003                        + " signatures don't match existing userdata copy; removing");
9004                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9005                        "scanPackageInternalLI")) {
9006                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9007                }
9008                ps = null;
9009            } else {
9010                /*
9011                 * If the newly-added system app is an older version than the
9012                 * already installed version, hide it. It will be scanned later
9013                 * and re-added like an update.
9014                 */
9015                if (pkg.mVersionCode <= ps.versionCode) {
9016                    shouldHideSystemApp = true;
9017                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9018                            + " but new version " + pkg.mVersionCode + " better than installed "
9019                            + ps.versionCode + "; hiding system");
9020                } else {
9021                    /*
9022                     * The newly found system app is a newer version that the
9023                     * one previously installed. Simply remove the
9024                     * already-installed application and replace it with our own
9025                     * while keeping the application data.
9026                     */
9027                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9028                            + " reverting from " + ps.codePathString + ": new version "
9029                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9030                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9031                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9032                    synchronized (mInstallLock) {
9033                        args.cleanUpResourcesLI();
9034                    }
9035                }
9036            }
9037        }
9038
9039        // The apk is forward locked (not public) if its code and resources
9040        // are kept in different files. (except for app in either system or
9041        // vendor path).
9042        // TODO grab this value from PackageSettings
9043        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9044            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9045                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9046            }
9047        }
9048
9049        // TODO: extend to support forward-locked splits
9050        String resourcePath = null;
9051        String baseResourcePath = null;
9052        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
9053            if (ps != null && ps.resourcePathString != null) {
9054                resourcePath = ps.resourcePathString;
9055                baseResourcePath = ps.resourcePathString;
9056            } else {
9057                // Should not happen at all. Just log an error.
9058                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9059            }
9060        } else {
9061            resourcePath = pkg.codePath;
9062            baseResourcePath = pkg.baseCodePath;
9063        }
9064
9065        // Set application objects path explicitly.
9066        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9067        pkg.setApplicationInfoCodePath(pkg.codePath);
9068        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9069        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9070        pkg.setApplicationInfoResourcePath(resourcePath);
9071        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9072        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9073
9074        final int userId = ((user == null) ? 0 : user.getIdentifier());
9075        if (ps != null && ps.getInstantApp(userId)) {
9076            scanFlags |= SCAN_AS_INSTANT_APP;
9077        }
9078
9079        // Note that we invoke the following method only if we are about to unpack an application
9080        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9081                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9082
9083        /*
9084         * If the system app should be overridden by a previously installed
9085         * data, hide the system app now and let the /data/app scan pick it up
9086         * again.
9087         */
9088        if (shouldHideSystemApp) {
9089            synchronized (mPackages) {
9090                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9091            }
9092        }
9093
9094        return scannedPkg;
9095    }
9096
9097    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9098        // Derive the new package synthetic package name
9099        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9100                + pkg.staticSharedLibVersion);
9101    }
9102
9103    private static String fixProcessName(String defProcessName,
9104            String processName) {
9105        if (processName == null) {
9106            return defProcessName;
9107        }
9108        return processName;
9109    }
9110
9111    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9112            throws PackageManagerException {
9113        if (pkgSetting.signatures.mSignatures != null) {
9114            // Already existing package. Make sure signatures match
9115            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9116                    == PackageManager.SIGNATURE_MATCH;
9117            if (!match) {
9118                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9119                        == PackageManager.SIGNATURE_MATCH;
9120            }
9121            if (!match) {
9122                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9123                        == PackageManager.SIGNATURE_MATCH;
9124            }
9125            if (!match) {
9126                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9127                        + pkg.packageName + " signatures do not match the "
9128                        + "previously installed version; ignoring!");
9129            }
9130        }
9131
9132        // Check for shared user signatures
9133        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9134            // Already existing package. Make sure signatures match
9135            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9136                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9137            if (!match) {
9138                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9139                        == PackageManager.SIGNATURE_MATCH;
9140            }
9141            if (!match) {
9142                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9143                        == PackageManager.SIGNATURE_MATCH;
9144            }
9145            if (!match) {
9146                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9147                        "Package " + pkg.packageName
9148                        + " has no signatures that match those in shared user "
9149                        + pkgSetting.sharedUser.name + "; ignoring!");
9150            }
9151        }
9152    }
9153
9154    /**
9155     * Enforces that only the system UID or root's UID can call a method exposed
9156     * via Binder.
9157     *
9158     * @param message used as message if SecurityException is thrown
9159     * @throws SecurityException if the caller is not system or root
9160     */
9161    private static final void enforceSystemOrRoot(String message) {
9162        final int uid = Binder.getCallingUid();
9163        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9164            throw new SecurityException(message);
9165        }
9166    }
9167
9168    @Override
9169    public void performFstrimIfNeeded() {
9170        enforceSystemOrRoot("Only the system can request fstrim");
9171
9172        // Before everything else, see whether we need to fstrim.
9173        try {
9174            IStorageManager sm = PackageHelper.getStorageManager();
9175            if (sm != null) {
9176                boolean doTrim = false;
9177                final long interval = android.provider.Settings.Global.getLong(
9178                        mContext.getContentResolver(),
9179                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9180                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9181                if (interval > 0) {
9182                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9183                    if (timeSinceLast > interval) {
9184                        doTrim = true;
9185                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9186                                + "; running immediately");
9187                    }
9188                }
9189                if (doTrim) {
9190                    final boolean dexOptDialogShown;
9191                    synchronized (mPackages) {
9192                        dexOptDialogShown = mDexOptDialogShown;
9193                    }
9194                    if (!isFirstBoot() && dexOptDialogShown) {
9195                        try {
9196                            ActivityManager.getService().showBootMessage(
9197                                    mContext.getResources().getString(
9198                                            R.string.android_upgrading_fstrim), true);
9199                        } catch (RemoteException e) {
9200                        }
9201                    }
9202                    sm.runMaintenance();
9203                }
9204            } else {
9205                Slog.e(TAG, "storageManager service unavailable!");
9206            }
9207        } catch (RemoteException e) {
9208            // Can't happen; StorageManagerService is local
9209        }
9210    }
9211
9212    @Override
9213    public void updatePackagesIfNeeded() {
9214        enforceSystemOrRoot("Only the system can request package update");
9215
9216        // We need to re-extract after an OTA.
9217        boolean causeUpgrade = isUpgrade();
9218
9219        // First boot or factory reset.
9220        // Note: we also handle devices that are upgrading to N right now as if it is their
9221        //       first boot, as they do not have profile data.
9222        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9223
9224        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9225        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9226
9227        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9228            return;
9229        }
9230
9231        List<PackageParser.Package> pkgs;
9232        synchronized (mPackages) {
9233            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9234        }
9235
9236        final long startTime = System.nanoTime();
9237        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9238                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
9239
9240        final int elapsedTimeSeconds =
9241                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9242
9243        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9244        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9245        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9246        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9247        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9248    }
9249
9250    /**
9251     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9252     * containing statistics about the invocation. The array consists of three elements,
9253     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9254     * and {@code numberOfPackagesFailed}.
9255     */
9256    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9257            String compilerFilter) {
9258
9259        int numberOfPackagesVisited = 0;
9260        int numberOfPackagesOptimized = 0;
9261        int numberOfPackagesSkipped = 0;
9262        int numberOfPackagesFailed = 0;
9263        final int numberOfPackagesToDexopt = pkgs.size();
9264
9265        for (PackageParser.Package pkg : pkgs) {
9266            numberOfPackagesVisited++;
9267
9268            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9269                if (DEBUG_DEXOPT) {
9270                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9271                }
9272                numberOfPackagesSkipped++;
9273                continue;
9274            }
9275
9276            if (DEBUG_DEXOPT) {
9277                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9278                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9279            }
9280
9281            if (showDialog) {
9282                try {
9283                    ActivityManager.getService().showBootMessage(
9284                            mContext.getResources().getString(R.string.android_upgrading_apk,
9285                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9286                } catch (RemoteException e) {
9287                }
9288                synchronized (mPackages) {
9289                    mDexOptDialogShown = true;
9290                }
9291            }
9292
9293            // If the OTA updates a system app which was previously preopted to a non-preopted state
9294            // the app might end up being verified at runtime. That's because by default the apps
9295            // are verify-profile but for preopted apps there's no profile.
9296            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9297            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9298            // filter (by default 'quicken').
9299            // Note that at this stage unused apps are already filtered.
9300            if (isSystemApp(pkg) &&
9301                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9302                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9303                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9304            }
9305
9306            // checkProfiles is false to avoid merging profiles during boot which
9307            // might interfere with background compilation (b/28612421).
9308            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9309            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9310            // trade-off worth doing to save boot time work.
9311            int dexOptStatus = performDexOptTraced(pkg.packageName,
9312                    false /* checkProfiles */,
9313                    compilerFilter,
9314                    false /* force */);
9315            switch (dexOptStatus) {
9316                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9317                    numberOfPackagesOptimized++;
9318                    break;
9319                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9320                    numberOfPackagesSkipped++;
9321                    break;
9322                case PackageDexOptimizer.DEX_OPT_FAILED:
9323                    numberOfPackagesFailed++;
9324                    break;
9325                default:
9326                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
9327                    break;
9328            }
9329        }
9330
9331        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9332                numberOfPackagesFailed };
9333    }
9334
9335    @Override
9336    public void notifyPackageUse(String packageName, int reason) {
9337        synchronized (mPackages) {
9338            final int callingUid = Binder.getCallingUid();
9339            final int callingUserId = UserHandle.getUserId(callingUid);
9340            if (getInstantAppPackageName(callingUid) != null) {
9341                if (!isCallerSameApp(packageName, callingUid)) {
9342                    return;
9343                }
9344            } else {
9345                if (isInstantApp(packageName, callingUserId)) {
9346                    return;
9347                }
9348            }
9349            final PackageParser.Package p = mPackages.get(packageName);
9350            if (p == null) {
9351                return;
9352            }
9353            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9354        }
9355    }
9356
9357    @Override
9358    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9359        int userId = UserHandle.getCallingUserId();
9360        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9361        if (ai == null) {
9362            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9363                + loadingPackageName + ", user=" + userId);
9364            return;
9365        }
9366        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9367    }
9368
9369    @Override
9370    public boolean performDexOpt(String packageName,
9371            boolean checkProfiles, int compileReason, boolean force) {
9372        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9373            return false;
9374        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9375            return false;
9376        }
9377        return performDexOptWithStatus(packageName, checkProfiles, compileReason, force) !=
9378                PackageDexOptimizer.DEX_OPT_FAILED;
9379    }
9380
9381    /**
9382     * Perform dexopt on the given package and return one of following result:
9383     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9384     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9385     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9386     */
9387    /* package */ int performDexOptWithStatus(String packageName,
9388            boolean checkProfiles, int compileReason, boolean force) {
9389        return performDexOptTraced(packageName, checkProfiles,
9390                getCompilerFilterForReason(compileReason), force);
9391    }
9392
9393    @Override
9394    public boolean performDexOptMode(String packageName,
9395            boolean checkProfiles, String targetCompilerFilter, boolean force) {
9396        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9397            return false;
9398        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9399            return false;
9400        }
9401        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9402                targetCompilerFilter, force);
9403        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9404    }
9405
9406    private int performDexOptTraced(String packageName,
9407                boolean checkProfiles, String targetCompilerFilter, boolean force) {
9408        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9409        try {
9410            return performDexOptInternal(packageName, checkProfiles,
9411                    targetCompilerFilter, force);
9412        } finally {
9413            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9414        }
9415    }
9416
9417    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9418    // if the package can now be considered up to date for the given filter.
9419    private int performDexOptInternal(String packageName,
9420                boolean checkProfiles, String targetCompilerFilter, boolean force) {
9421        PackageParser.Package p;
9422        synchronized (mPackages) {
9423            p = mPackages.get(packageName);
9424            if (p == null) {
9425                // Package could not be found. Report failure.
9426                return PackageDexOptimizer.DEX_OPT_FAILED;
9427            }
9428            mPackageUsage.maybeWriteAsync(mPackages);
9429            mCompilerStats.maybeWriteAsync();
9430        }
9431        long callingId = Binder.clearCallingIdentity();
9432        try {
9433            synchronized (mInstallLock) {
9434                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9435                        targetCompilerFilter, force);
9436            }
9437        } finally {
9438            Binder.restoreCallingIdentity(callingId);
9439        }
9440    }
9441
9442    public ArraySet<String> getOptimizablePackages() {
9443        ArraySet<String> pkgs = new ArraySet<String>();
9444        synchronized (mPackages) {
9445            for (PackageParser.Package p : mPackages.values()) {
9446                if (PackageDexOptimizer.canOptimizePackage(p)) {
9447                    pkgs.add(p.packageName);
9448                }
9449            }
9450        }
9451        return pkgs;
9452    }
9453
9454    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9455            boolean checkProfiles, String targetCompilerFilter,
9456            boolean force) {
9457        // Select the dex optimizer based on the force parameter.
9458        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9459        //       allocate an object here.
9460        PackageDexOptimizer pdo = force
9461                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9462                : mPackageDexOptimizer;
9463
9464        // Dexopt all dependencies first. Note: we ignore the return value and march on
9465        // on errors.
9466        // Note that we are going to call performDexOpt on those libraries as many times as
9467        // they are referenced in packages. When we do a batch of performDexOpt (for example
9468        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9469        // and the first package that uses the library will dexopt it. The
9470        // others will see that the compiled code for the library is up to date.
9471        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9472        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9473        if (!deps.isEmpty()) {
9474            for (PackageParser.Package depPackage : deps) {
9475                // TODO: Analyze and investigate if we (should) profile libraries.
9476                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9477                        false /* checkProfiles */,
9478                        targetCompilerFilter,
9479                        getOrCreateCompilerPackageStats(depPackage),
9480                        true /* isUsedByOtherApps */);
9481            }
9482        }
9483        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9484                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9485                mDexManager.isUsedByOtherApps(p.packageName));
9486    }
9487
9488    // Performs dexopt on the used secondary dex files belonging to the given package.
9489    // Returns true if all dex files were process successfully (which could mean either dexopt or
9490    // skip). Returns false if any of the files caused errors.
9491    @Override
9492    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9493            boolean force) {
9494        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9495            return false;
9496        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9497            return false;
9498        }
9499        mDexManager.reconcileSecondaryDexFiles(packageName);
9500        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
9501    }
9502
9503    public boolean performDexOptSecondary(String packageName, int compileReason,
9504            boolean force) {
9505        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9506    }
9507
9508    /**
9509     * Reconcile the information we have about the secondary dex files belonging to
9510     * {@code packagName} and the actual dex files. For all dex files that were
9511     * deleted, update the internal records and delete the generated oat files.
9512     */
9513    @Override
9514    public void reconcileSecondaryDexFiles(String packageName) {
9515        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9516            return;
9517        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9518            return;
9519        }
9520        mDexManager.reconcileSecondaryDexFiles(packageName);
9521    }
9522
9523    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9524    // a reference there.
9525    /*package*/ DexManager getDexManager() {
9526        return mDexManager;
9527    }
9528
9529    /**
9530     * Execute the background dexopt job immediately.
9531     */
9532    @Override
9533    public boolean runBackgroundDexoptJob() {
9534        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9535            return false;
9536        }
9537        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9538    }
9539
9540    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9541        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9542                || p.usesStaticLibraries != null) {
9543            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9544            Set<String> collectedNames = new HashSet<>();
9545            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9546
9547            retValue.remove(p);
9548
9549            return retValue;
9550        } else {
9551            return Collections.emptyList();
9552        }
9553    }
9554
9555    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9556            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9557        if (!collectedNames.contains(p.packageName)) {
9558            collectedNames.add(p.packageName);
9559            collected.add(p);
9560
9561            if (p.usesLibraries != null) {
9562                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9563                        null, collected, collectedNames);
9564            }
9565            if (p.usesOptionalLibraries != null) {
9566                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9567                        null, collected, collectedNames);
9568            }
9569            if (p.usesStaticLibraries != null) {
9570                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9571                        p.usesStaticLibrariesVersions, collected, collectedNames);
9572            }
9573        }
9574    }
9575
9576    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9577            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9578        final int libNameCount = libs.size();
9579        for (int i = 0; i < libNameCount; i++) {
9580            String libName = libs.get(i);
9581            int version = (versions != null && versions.length == libNameCount)
9582                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9583            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9584            if (libPkg != null) {
9585                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9586            }
9587        }
9588    }
9589
9590    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9591        synchronized (mPackages) {
9592            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9593            if (libEntry != null) {
9594                return mPackages.get(libEntry.apk);
9595            }
9596            return null;
9597        }
9598    }
9599
9600    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9601        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9602        if (versionedLib == null) {
9603            return null;
9604        }
9605        return versionedLib.get(version);
9606    }
9607
9608    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9609        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9610                pkg.staticSharedLibName);
9611        if (versionedLib == null) {
9612            return null;
9613        }
9614        int previousLibVersion = -1;
9615        final int versionCount = versionedLib.size();
9616        for (int i = 0; i < versionCount; i++) {
9617            final int libVersion = versionedLib.keyAt(i);
9618            if (libVersion < pkg.staticSharedLibVersion) {
9619                previousLibVersion = Math.max(previousLibVersion, libVersion);
9620            }
9621        }
9622        if (previousLibVersion >= 0) {
9623            return versionedLib.get(previousLibVersion);
9624        }
9625        return null;
9626    }
9627
9628    public void shutdown() {
9629        mPackageUsage.writeNow(mPackages);
9630        mCompilerStats.writeNow();
9631    }
9632
9633    @Override
9634    public void dumpProfiles(String packageName) {
9635        PackageParser.Package pkg;
9636        synchronized (mPackages) {
9637            pkg = mPackages.get(packageName);
9638            if (pkg == null) {
9639                throw new IllegalArgumentException("Unknown package: " + packageName);
9640            }
9641        }
9642        /* Only the shell, root, or the app user should be able to dump profiles. */
9643        int callingUid = Binder.getCallingUid();
9644        if (callingUid != Process.SHELL_UID &&
9645            callingUid != Process.ROOT_UID &&
9646            callingUid != pkg.applicationInfo.uid) {
9647            throw new SecurityException("dumpProfiles");
9648        }
9649
9650        synchronized (mInstallLock) {
9651            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9652            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9653            try {
9654                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9655                String codePaths = TextUtils.join(";", allCodePaths);
9656                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9657            } catch (InstallerException e) {
9658                Slog.w(TAG, "Failed to dump profiles", e);
9659            }
9660            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9661        }
9662    }
9663
9664    @Override
9665    public void forceDexOpt(String packageName) {
9666        enforceSystemOrRoot("forceDexOpt");
9667
9668        PackageParser.Package pkg;
9669        synchronized (mPackages) {
9670            pkg = mPackages.get(packageName);
9671            if (pkg == null) {
9672                throw new IllegalArgumentException("Unknown package: " + packageName);
9673            }
9674        }
9675
9676        synchronized (mInstallLock) {
9677            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9678
9679            // Whoever is calling forceDexOpt wants a compiled package.
9680            // Don't use profiles since that may cause compilation to be skipped.
9681            final int res = performDexOptInternalWithDependenciesLI(pkg,
9682                    false /* checkProfiles */, getDefaultCompilerFilter(),
9683                    true /* force */);
9684
9685            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9686            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9687                throw new IllegalStateException("Failed to dexopt: " + res);
9688            }
9689        }
9690    }
9691
9692    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9693        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9694            Slog.w(TAG, "Unable to update from " + oldPkg.name
9695                    + " to " + newPkg.packageName
9696                    + ": old package not in system partition");
9697            return false;
9698        } else if (mPackages.get(oldPkg.name) != null) {
9699            Slog.w(TAG, "Unable to update from " + oldPkg.name
9700                    + " to " + newPkg.packageName
9701                    + ": old package still exists");
9702            return false;
9703        }
9704        return true;
9705    }
9706
9707    void removeCodePathLI(File codePath) {
9708        if (codePath.isDirectory()) {
9709            try {
9710                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9711            } catch (InstallerException e) {
9712                Slog.w(TAG, "Failed to remove code path", e);
9713            }
9714        } else {
9715            codePath.delete();
9716        }
9717    }
9718
9719    private int[] resolveUserIds(int userId) {
9720        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9721    }
9722
9723    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9724        if (pkg == null) {
9725            Slog.wtf(TAG, "Package was null!", new Throwable());
9726            return;
9727        }
9728        clearAppDataLeafLIF(pkg, userId, flags);
9729        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9730        for (int i = 0; i < childCount; i++) {
9731            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9732        }
9733    }
9734
9735    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9736        final PackageSetting ps;
9737        synchronized (mPackages) {
9738            ps = mSettings.mPackages.get(pkg.packageName);
9739        }
9740        for (int realUserId : resolveUserIds(userId)) {
9741            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9742            try {
9743                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9744                        ceDataInode);
9745            } catch (InstallerException e) {
9746                Slog.w(TAG, String.valueOf(e));
9747            }
9748        }
9749    }
9750
9751    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9752        if (pkg == null) {
9753            Slog.wtf(TAG, "Package was null!", new Throwable());
9754            return;
9755        }
9756        destroyAppDataLeafLIF(pkg, userId, flags);
9757        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9758        for (int i = 0; i < childCount; i++) {
9759            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9760        }
9761    }
9762
9763    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9764        final PackageSetting ps;
9765        synchronized (mPackages) {
9766            ps = mSettings.mPackages.get(pkg.packageName);
9767        }
9768        for (int realUserId : resolveUserIds(userId)) {
9769            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9770            try {
9771                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9772                        ceDataInode);
9773            } catch (InstallerException e) {
9774                Slog.w(TAG, String.valueOf(e));
9775            }
9776            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9777        }
9778    }
9779
9780    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9781        if (pkg == null) {
9782            Slog.wtf(TAG, "Package was null!", new Throwable());
9783            return;
9784        }
9785        destroyAppProfilesLeafLIF(pkg);
9786        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9787        for (int i = 0; i < childCount; i++) {
9788            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9789        }
9790    }
9791
9792    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9793        try {
9794            mInstaller.destroyAppProfiles(pkg.packageName);
9795        } catch (InstallerException e) {
9796            Slog.w(TAG, String.valueOf(e));
9797        }
9798    }
9799
9800    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9801        if (pkg == null) {
9802            Slog.wtf(TAG, "Package was null!", new Throwable());
9803            return;
9804        }
9805        clearAppProfilesLeafLIF(pkg);
9806        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9807        for (int i = 0; i < childCount; i++) {
9808            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9809        }
9810    }
9811
9812    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9813        try {
9814            mInstaller.clearAppProfiles(pkg.packageName);
9815        } catch (InstallerException e) {
9816            Slog.w(TAG, String.valueOf(e));
9817        }
9818    }
9819
9820    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9821            long lastUpdateTime) {
9822        // Set parent install/update time
9823        PackageSetting ps = (PackageSetting) pkg.mExtras;
9824        if (ps != null) {
9825            ps.firstInstallTime = firstInstallTime;
9826            ps.lastUpdateTime = lastUpdateTime;
9827        }
9828        // Set children install/update time
9829        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9830        for (int i = 0; i < childCount; i++) {
9831            PackageParser.Package childPkg = pkg.childPackages.get(i);
9832            ps = (PackageSetting) childPkg.mExtras;
9833            if (ps != null) {
9834                ps.firstInstallTime = firstInstallTime;
9835                ps.lastUpdateTime = lastUpdateTime;
9836            }
9837        }
9838    }
9839
9840    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9841            PackageParser.Package changingLib) {
9842        if (file.path != null) {
9843            usesLibraryFiles.add(file.path);
9844            return;
9845        }
9846        PackageParser.Package p = mPackages.get(file.apk);
9847        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9848            // If we are doing this while in the middle of updating a library apk,
9849            // then we need to make sure to use that new apk for determining the
9850            // dependencies here.  (We haven't yet finished committing the new apk
9851            // to the package manager state.)
9852            if (p == null || p.packageName.equals(changingLib.packageName)) {
9853                p = changingLib;
9854            }
9855        }
9856        if (p != null) {
9857            usesLibraryFiles.addAll(p.getAllCodePaths());
9858            if (p.usesLibraryFiles != null) {
9859                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9860            }
9861        }
9862    }
9863
9864    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9865            PackageParser.Package changingLib) throws PackageManagerException {
9866        if (pkg == null) {
9867            return;
9868        }
9869        ArraySet<String> usesLibraryFiles = null;
9870        if (pkg.usesLibraries != null) {
9871            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9872                    null, null, pkg.packageName, changingLib, true, null);
9873        }
9874        if (pkg.usesStaticLibraries != null) {
9875            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9876                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9877                    pkg.packageName, changingLib, true, usesLibraryFiles);
9878        }
9879        if (pkg.usesOptionalLibraries != null) {
9880            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9881                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9882        }
9883        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9884            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9885        } else {
9886            pkg.usesLibraryFiles = null;
9887        }
9888    }
9889
9890    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9891            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9892            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9893            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9894            throws PackageManagerException {
9895        final int libCount = requestedLibraries.size();
9896        for (int i = 0; i < libCount; i++) {
9897            final String libName = requestedLibraries.get(i);
9898            final int libVersion = requiredVersions != null ? requiredVersions[i]
9899                    : SharedLibraryInfo.VERSION_UNDEFINED;
9900            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9901            if (libEntry == null) {
9902                if (required) {
9903                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9904                            "Package " + packageName + " requires unavailable shared library "
9905                                    + libName + "; failing!");
9906                } else if (DEBUG_SHARED_LIBRARIES) {
9907                    Slog.i(TAG, "Package " + packageName
9908                            + " desires unavailable shared library "
9909                            + libName + "; ignoring!");
9910                }
9911            } else {
9912                if (requiredVersions != null && requiredCertDigests != null) {
9913                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9914                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9915                            "Package " + packageName + " requires unavailable static shared"
9916                                    + " library " + libName + " version "
9917                                    + libEntry.info.getVersion() + "; failing!");
9918                    }
9919
9920                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9921                    if (libPkg == null) {
9922                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9923                                "Package " + packageName + " requires unavailable static shared"
9924                                        + " library; failing!");
9925                    }
9926
9927                    String expectedCertDigest = requiredCertDigests[i];
9928                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9929                                libPkg.mSignatures[0]);
9930                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9931                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9932                                "Package " + packageName + " requires differently signed" +
9933                                        " static shared library; failing!");
9934                    }
9935                }
9936
9937                if (outUsedLibraries == null) {
9938                    outUsedLibraries = new ArraySet<>();
9939                }
9940                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9941            }
9942        }
9943        return outUsedLibraries;
9944    }
9945
9946    private static boolean hasString(List<String> list, List<String> which) {
9947        if (list == null) {
9948            return false;
9949        }
9950        for (int i=list.size()-1; i>=0; i--) {
9951            for (int j=which.size()-1; j>=0; j--) {
9952                if (which.get(j).equals(list.get(i))) {
9953                    return true;
9954                }
9955            }
9956        }
9957        return false;
9958    }
9959
9960    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9961            PackageParser.Package changingPkg) {
9962        ArrayList<PackageParser.Package> res = null;
9963        for (PackageParser.Package pkg : mPackages.values()) {
9964            if (changingPkg != null
9965                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9966                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9967                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9968                            changingPkg.staticSharedLibName)) {
9969                return null;
9970            }
9971            if (res == null) {
9972                res = new ArrayList<>();
9973            }
9974            res.add(pkg);
9975            try {
9976                updateSharedLibrariesLPr(pkg, changingPkg);
9977            } catch (PackageManagerException e) {
9978                // If a system app update or an app and a required lib missing we
9979                // delete the package and for updated system apps keep the data as
9980                // it is better for the user to reinstall than to be in an limbo
9981                // state. Also libs disappearing under an app should never happen
9982                // - just in case.
9983                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9984                    final int flags = pkg.isUpdatedSystemApp()
9985                            ? PackageManager.DELETE_KEEP_DATA : 0;
9986                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9987                            flags , null, true, null);
9988                }
9989                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9990            }
9991        }
9992        return res;
9993    }
9994
9995    /**
9996     * Derive the value of the {@code cpuAbiOverride} based on the provided
9997     * value and an optional stored value from the package settings.
9998     */
9999    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10000        String cpuAbiOverride = null;
10001
10002        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10003            cpuAbiOverride = null;
10004        } else if (abiOverride != null) {
10005            cpuAbiOverride = abiOverride;
10006        } else if (settings != null) {
10007            cpuAbiOverride = settings.cpuAbiOverrideString;
10008        }
10009
10010        return cpuAbiOverride;
10011    }
10012
10013    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10014            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10015                    throws PackageManagerException {
10016        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10017        // If the package has children and this is the first dive in the function
10018        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10019        // whether all packages (parent and children) would be successfully scanned
10020        // before the actual scan since scanning mutates internal state and we want
10021        // to atomically install the package and its children.
10022        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10023            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10024                scanFlags |= SCAN_CHECK_ONLY;
10025            }
10026        } else {
10027            scanFlags &= ~SCAN_CHECK_ONLY;
10028        }
10029
10030        final PackageParser.Package scannedPkg;
10031        try {
10032            // Scan the parent
10033            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10034            // Scan the children
10035            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10036            for (int i = 0; i < childCount; i++) {
10037                PackageParser.Package childPkg = pkg.childPackages.get(i);
10038                scanPackageLI(childPkg, policyFlags,
10039                        scanFlags, currentTime, user);
10040            }
10041        } finally {
10042            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10043        }
10044
10045        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10046            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10047        }
10048
10049        return scannedPkg;
10050    }
10051
10052    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10053            int scanFlags, long currentTime, @Nullable UserHandle user)
10054                    throws PackageManagerException {
10055        boolean success = false;
10056        try {
10057            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10058                    currentTime, user);
10059            success = true;
10060            return res;
10061        } finally {
10062            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10063                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10064                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10065                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10066                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10067            }
10068        }
10069    }
10070
10071    /**
10072     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10073     */
10074    private static boolean apkHasCode(String fileName) {
10075        StrictJarFile jarFile = null;
10076        try {
10077            jarFile = new StrictJarFile(fileName,
10078                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10079            return jarFile.findEntry("classes.dex") != null;
10080        } catch (IOException ignore) {
10081        } finally {
10082            try {
10083                if (jarFile != null) {
10084                    jarFile.close();
10085                }
10086            } catch (IOException ignore) {}
10087        }
10088        return false;
10089    }
10090
10091    /**
10092     * Enforces code policy for the package. This ensures that if an APK has
10093     * declared hasCode="true" in its manifest that the APK actually contains
10094     * code.
10095     *
10096     * @throws PackageManagerException If bytecode could not be found when it should exist
10097     */
10098    private static void assertCodePolicy(PackageParser.Package pkg)
10099            throws PackageManagerException {
10100        final boolean shouldHaveCode =
10101                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10102        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10103            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10104                    "Package " + pkg.baseCodePath + " code is missing");
10105        }
10106
10107        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10108            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10109                final boolean splitShouldHaveCode =
10110                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10111                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10112                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10113                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10114                }
10115            }
10116        }
10117    }
10118
10119    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10120            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10121                    throws PackageManagerException {
10122        if (DEBUG_PACKAGE_SCANNING) {
10123            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10124                Log.d(TAG, "Scanning package " + pkg.packageName);
10125        }
10126
10127        applyPolicy(pkg, policyFlags);
10128
10129        assertPackageIsValid(pkg, policyFlags, scanFlags);
10130
10131        // Initialize package source and resource directories
10132        final File scanFile = new File(pkg.codePath);
10133        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10134        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10135
10136        SharedUserSetting suid = null;
10137        PackageSetting pkgSetting = null;
10138
10139        // Getting the package setting may have a side-effect, so if we
10140        // are only checking if scan would succeed, stash a copy of the
10141        // old setting to restore at the end.
10142        PackageSetting nonMutatedPs = null;
10143
10144        // We keep references to the derived CPU Abis from settings in oder to reuse
10145        // them in the case where we're not upgrading or booting for the first time.
10146        String primaryCpuAbiFromSettings = null;
10147        String secondaryCpuAbiFromSettings = null;
10148
10149        // writer
10150        synchronized (mPackages) {
10151            if (pkg.mSharedUserId != null) {
10152                // SIDE EFFECTS; may potentially allocate a new shared user
10153                suid = mSettings.getSharedUserLPw(
10154                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10155                if (DEBUG_PACKAGE_SCANNING) {
10156                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10157                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10158                                + "): packages=" + suid.packages);
10159                }
10160            }
10161
10162            // Check if we are renaming from an original package name.
10163            PackageSetting origPackage = null;
10164            String realName = null;
10165            if (pkg.mOriginalPackages != null) {
10166                // This package may need to be renamed to a previously
10167                // installed name.  Let's check on that...
10168                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10169                if (pkg.mOriginalPackages.contains(renamed)) {
10170                    // This package had originally been installed as the
10171                    // original name, and we have already taken care of
10172                    // transitioning to the new one.  Just update the new
10173                    // one to continue using the old name.
10174                    realName = pkg.mRealPackage;
10175                    if (!pkg.packageName.equals(renamed)) {
10176                        // Callers into this function may have already taken
10177                        // care of renaming the package; only do it here if
10178                        // it is not already done.
10179                        pkg.setPackageName(renamed);
10180                    }
10181                } else {
10182                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10183                        if ((origPackage = mSettings.getPackageLPr(
10184                                pkg.mOriginalPackages.get(i))) != null) {
10185                            // We do have the package already installed under its
10186                            // original name...  should we use it?
10187                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10188                                // New package is not compatible with original.
10189                                origPackage = null;
10190                                continue;
10191                            } else if (origPackage.sharedUser != null) {
10192                                // Make sure uid is compatible between packages.
10193                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10194                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10195                                            + " to " + pkg.packageName + ": old uid "
10196                                            + origPackage.sharedUser.name
10197                                            + " differs from " + pkg.mSharedUserId);
10198                                    origPackage = null;
10199                                    continue;
10200                                }
10201                                // TODO: Add case when shared user id is added [b/28144775]
10202                            } else {
10203                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10204                                        + pkg.packageName + " to old name " + origPackage.name);
10205                            }
10206                            break;
10207                        }
10208                    }
10209                }
10210            }
10211
10212            if (mTransferedPackages.contains(pkg.packageName)) {
10213                Slog.w(TAG, "Package " + pkg.packageName
10214                        + " was transferred to another, but its .apk remains");
10215            }
10216
10217            // See comments in nonMutatedPs declaration
10218            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10219                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10220                if (foundPs != null) {
10221                    nonMutatedPs = new PackageSetting(foundPs);
10222                }
10223            }
10224
10225            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10226                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10227                if (foundPs != null) {
10228                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10229                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10230                }
10231            }
10232
10233            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10234            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10235                PackageManagerService.reportSettingsProblem(Log.WARN,
10236                        "Package " + pkg.packageName + " shared user changed from "
10237                                + (pkgSetting.sharedUser != null
10238                                        ? pkgSetting.sharedUser.name : "<nothing>")
10239                                + " to "
10240                                + (suid != null ? suid.name : "<nothing>")
10241                                + "; replacing with new");
10242                pkgSetting = null;
10243            }
10244            final PackageSetting oldPkgSetting =
10245                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10246            final PackageSetting disabledPkgSetting =
10247                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10248
10249            String[] usesStaticLibraries = null;
10250            if (pkg.usesStaticLibraries != null) {
10251                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10252                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10253            }
10254
10255            if (pkgSetting == null) {
10256                final String parentPackageName = (pkg.parentPackage != null)
10257                        ? pkg.parentPackage.packageName : null;
10258                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10259                // REMOVE SharedUserSetting from method; update in a separate call
10260                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10261                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10262                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10263                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10264                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10265                        true /*allowInstall*/, instantApp, parentPackageName,
10266                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10267                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10268                // SIDE EFFECTS; updates system state; move elsewhere
10269                if (origPackage != null) {
10270                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10271                }
10272                mSettings.addUserToSettingLPw(pkgSetting);
10273            } else {
10274                // REMOVE SharedUserSetting from method; update in a separate call.
10275                //
10276                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10277                // secondaryCpuAbi are not known at this point so we always update them
10278                // to null here, only to reset them at a later point.
10279                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10280                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10281                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10282                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10283                        UserManagerService.getInstance(), usesStaticLibraries,
10284                        pkg.usesStaticLibrariesVersions);
10285            }
10286            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10287            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10288
10289            // SIDE EFFECTS; modifies system state; move elsewhere
10290            if (pkgSetting.origPackage != null) {
10291                // If we are first transitioning from an original package,
10292                // fix up the new package's name now.  We need to do this after
10293                // looking up the package under its new name, so getPackageLP
10294                // can take care of fiddling things correctly.
10295                pkg.setPackageName(origPackage.name);
10296
10297                // File a report about this.
10298                String msg = "New package " + pkgSetting.realName
10299                        + " renamed to replace old package " + pkgSetting.name;
10300                reportSettingsProblem(Log.WARN, msg);
10301
10302                // Make a note of it.
10303                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10304                    mTransferedPackages.add(origPackage.name);
10305                }
10306
10307                // No longer need to retain this.
10308                pkgSetting.origPackage = null;
10309            }
10310
10311            // SIDE EFFECTS; modifies system state; move elsewhere
10312            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10313                // Make a note of it.
10314                mTransferedPackages.add(pkg.packageName);
10315            }
10316
10317            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10318                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10319            }
10320
10321            if ((scanFlags & SCAN_BOOTING) == 0
10322                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10323                // Check all shared libraries and map to their actual file path.
10324                // We only do this here for apps not on a system dir, because those
10325                // are the only ones that can fail an install due to this.  We
10326                // will take care of the system apps by updating all of their
10327                // library paths after the scan is done. Also during the initial
10328                // scan don't update any libs as we do this wholesale after all
10329                // apps are scanned to avoid dependency based scanning.
10330                updateSharedLibrariesLPr(pkg, null);
10331            }
10332
10333            if (mFoundPolicyFile) {
10334                SELinuxMMAC.assignSeInfoValue(pkg);
10335            }
10336            pkg.applicationInfo.uid = pkgSetting.appId;
10337            pkg.mExtras = pkgSetting;
10338
10339
10340            // Static shared libs have same package with different versions where
10341            // we internally use a synthetic package name to allow multiple versions
10342            // of the same package, therefore we need to compare signatures against
10343            // the package setting for the latest library version.
10344            PackageSetting signatureCheckPs = pkgSetting;
10345            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10346                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10347                if (libraryEntry != null) {
10348                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10349                }
10350            }
10351
10352            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10353                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10354                    // We just determined the app is signed correctly, so bring
10355                    // over the latest parsed certs.
10356                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10357                } else {
10358                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10359                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10360                                "Package " + pkg.packageName + " upgrade keys do not match the "
10361                                + "previously installed version");
10362                    } else {
10363                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10364                        String msg = "System package " + pkg.packageName
10365                                + " signature changed; retaining data.";
10366                        reportSettingsProblem(Log.WARN, msg);
10367                    }
10368                }
10369            } else {
10370                try {
10371                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10372                    verifySignaturesLP(signatureCheckPs, pkg);
10373                    // We just determined the app is signed correctly, so bring
10374                    // over the latest parsed certs.
10375                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10376                } catch (PackageManagerException e) {
10377                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10378                        throw e;
10379                    }
10380                    // The signature has changed, but this package is in the system
10381                    // image...  let's recover!
10382                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10383                    // However...  if this package is part of a shared user, but it
10384                    // doesn't match the signature of the shared user, let's fail.
10385                    // What this means is that you can't change the signatures
10386                    // associated with an overall shared user, which doesn't seem all
10387                    // that unreasonable.
10388                    if (signatureCheckPs.sharedUser != null) {
10389                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10390                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10391                            throw new PackageManagerException(
10392                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10393                                    "Signature mismatch for shared user: "
10394                                            + pkgSetting.sharedUser);
10395                        }
10396                    }
10397                    // File a report about this.
10398                    String msg = "System package " + pkg.packageName
10399                            + " signature changed; retaining data.";
10400                    reportSettingsProblem(Log.WARN, msg);
10401                }
10402            }
10403
10404            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10405                // This package wants to adopt ownership of permissions from
10406                // another package.
10407                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10408                    final String origName = pkg.mAdoptPermissions.get(i);
10409                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10410                    if (orig != null) {
10411                        if (verifyPackageUpdateLPr(orig, pkg)) {
10412                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10413                                    + pkg.packageName);
10414                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10415                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10416                        }
10417                    }
10418                }
10419            }
10420        }
10421
10422        pkg.applicationInfo.processName = fixProcessName(
10423                pkg.applicationInfo.packageName,
10424                pkg.applicationInfo.processName);
10425
10426        if (pkg != mPlatformPackage) {
10427            // Get all of our default paths setup
10428            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10429        }
10430
10431        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10432
10433        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10434            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10435                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10436                final boolean extractNativeLibs = !pkg.isLibrary();
10437                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10438                        mAppLib32InstallDir);
10439                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10440
10441                // Some system apps still use directory structure for native libraries
10442                // in which case we might end up not detecting abi solely based on apk
10443                // structure. Try to detect abi based on directory structure.
10444                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10445                        pkg.applicationInfo.primaryCpuAbi == null) {
10446                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10447                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10448                }
10449            } else {
10450                // This is not a first boot or an upgrade, don't bother deriving the
10451                // ABI during the scan. Instead, trust the value that was stored in the
10452                // package setting.
10453                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10454                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10455
10456                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10457
10458                if (DEBUG_ABI_SELECTION) {
10459                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10460                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10461                        pkg.applicationInfo.secondaryCpuAbi);
10462                }
10463            }
10464        } else {
10465            if ((scanFlags & SCAN_MOVE) != 0) {
10466                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10467                // but we already have this packages package info in the PackageSetting. We just
10468                // use that and derive the native library path based on the new codepath.
10469                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10470                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10471            }
10472
10473            // Set native library paths again. For moves, the path will be updated based on the
10474            // ABIs we've determined above. For non-moves, the path will be updated based on the
10475            // ABIs we determined during compilation, but the path will depend on the final
10476            // package path (after the rename away from the stage path).
10477            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10478        }
10479
10480        // This is a special case for the "system" package, where the ABI is
10481        // dictated by the zygote configuration (and init.rc). We should keep track
10482        // of this ABI so that we can deal with "normal" applications that run under
10483        // the same UID correctly.
10484        if (mPlatformPackage == pkg) {
10485            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10486                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10487        }
10488
10489        // If there's a mismatch between the abi-override in the package setting
10490        // and the abiOverride specified for the install. Warn about this because we
10491        // would've already compiled the app without taking the package setting into
10492        // account.
10493        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10494            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10495                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10496                        " for package " + pkg.packageName);
10497            }
10498        }
10499
10500        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10501        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10502        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10503
10504        // Copy the derived override back to the parsed package, so that we can
10505        // update the package settings accordingly.
10506        pkg.cpuAbiOverride = cpuAbiOverride;
10507
10508        if (DEBUG_ABI_SELECTION) {
10509            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10510                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10511                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10512        }
10513
10514        // Push the derived path down into PackageSettings so we know what to
10515        // clean up at uninstall time.
10516        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10517
10518        if (DEBUG_ABI_SELECTION) {
10519            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10520                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10521                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10522        }
10523
10524        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10525        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10526            // We don't do this here during boot because we can do it all
10527            // at once after scanning all existing packages.
10528            //
10529            // We also do this *before* we perform dexopt on this package, so that
10530            // we can avoid redundant dexopts, and also to make sure we've got the
10531            // code and package path correct.
10532            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10533        }
10534
10535        if (mFactoryTest && pkg.requestedPermissions.contains(
10536                android.Manifest.permission.FACTORY_TEST)) {
10537            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10538        }
10539
10540        if (isSystemApp(pkg)) {
10541            pkgSetting.isOrphaned = true;
10542        }
10543
10544        // Take care of first install / last update times.
10545        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10546        if (currentTime != 0) {
10547            if (pkgSetting.firstInstallTime == 0) {
10548                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10549            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10550                pkgSetting.lastUpdateTime = currentTime;
10551            }
10552        } else if (pkgSetting.firstInstallTime == 0) {
10553            // We need *something*.  Take time time stamp of the file.
10554            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10555        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10556            if (scanFileTime != pkgSetting.timeStamp) {
10557                // A package on the system image has changed; consider this
10558                // to be an update.
10559                pkgSetting.lastUpdateTime = scanFileTime;
10560            }
10561        }
10562        pkgSetting.setTimeStamp(scanFileTime);
10563
10564        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10565            if (nonMutatedPs != null) {
10566                synchronized (mPackages) {
10567                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10568                }
10569            }
10570        } else {
10571            final int userId = user == null ? 0 : user.getIdentifier();
10572            // Modify state for the given package setting
10573            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10574                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10575            if (pkgSetting.getInstantApp(userId)) {
10576                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10577            }
10578        }
10579        return pkg;
10580    }
10581
10582    /**
10583     * Applies policy to the parsed package based upon the given policy flags.
10584     * Ensures the package is in a good state.
10585     * <p>
10586     * Implementation detail: This method must NOT have any side effect. It would
10587     * ideally be static, but, it requires locks to read system state.
10588     */
10589    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10590        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10591            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10592            if (pkg.applicationInfo.isDirectBootAware()) {
10593                // we're direct boot aware; set for all components
10594                for (PackageParser.Service s : pkg.services) {
10595                    s.info.encryptionAware = s.info.directBootAware = true;
10596                }
10597                for (PackageParser.Provider p : pkg.providers) {
10598                    p.info.encryptionAware = p.info.directBootAware = true;
10599                }
10600                for (PackageParser.Activity a : pkg.activities) {
10601                    a.info.encryptionAware = a.info.directBootAware = true;
10602                }
10603                for (PackageParser.Activity r : pkg.receivers) {
10604                    r.info.encryptionAware = r.info.directBootAware = true;
10605                }
10606            }
10607        } else {
10608            // Only allow system apps to be flagged as core apps.
10609            pkg.coreApp = false;
10610            // clear flags not applicable to regular apps
10611            pkg.applicationInfo.privateFlags &=
10612                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10613            pkg.applicationInfo.privateFlags &=
10614                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10615        }
10616        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10617
10618        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10619            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10620        }
10621
10622        if (!isSystemApp(pkg)) {
10623            // Only system apps can use these features.
10624            pkg.mOriginalPackages = null;
10625            pkg.mRealPackage = null;
10626            pkg.mAdoptPermissions = null;
10627        }
10628    }
10629
10630    /**
10631     * Asserts the parsed package is valid according to the given policy. If the
10632     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10633     * <p>
10634     * Implementation detail: This method must NOT have any side effects. It would
10635     * ideally be static, but, it requires locks to read system state.
10636     *
10637     * @throws PackageManagerException If the package fails any of the validation checks
10638     */
10639    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10640            throws PackageManagerException {
10641        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10642            assertCodePolicy(pkg);
10643        }
10644
10645        if (pkg.applicationInfo.getCodePath() == null ||
10646                pkg.applicationInfo.getResourcePath() == null) {
10647            // Bail out. The resource and code paths haven't been set.
10648            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10649                    "Code and resource paths haven't been set correctly");
10650        }
10651
10652        // Make sure we're not adding any bogus keyset info
10653        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10654        ksms.assertScannedPackageValid(pkg);
10655
10656        synchronized (mPackages) {
10657            // The special "android" package can only be defined once
10658            if (pkg.packageName.equals("android")) {
10659                if (mAndroidApplication != null) {
10660                    Slog.w(TAG, "*************************************************");
10661                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10662                    Slog.w(TAG, " codePath=" + pkg.codePath);
10663                    Slog.w(TAG, "*************************************************");
10664                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10665                            "Core android package being redefined.  Skipping.");
10666                }
10667            }
10668
10669            // A package name must be unique; don't allow duplicates
10670            if (mPackages.containsKey(pkg.packageName)) {
10671                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10672                        "Application package " + pkg.packageName
10673                        + " already installed.  Skipping duplicate.");
10674            }
10675
10676            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10677                // Static libs have a synthetic package name containing the version
10678                // but we still want the base name to be unique.
10679                if (mPackages.containsKey(pkg.manifestPackageName)) {
10680                    throw new PackageManagerException(
10681                            "Duplicate static shared lib provider package");
10682                }
10683
10684                // Static shared libraries should have at least O target SDK
10685                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10686                    throw new PackageManagerException(
10687                            "Packages declaring static-shared libs must target O SDK or higher");
10688                }
10689
10690                // Package declaring static a shared lib cannot be instant apps
10691                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10692                    throw new PackageManagerException(
10693                            "Packages declaring static-shared libs cannot be instant apps");
10694                }
10695
10696                // Package declaring static a shared lib cannot be renamed since the package
10697                // name is synthetic and apps can't code around package manager internals.
10698                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10699                    throw new PackageManagerException(
10700                            "Packages declaring static-shared libs cannot be renamed");
10701                }
10702
10703                // Package declaring static a shared lib cannot declare child packages
10704                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10705                    throw new PackageManagerException(
10706                            "Packages declaring static-shared libs cannot have child packages");
10707                }
10708
10709                // Package declaring static a shared lib cannot declare dynamic libs
10710                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10711                    throw new PackageManagerException(
10712                            "Packages declaring static-shared libs cannot declare dynamic libs");
10713                }
10714
10715                // Package declaring static a shared lib cannot declare shared users
10716                if (pkg.mSharedUserId != null) {
10717                    throw new PackageManagerException(
10718                            "Packages declaring static-shared libs cannot declare shared users");
10719                }
10720
10721                // Static shared libs cannot declare activities
10722                if (!pkg.activities.isEmpty()) {
10723                    throw new PackageManagerException(
10724                            "Static shared libs cannot declare activities");
10725                }
10726
10727                // Static shared libs cannot declare services
10728                if (!pkg.services.isEmpty()) {
10729                    throw new PackageManagerException(
10730                            "Static shared libs cannot declare services");
10731                }
10732
10733                // Static shared libs cannot declare providers
10734                if (!pkg.providers.isEmpty()) {
10735                    throw new PackageManagerException(
10736                            "Static shared libs cannot declare content providers");
10737                }
10738
10739                // Static shared libs cannot declare receivers
10740                if (!pkg.receivers.isEmpty()) {
10741                    throw new PackageManagerException(
10742                            "Static shared libs cannot declare broadcast receivers");
10743                }
10744
10745                // Static shared libs cannot declare permission groups
10746                if (!pkg.permissionGroups.isEmpty()) {
10747                    throw new PackageManagerException(
10748                            "Static shared libs cannot declare permission groups");
10749                }
10750
10751                // Static shared libs cannot declare permissions
10752                if (!pkg.permissions.isEmpty()) {
10753                    throw new PackageManagerException(
10754                            "Static shared libs cannot declare permissions");
10755                }
10756
10757                // Static shared libs cannot declare protected broadcasts
10758                if (pkg.protectedBroadcasts != null) {
10759                    throw new PackageManagerException(
10760                            "Static shared libs cannot declare protected broadcasts");
10761                }
10762
10763                // Static shared libs cannot be overlay targets
10764                if (pkg.mOverlayTarget != null) {
10765                    throw new PackageManagerException(
10766                            "Static shared libs cannot be overlay targets");
10767                }
10768
10769                // The version codes must be ordered as lib versions
10770                int minVersionCode = Integer.MIN_VALUE;
10771                int maxVersionCode = Integer.MAX_VALUE;
10772
10773                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10774                        pkg.staticSharedLibName);
10775                if (versionedLib != null) {
10776                    final int versionCount = versionedLib.size();
10777                    for (int i = 0; i < versionCount; i++) {
10778                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10779                        final int libVersionCode = libInfo.getDeclaringPackage()
10780                                .getVersionCode();
10781                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10782                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10783                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10784                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10785                        } else {
10786                            minVersionCode = maxVersionCode = libVersionCode;
10787                            break;
10788                        }
10789                    }
10790                }
10791                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10792                    throw new PackageManagerException("Static shared"
10793                            + " lib version codes must be ordered as lib versions");
10794                }
10795            }
10796
10797            // Only privileged apps and updated privileged apps can add child packages.
10798            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10799                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10800                    throw new PackageManagerException("Only privileged apps can add child "
10801                            + "packages. Ignoring package " + pkg.packageName);
10802                }
10803                final int childCount = pkg.childPackages.size();
10804                for (int i = 0; i < childCount; i++) {
10805                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10806                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10807                            childPkg.packageName)) {
10808                        throw new PackageManagerException("Can't override child of "
10809                                + "another disabled app. Ignoring package " + pkg.packageName);
10810                    }
10811                }
10812            }
10813
10814            // If we're only installing presumed-existing packages, require that the
10815            // scanned APK is both already known and at the path previously established
10816            // for it.  Previously unknown packages we pick up normally, but if we have an
10817            // a priori expectation about this package's install presence, enforce it.
10818            // With a singular exception for new system packages. When an OTA contains
10819            // a new system package, we allow the codepath to change from a system location
10820            // to the user-installed location. If we don't allow this change, any newer,
10821            // user-installed version of the application will be ignored.
10822            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10823                if (mExpectingBetter.containsKey(pkg.packageName)) {
10824                    logCriticalInfo(Log.WARN,
10825                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10826                } else {
10827                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10828                    if (known != null) {
10829                        if (DEBUG_PACKAGE_SCANNING) {
10830                            Log.d(TAG, "Examining " + pkg.codePath
10831                                    + " and requiring known paths " + known.codePathString
10832                                    + " & " + known.resourcePathString);
10833                        }
10834                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10835                                || !pkg.applicationInfo.getResourcePath().equals(
10836                                        known.resourcePathString)) {
10837                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10838                                    "Application package " + pkg.packageName
10839                                    + " found at " + pkg.applicationInfo.getCodePath()
10840                                    + " but expected at " + known.codePathString
10841                                    + "; ignoring.");
10842                        }
10843                    }
10844                }
10845            }
10846
10847            // Verify that this new package doesn't have any content providers
10848            // that conflict with existing packages.  Only do this if the
10849            // package isn't already installed, since we don't want to break
10850            // things that are installed.
10851            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10852                final int N = pkg.providers.size();
10853                int i;
10854                for (i=0; i<N; i++) {
10855                    PackageParser.Provider p = pkg.providers.get(i);
10856                    if (p.info.authority != null) {
10857                        String names[] = p.info.authority.split(";");
10858                        for (int j = 0; j < names.length; j++) {
10859                            if (mProvidersByAuthority.containsKey(names[j])) {
10860                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10861                                final String otherPackageName =
10862                                        ((other != null && other.getComponentName() != null) ?
10863                                                other.getComponentName().getPackageName() : "?");
10864                                throw new PackageManagerException(
10865                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10866                                        "Can't install because provider name " + names[j]
10867                                                + " (in package " + pkg.applicationInfo.packageName
10868                                                + ") is already used by " + otherPackageName);
10869                            }
10870                        }
10871                    }
10872                }
10873            }
10874        }
10875    }
10876
10877    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10878            int type, String declaringPackageName, int declaringVersionCode) {
10879        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10880        if (versionedLib == null) {
10881            versionedLib = new SparseArray<>();
10882            mSharedLibraries.put(name, versionedLib);
10883            if (type == SharedLibraryInfo.TYPE_STATIC) {
10884                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10885            }
10886        } else if (versionedLib.indexOfKey(version) >= 0) {
10887            return false;
10888        }
10889        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10890                version, type, declaringPackageName, declaringVersionCode);
10891        versionedLib.put(version, libEntry);
10892        return true;
10893    }
10894
10895    private boolean removeSharedLibraryLPw(String name, int version) {
10896        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10897        if (versionedLib == null) {
10898            return false;
10899        }
10900        final int libIdx = versionedLib.indexOfKey(version);
10901        if (libIdx < 0) {
10902            return false;
10903        }
10904        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10905        versionedLib.remove(version);
10906        if (versionedLib.size() <= 0) {
10907            mSharedLibraries.remove(name);
10908            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10909                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10910                        .getPackageName());
10911            }
10912        }
10913        return true;
10914    }
10915
10916    /**
10917     * Adds a scanned package to the system. When this method is finished, the package will
10918     * be available for query, resolution, etc...
10919     */
10920    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10921            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10922        final String pkgName = pkg.packageName;
10923        if (mCustomResolverComponentName != null &&
10924                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10925            setUpCustomResolverActivity(pkg);
10926        }
10927
10928        if (pkg.packageName.equals("android")) {
10929            synchronized (mPackages) {
10930                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10931                    // Set up information for our fall-back user intent resolution activity.
10932                    mPlatformPackage = pkg;
10933                    pkg.mVersionCode = mSdkVersion;
10934                    mAndroidApplication = pkg.applicationInfo;
10935                    if (!mResolverReplaced) {
10936                        mResolveActivity.applicationInfo = mAndroidApplication;
10937                        mResolveActivity.name = ResolverActivity.class.getName();
10938                        mResolveActivity.packageName = mAndroidApplication.packageName;
10939                        mResolveActivity.processName = "system:ui";
10940                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10941                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10942                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10943                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10944                        mResolveActivity.exported = true;
10945                        mResolveActivity.enabled = true;
10946                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10947                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10948                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10949                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10950                                | ActivityInfo.CONFIG_ORIENTATION
10951                                | ActivityInfo.CONFIG_KEYBOARD
10952                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10953                        mResolveInfo.activityInfo = mResolveActivity;
10954                        mResolveInfo.priority = 0;
10955                        mResolveInfo.preferredOrder = 0;
10956                        mResolveInfo.match = 0;
10957                        mResolveComponentName = new ComponentName(
10958                                mAndroidApplication.packageName, mResolveActivity.name);
10959                    }
10960                }
10961            }
10962        }
10963
10964        ArrayList<PackageParser.Package> clientLibPkgs = null;
10965        // writer
10966        synchronized (mPackages) {
10967            boolean hasStaticSharedLibs = false;
10968
10969            // Any app can add new static shared libraries
10970            if (pkg.staticSharedLibName != null) {
10971                // Static shared libs don't allow renaming as they have synthetic package
10972                // names to allow install of multiple versions, so use name from manifest.
10973                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10974                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10975                        pkg.manifestPackageName, pkg.mVersionCode)) {
10976                    hasStaticSharedLibs = true;
10977                } else {
10978                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10979                                + pkg.staticSharedLibName + " already exists; skipping");
10980                }
10981                // Static shared libs cannot be updated once installed since they
10982                // use synthetic package name which includes the version code, so
10983                // not need to update other packages's shared lib dependencies.
10984            }
10985
10986            if (!hasStaticSharedLibs
10987                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10988                // Only system apps can add new dynamic shared libraries.
10989                if (pkg.libraryNames != null) {
10990                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10991                        String name = pkg.libraryNames.get(i);
10992                        boolean allowed = false;
10993                        if (pkg.isUpdatedSystemApp()) {
10994                            // New library entries can only be added through the
10995                            // system image.  This is important to get rid of a lot
10996                            // of nasty edge cases: for example if we allowed a non-
10997                            // system update of the app to add a library, then uninstalling
10998                            // the update would make the library go away, and assumptions
10999                            // we made such as through app install filtering would now
11000                            // have allowed apps on the device which aren't compatible
11001                            // with it.  Better to just have the restriction here, be
11002                            // conservative, and create many fewer cases that can negatively
11003                            // impact the user experience.
11004                            final PackageSetting sysPs = mSettings
11005                                    .getDisabledSystemPkgLPr(pkg.packageName);
11006                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11007                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11008                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11009                                        allowed = true;
11010                                        break;
11011                                    }
11012                                }
11013                            }
11014                        } else {
11015                            allowed = true;
11016                        }
11017                        if (allowed) {
11018                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11019                                    SharedLibraryInfo.VERSION_UNDEFINED,
11020                                    SharedLibraryInfo.TYPE_DYNAMIC,
11021                                    pkg.packageName, pkg.mVersionCode)) {
11022                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11023                                        + name + " already exists; skipping");
11024                            }
11025                        } else {
11026                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11027                                    + name + " that is not declared on system image; skipping");
11028                        }
11029                    }
11030
11031                    if ((scanFlags & SCAN_BOOTING) == 0) {
11032                        // If we are not booting, we need to update any applications
11033                        // that are clients of our shared library.  If we are booting,
11034                        // this will all be done once the scan is complete.
11035                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11036                    }
11037                }
11038            }
11039        }
11040
11041        if ((scanFlags & SCAN_BOOTING) != 0) {
11042            // No apps can run during boot scan, so they don't need to be frozen
11043        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11044            // Caller asked to not kill app, so it's probably not frozen
11045        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11046            // Caller asked us to ignore frozen check for some reason; they
11047            // probably didn't know the package name
11048        } else {
11049            // We're doing major surgery on this package, so it better be frozen
11050            // right now to keep it from launching
11051            checkPackageFrozen(pkgName);
11052        }
11053
11054        // Also need to kill any apps that are dependent on the library.
11055        if (clientLibPkgs != null) {
11056            for (int i=0; i<clientLibPkgs.size(); i++) {
11057                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11058                killApplication(clientPkg.applicationInfo.packageName,
11059                        clientPkg.applicationInfo.uid, "update lib");
11060            }
11061        }
11062
11063        // writer
11064        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11065
11066        synchronized (mPackages) {
11067            // We don't expect installation to fail beyond this point
11068
11069            // Add the new setting to mSettings
11070            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11071            // Add the new setting to mPackages
11072            mPackages.put(pkg.applicationInfo.packageName, pkg);
11073            // Make sure we don't accidentally delete its data.
11074            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11075            while (iter.hasNext()) {
11076                PackageCleanItem item = iter.next();
11077                if (pkgName.equals(item.packageName)) {
11078                    iter.remove();
11079                }
11080            }
11081
11082            // Add the package's KeySets to the global KeySetManagerService
11083            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11084            ksms.addScannedPackageLPw(pkg);
11085
11086            int N = pkg.providers.size();
11087            StringBuilder r = null;
11088            int i;
11089            for (i=0; i<N; i++) {
11090                PackageParser.Provider p = pkg.providers.get(i);
11091                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11092                        p.info.processName);
11093                mProviders.addProvider(p);
11094                p.syncable = p.info.isSyncable;
11095                if (p.info.authority != null) {
11096                    String names[] = p.info.authority.split(";");
11097                    p.info.authority = null;
11098                    for (int j = 0; j < names.length; j++) {
11099                        if (j == 1 && p.syncable) {
11100                            // We only want the first authority for a provider to possibly be
11101                            // syncable, so if we already added this provider using a different
11102                            // authority clear the syncable flag. We copy the provider before
11103                            // changing it because the mProviders object contains a reference
11104                            // to a provider that we don't want to change.
11105                            // Only do this for the second authority since the resulting provider
11106                            // object can be the same for all future authorities for this provider.
11107                            p = new PackageParser.Provider(p);
11108                            p.syncable = false;
11109                        }
11110                        if (!mProvidersByAuthority.containsKey(names[j])) {
11111                            mProvidersByAuthority.put(names[j], p);
11112                            if (p.info.authority == null) {
11113                                p.info.authority = names[j];
11114                            } else {
11115                                p.info.authority = p.info.authority + ";" + names[j];
11116                            }
11117                            if (DEBUG_PACKAGE_SCANNING) {
11118                                if (chatty)
11119                                    Log.d(TAG, "Registered content provider: " + names[j]
11120                                            + ", className = " + p.info.name + ", isSyncable = "
11121                                            + p.info.isSyncable);
11122                            }
11123                        } else {
11124                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11125                            Slog.w(TAG, "Skipping provider name " + names[j] +
11126                                    " (in package " + pkg.applicationInfo.packageName +
11127                                    "): name already used by "
11128                                    + ((other != null && other.getComponentName() != null)
11129                                            ? other.getComponentName().getPackageName() : "?"));
11130                        }
11131                    }
11132                }
11133                if (chatty) {
11134                    if (r == null) {
11135                        r = new StringBuilder(256);
11136                    } else {
11137                        r.append(' ');
11138                    }
11139                    r.append(p.info.name);
11140                }
11141            }
11142            if (r != null) {
11143                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11144            }
11145
11146            N = pkg.services.size();
11147            r = null;
11148            for (i=0; i<N; i++) {
11149                PackageParser.Service s = pkg.services.get(i);
11150                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11151                        s.info.processName);
11152                mServices.addService(s);
11153                if (chatty) {
11154                    if (r == null) {
11155                        r = new StringBuilder(256);
11156                    } else {
11157                        r.append(' ');
11158                    }
11159                    r.append(s.info.name);
11160                }
11161            }
11162            if (r != null) {
11163                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11164            }
11165
11166            N = pkg.receivers.size();
11167            r = null;
11168            for (i=0; i<N; i++) {
11169                PackageParser.Activity a = pkg.receivers.get(i);
11170                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11171                        a.info.processName);
11172                mReceivers.addActivity(a, "receiver");
11173                if (chatty) {
11174                    if (r == null) {
11175                        r = new StringBuilder(256);
11176                    } else {
11177                        r.append(' ');
11178                    }
11179                    r.append(a.info.name);
11180                }
11181            }
11182            if (r != null) {
11183                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11184            }
11185
11186            N = pkg.activities.size();
11187            r = null;
11188            for (i=0; i<N; i++) {
11189                PackageParser.Activity a = pkg.activities.get(i);
11190                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11191                        a.info.processName);
11192                mActivities.addActivity(a, "activity");
11193                if (chatty) {
11194                    if (r == null) {
11195                        r = new StringBuilder(256);
11196                    } else {
11197                        r.append(' ');
11198                    }
11199                    r.append(a.info.name);
11200                }
11201            }
11202            if (r != null) {
11203                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11204            }
11205
11206            N = pkg.permissionGroups.size();
11207            r = null;
11208            for (i=0; i<N; i++) {
11209                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11210                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11211                final String curPackageName = cur == null ? null : cur.info.packageName;
11212                // Dont allow ephemeral apps to define new permission groups.
11213                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11214                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11215                            + pg.info.packageName
11216                            + " ignored: instant apps cannot define new permission groups.");
11217                    continue;
11218                }
11219                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11220                if (cur == null || isPackageUpdate) {
11221                    mPermissionGroups.put(pg.info.name, pg);
11222                    if (chatty) {
11223                        if (r == null) {
11224                            r = new StringBuilder(256);
11225                        } else {
11226                            r.append(' ');
11227                        }
11228                        if (isPackageUpdate) {
11229                            r.append("UPD:");
11230                        }
11231                        r.append(pg.info.name);
11232                    }
11233                } else {
11234                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11235                            + pg.info.packageName + " ignored: original from "
11236                            + cur.info.packageName);
11237                    if (chatty) {
11238                        if (r == null) {
11239                            r = new StringBuilder(256);
11240                        } else {
11241                            r.append(' ');
11242                        }
11243                        r.append("DUP:");
11244                        r.append(pg.info.name);
11245                    }
11246                }
11247            }
11248            if (r != null) {
11249                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11250            }
11251
11252            N = pkg.permissions.size();
11253            r = null;
11254            for (i=0; i<N; i++) {
11255                PackageParser.Permission p = pkg.permissions.get(i);
11256
11257                // Dont allow ephemeral apps to define new permissions.
11258                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11259                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11260                            + p.info.packageName
11261                            + " ignored: instant apps cannot define new permissions.");
11262                    continue;
11263                }
11264
11265                // Assume by default that we did not install this permission into the system.
11266                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11267
11268                // Now that permission groups have a special meaning, we ignore permission
11269                // groups for legacy apps to prevent unexpected behavior. In particular,
11270                // permissions for one app being granted to someone just because they happen
11271                // to be in a group defined by another app (before this had no implications).
11272                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11273                    p.group = mPermissionGroups.get(p.info.group);
11274                    // Warn for a permission in an unknown group.
11275                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11276                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11277                                + p.info.packageName + " in an unknown group " + p.info.group);
11278                    }
11279                }
11280
11281                ArrayMap<String, BasePermission> permissionMap =
11282                        p.tree ? mSettings.mPermissionTrees
11283                                : mSettings.mPermissions;
11284                BasePermission bp = permissionMap.get(p.info.name);
11285
11286                // Allow system apps to redefine non-system permissions
11287                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11288                    final boolean currentOwnerIsSystem = (bp.perm != null
11289                            && isSystemApp(bp.perm.owner));
11290                    if (isSystemApp(p.owner)) {
11291                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11292                            // It's a built-in permission and no owner, take ownership now
11293                            bp.packageSetting = pkgSetting;
11294                            bp.perm = p;
11295                            bp.uid = pkg.applicationInfo.uid;
11296                            bp.sourcePackage = p.info.packageName;
11297                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11298                        } else if (!currentOwnerIsSystem) {
11299                            String msg = "New decl " + p.owner + " of permission  "
11300                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11301                            reportSettingsProblem(Log.WARN, msg);
11302                            bp = null;
11303                        }
11304                    }
11305                }
11306
11307                if (bp == null) {
11308                    bp = new BasePermission(p.info.name, p.info.packageName,
11309                            BasePermission.TYPE_NORMAL);
11310                    permissionMap.put(p.info.name, bp);
11311                }
11312
11313                if (bp.perm == null) {
11314                    if (bp.sourcePackage == null
11315                            || bp.sourcePackage.equals(p.info.packageName)) {
11316                        BasePermission tree = findPermissionTreeLP(p.info.name);
11317                        if (tree == null
11318                                || tree.sourcePackage.equals(p.info.packageName)) {
11319                            bp.packageSetting = pkgSetting;
11320                            bp.perm = p;
11321                            bp.uid = pkg.applicationInfo.uid;
11322                            bp.sourcePackage = p.info.packageName;
11323                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11324                            if (chatty) {
11325                                if (r == null) {
11326                                    r = new StringBuilder(256);
11327                                } else {
11328                                    r.append(' ');
11329                                }
11330                                r.append(p.info.name);
11331                            }
11332                        } else {
11333                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11334                                    + p.info.packageName + " ignored: base tree "
11335                                    + tree.name + " is from package "
11336                                    + tree.sourcePackage);
11337                        }
11338                    } else {
11339                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11340                                + p.info.packageName + " ignored: original from "
11341                                + bp.sourcePackage);
11342                    }
11343                } else if (chatty) {
11344                    if (r == null) {
11345                        r = new StringBuilder(256);
11346                    } else {
11347                        r.append(' ');
11348                    }
11349                    r.append("DUP:");
11350                    r.append(p.info.name);
11351                }
11352                if (bp.perm == p) {
11353                    bp.protectionLevel = p.info.protectionLevel;
11354                }
11355            }
11356
11357            if (r != null) {
11358                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11359            }
11360
11361            N = pkg.instrumentation.size();
11362            r = null;
11363            for (i=0; i<N; i++) {
11364                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11365                a.info.packageName = pkg.applicationInfo.packageName;
11366                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11367                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11368                a.info.splitNames = pkg.splitNames;
11369                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11370                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11371                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11372                a.info.dataDir = pkg.applicationInfo.dataDir;
11373                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11374                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11375                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11376                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11377                mInstrumentation.put(a.getComponentName(), a);
11378                if (chatty) {
11379                    if (r == null) {
11380                        r = new StringBuilder(256);
11381                    } else {
11382                        r.append(' ');
11383                    }
11384                    r.append(a.info.name);
11385                }
11386            }
11387            if (r != null) {
11388                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11389            }
11390
11391            if (pkg.protectedBroadcasts != null) {
11392                N = pkg.protectedBroadcasts.size();
11393                for (i=0; i<N; i++) {
11394                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11395                }
11396            }
11397        }
11398
11399        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11400    }
11401
11402    /**
11403     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11404     * is derived purely on the basis of the contents of {@code scanFile} and
11405     * {@code cpuAbiOverride}.
11406     *
11407     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11408     */
11409    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11410                                 String cpuAbiOverride, boolean extractLibs,
11411                                 File appLib32InstallDir)
11412            throws PackageManagerException {
11413        // Give ourselves some initial paths; we'll come back for another
11414        // pass once we've determined ABI below.
11415        setNativeLibraryPaths(pkg, appLib32InstallDir);
11416
11417        // We would never need to extract libs for forward-locked and external packages,
11418        // since the container service will do it for us. We shouldn't attempt to
11419        // extract libs from system app when it was not updated.
11420        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11421                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11422            extractLibs = false;
11423        }
11424
11425        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11426        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11427
11428        NativeLibraryHelper.Handle handle = null;
11429        try {
11430            handle = NativeLibraryHelper.Handle.create(pkg);
11431            // TODO(multiArch): This can be null for apps that didn't go through the
11432            // usual installation process. We can calculate it again, like we
11433            // do during install time.
11434            //
11435            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11436            // unnecessary.
11437            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11438
11439            // Null out the abis so that they can be recalculated.
11440            pkg.applicationInfo.primaryCpuAbi = null;
11441            pkg.applicationInfo.secondaryCpuAbi = null;
11442            if (isMultiArch(pkg.applicationInfo)) {
11443                // Warn if we've set an abiOverride for multi-lib packages..
11444                // By definition, we need to copy both 32 and 64 bit libraries for
11445                // such packages.
11446                if (pkg.cpuAbiOverride != null
11447                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11448                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11449                }
11450
11451                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11452                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11453                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11454                    if (extractLibs) {
11455                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11456                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11457                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11458                                useIsaSpecificSubdirs);
11459                    } else {
11460                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11461                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11462                    }
11463                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11464                }
11465
11466                // Shared library native code should be in the APK zip aligned
11467                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11468                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11469                            "Shared library native lib extraction not supported");
11470                }
11471
11472                maybeThrowExceptionForMultiArchCopy(
11473                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11474
11475                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11476                    if (extractLibs) {
11477                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11478                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11479                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11480                                useIsaSpecificSubdirs);
11481                    } else {
11482                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11483                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11484                    }
11485                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11486                }
11487
11488                maybeThrowExceptionForMultiArchCopy(
11489                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11490
11491                if (abi64 >= 0) {
11492                    // Shared library native libs should be in the APK zip aligned
11493                    if (extractLibs && pkg.isLibrary()) {
11494                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11495                                "Shared library native lib extraction not supported");
11496                    }
11497                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11498                }
11499
11500                if (abi32 >= 0) {
11501                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11502                    if (abi64 >= 0) {
11503                        if (pkg.use32bitAbi) {
11504                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11505                            pkg.applicationInfo.primaryCpuAbi = abi;
11506                        } else {
11507                            pkg.applicationInfo.secondaryCpuAbi = abi;
11508                        }
11509                    } else {
11510                        pkg.applicationInfo.primaryCpuAbi = abi;
11511                    }
11512                }
11513            } else {
11514                String[] abiList = (cpuAbiOverride != null) ?
11515                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11516
11517                // Enable gross and lame hacks for apps that are built with old
11518                // SDK tools. We must scan their APKs for renderscript bitcode and
11519                // not launch them if it's present. Don't bother checking on devices
11520                // that don't have 64 bit support.
11521                boolean needsRenderScriptOverride = false;
11522                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11523                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11524                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11525                    needsRenderScriptOverride = true;
11526                }
11527
11528                final int copyRet;
11529                if (extractLibs) {
11530                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11531                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11532                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11533                } else {
11534                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11535                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11536                }
11537                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11538
11539                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11540                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11541                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11542                }
11543
11544                if (copyRet >= 0) {
11545                    // Shared libraries that have native libs must be multi-architecture
11546                    if (pkg.isLibrary()) {
11547                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11548                                "Shared library with native libs must be multiarch");
11549                    }
11550                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11551                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11552                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11553                } else if (needsRenderScriptOverride) {
11554                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11555                }
11556            }
11557        } catch (IOException ioe) {
11558            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11559        } finally {
11560            IoUtils.closeQuietly(handle);
11561        }
11562
11563        // Now that we've calculated the ABIs and determined if it's an internal app,
11564        // we will go ahead and populate the nativeLibraryPath.
11565        setNativeLibraryPaths(pkg, appLib32InstallDir);
11566    }
11567
11568    /**
11569     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11570     * i.e, so that all packages can be run inside a single process if required.
11571     *
11572     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11573     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11574     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11575     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11576     * updating a package that belongs to a shared user.
11577     *
11578     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11579     * adds unnecessary complexity.
11580     */
11581    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11582            PackageParser.Package scannedPackage) {
11583        String requiredInstructionSet = null;
11584        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11585            requiredInstructionSet = VMRuntime.getInstructionSet(
11586                     scannedPackage.applicationInfo.primaryCpuAbi);
11587        }
11588
11589        PackageSetting requirer = null;
11590        for (PackageSetting ps : packagesForUser) {
11591            // If packagesForUser contains scannedPackage, we skip it. This will happen
11592            // when scannedPackage is an update of an existing package. Without this check,
11593            // we will never be able to change the ABI of any package belonging to a shared
11594            // user, even if it's compatible with other packages.
11595            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11596                if (ps.primaryCpuAbiString == null) {
11597                    continue;
11598                }
11599
11600                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11601                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11602                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11603                    // this but there's not much we can do.
11604                    String errorMessage = "Instruction set mismatch, "
11605                            + ((requirer == null) ? "[caller]" : requirer)
11606                            + " requires " + requiredInstructionSet + " whereas " + ps
11607                            + " requires " + instructionSet;
11608                    Slog.w(TAG, errorMessage);
11609                }
11610
11611                if (requiredInstructionSet == null) {
11612                    requiredInstructionSet = instructionSet;
11613                    requirer = ps;
11614                }
11615            }
11616        }
11617
11618        if (requiredInstructionSet != null) {
11619            String adjustedAbi;
11620            if (requirer != null) {
11621                // requirer != null implies that either scannedPackage was null or that scannedPackage
11622                // did not require an ABI, in which case we have to adjust scannedPackage to match
11623                // the ABI of the set (which is the same as requirer's ABI)
11624                adjustedAbi = requirer.primaryCpuAbiString;
11625                if (scannedPackage != null) {
11626                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11627                }
11628            } else {
11629                // requirer == null implies that we're updating all ABIs in the set to
11630                // match scannedPackage.
11631                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11632            }
11633
11634            for (PackageSetting ps : packagesForUser) {
11635                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11636                    if (ps.primaryCpuAbiString != null) {
11637                        continue;
11638                    }
11639
11640                    ps.primaryCpuAbiString = adjustedAbi;
11641                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11642                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11643                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11644                        if (DEBUG_ABI_SELECTION) {
11645                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11646                                    + " (requirer="
11647                                    + (requirer != null ? requirer.pkg : "null")
11648                                    + ", scannedPackage="
11649                                    + (scannedPackage != null ? scannedPackage : "null")
11650                                    + ")");
11651                        }
11652                        try {
11653                            mInstaller.rmdex(ps.codePathString,
11654                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11655                        } catch (InstallerException ignored) {
11656                        }
11657                    }
11658                }
11659            }
11660        }
11661    }
11662
11663    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11664        synchronized (mPackages) {
11665            mResolverReplaced = true;
11666            // Set up information for custom user intent resolution activity.
11667            mResolveActivity.applicationInfo = pkg.applicationInfo;
11668            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11669            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11670            mResolveActivity.processName = pkg.applicationInfo.packageName;
11671            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11672            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11673                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11674            mResolveActivity.theme = 0;
11675            mResolveActivity.exported = true;
11676            mResolveActivity.enabled = true;
11677            mResolveInfo.activityInfo = mResolveActivity;
11678            mResolveInfo.priority = 0;
11679            mResolveInfo.preferredOrder = 0;
11680            mResolveInfo.match = 0;
11681            mResolveComponentName = mCustomResolverComponentName;
11682            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11683                    mResolveComponentName);
11684        }
11685    }
11686
11687    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11688        if (installerActivity == null) {
11689            if (DEBUG_EPHEMERAL) {
11690                Slog.d(TAG, "Clear ephemeral installer activity");
11691            }
11692            mInstantAppInstallerActivity = null;
11693            return;
11694        }
11695
11696        if (DEBUG_EPHEMERAL) {
11697            Slog.d(TAG, "Set ephemeral installer activity: "
11698                    + installerActivity.getComponentName());
11699        }
11700        // Set up information for ephemeral installer activity
11701        mInstantAppInstallerActivity = installerActivity;
11702        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11703                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11704        mInstantAppInstallerActivity.exported = true;
11705        mInstantAppInstallerActivity.enabled = true;
11706        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11707        mInstantAppInstallerInfo.priority = 0;
11708        mInstantAppInstallerInfo.preferredOrder = 1;
11709        mInstantAppInstallerInfo.isDefault = true;
11710        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11711                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11712    }
11713
11714    private static String calculateBundledApkRoot(final String codePathString) {
11715        final File codePath = new File(codePathString);
11716        final File codeRoot;
11717        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11718            codeRoot = Environment.getRootDirectory();
11719        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11720            codeRoot = Environment.getOemDirectory();
11721        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11722            codeRoot = Environment.getVendorDirectory();
11723        } else {
11724            // Unrecognized code path; take its top real segment as the apk root:
11725            // e.g. /something/app/blah.apk => /something
11726            try {
11727                File f = codePath.getCanonicalFile();
11728                File parent = f.getParentFile();    // non-null because codePath is a file
11729                File tmp;
11730                while ((tmp = parent.getParentFile()) != null) {
11731                    f = parent;
11732                    parent = tmp;
11733                }
11734                codeRoot = f;
11735                Slog.w(TAG, "Unrecognized code path "
11736                        + codePath + " - using " + codeRoot);
11737            } catch (IOException e) {
11738                // Can't canonicalize the code path -- shenanigans?
11739                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11740                return Environment.getRootDirectory().getPath();
11741            }
11742        }
11743        return codeRoot.getPath();
11744    }
11745
11746    /**
11747     * Derive and set the location of native libraries for the given package,
11748     * which varies depending on where and how the package was installed.
11749     */
11750    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11751        final ApplicationInfo info = pkg.applicationInfo;
11752        final String codePath = pkg.codePath;
11753        final File codeFile = new File(codePath);
11754        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11755        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11756
11757        info.nativeLibraryRootDir = null;
11758        info.nativeLibraryRootRequiresIsa = false;
11759        info.nativeLibraryDir = null;
11760        info.secondaryNativeLibraryDir = null;
11761
11762        if (isApkFile(codeFile)) {
11763            // Monolithic install
11764            if (bundledApp) {
11765                // If "/system/lib64/apkname" exists, assume that is the per-package
11766                // native library directory to use; otherwise use "/system/lib/apkname".
11767                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11768                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11769                        getPrimaryInstructionSet(info));
11770
11771                // This is a bundled system app so choose the path based on the ABI.
11772                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11773                // is just the default path.
11774                final String apkName = deriveCodePathName(codePath);
11775                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11776                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11777                        apkName).getAbsolutePath();
11778
11779                if (info.secondaryCpuAbi != null) {
11780                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11781                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11782                            secondaryLibDir, apkName).getAbsolutePath();
11783                }
11784            } else if (asecApp) {
11785                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11786                        .getAbsolutePath();
11787            } else {
11788                final String apkName = deriveCodePathName(codePath);
11789                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11790                        .getAbsolutePath();
11791            }
11792
11793            info.nativeLibraryRootRequiresIsa = false;
11794            info.nativeLibraryDir = info.nativeLibraryRootDir;
11795        } else {
11796            // Cluster install
11797            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11798            info.nativeLibraryRootRequiresIsa = true;
11799
11800            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11801                    getPrimaryInstructionSet(info)).getAbsolutePath();
11802
11803            if (info.secondaryCpuAbi != null) {
11804                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11805                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11806            }
11807        }
11808    }
11809
11810    /**
11811     * Calculate the abis and roots for a bundled app. These can uniquely
11812     * be determined from the contents of the system partition, i.e whether
11813     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11814     * of this information, and instead assume that the system was built
11815     * sensibly.
11816     */
11817    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11818                                           PackageSetting pkgSetting) {
11819        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11820
11821        // If "/system/lib64/apkname" exists, assume that is the per-package
11822        // native library directory to use; otherwise use "/system/lib/apkname".
11823        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11824        setBundledAppAbi(pkg, apkRoot, apkName);
11825        // pkgSetting might be null during rescan following uninstall of updates
11826        // to a bundled app, so accommodate that possibility.  The settings in
11827        // that case will be established later from the parsed package.
11828        //
11829        // If the settings aren't null, sync them up with what we've just derived.
11830        // note that apkRoot isn't stored in the package settings.
11831        if (pkgSetting != null) {
11832            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11833            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11834        }
11835    }
11836
11837    /**
11838     * Deduces the ABI of a bundled app and sets the relevant fields on the
11839     * parsed pkg object.
11840     *
11841     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11842     *        under which system libraries are installed.
11843     * @param apkName the name of the installed package.
11844     */
11845    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11846        final File codeFile = new File(pkg.codePath);
11847
11848        final boolean has64BitLibs;
11849        final boolean has32BitLibs;
11850        if (isApkFile(codeFile)) {
11851            // Monolithic install
11852            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11853            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11854        } else {
11855            // Cluster install
11856            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11857            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11858                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11859                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11860                has64BitLibs = (new File(rootDir, isa)).exists();
11861            } else {
11862                has64BitLibs = false;
11863            }
11864            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11865                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11866                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11867                has32BitLibs = (new File(rootDir, isa)).exists();
11868            } else {
11869                has32BitLibs = false;
11870            }
11871        }
11872
11873        if (has64BitLibs && !has32BitLibs) {
11874            // The package has 64 bit libs, but not 32 bit libs. Its primary
11875            // ABI should be 64 bit. We can safely assume here that the bundled
11876            // native libraries correspond to the most preferred ABI in the list.
11877
11878            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11879            pkg.applicationInfo.secondaryCpuAbi = null;
11880        } else if (has32BitLibs && !has64BitLibs) {
11881            // The package has 32 bit libs but not 64 bit libs. Its primary
11882            // ABI should be 32 bit.
11883
11884            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11885            pkg.applicationInfo.secondaryCpuAbi = null;
11886        } else if (has32BitLibs && has64BitLibs) {
11887            // The application has both 64 and 32 bit bundled libraries. We check
11888            // here that the app declares multiArch support, and warn if it doesn't.
11889            //
11890            // We will be lenient here and record both ABIs. The primary will be the
11891            // ABI that's higher on the list, i.e, a device that's configured to prefer
11892            // 64 bit apps will see a 64 bit primary ABI,
11893
11894            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11895                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11896            }
11897
11898            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11899                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11900                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11901            } else {
11902                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11903                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11904            }
11905        } else {
11906            pkg.applicationInfo.primaryCpuAbi = null;
11907            pkg.applicationInfo.secondaryCpuAbi = null;
11908        }
11909    }
11910
11911    private void killApplication(String pkgName, int appId, String reason) {
11912        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11913    }
11914
11915    private void killApplication(String pkgName, int appId, int userId, String reason) {
11916        // Request the ActivityManager to kill the process(only for existing packages)
11917        // so that we do not end up in a confused state while the user is still using the older
11918        // version of the application while the new one gets installed.
11919        final long token = Binder.clearCallingIdentity();
11920        try {
11921            IActivityManager am = ActivityManager.getService();
11922            if (am != null) {
11923                try {
11924                    am.killApplication(pkgName, appId, userId, reason);
11925                } catch (RemoteException e) {
11926                }
11927            }
11928        } finally {
11929            Binder.restoreCallingIdentity(token);
11930        }
11931    }
11932
11933    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11934        // Remove the parent package setting
11935        PackageSetting ps = (PackageSetting) pkg.mExtras;
11936        if (ps != null) {
11937            removePackageLI(ps, chatty);
11938        }
11939        // Remove the child package setting
11940        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11941        for (int i = 0; i < childCount; i++) {
11942            PackageParser.Package childPkg = pkg.childPackages.get(i);
11943            ps = (PackageSetting) childPkg.mExtras;
11944            if (ps != null) {
11945                removePackageLI(ps, chatty);
11946            }
11947        }
11948    }
11949
11950    void removePackageLI(PackageSetting ps, boolean chatty) {
11951        if (DEBUG_INSTALL) {
11952            if (chatty)
11953                Log.d(TAG, "Removing package " + ps.name);
11954        }
11955
11956        // writer
11957        synchronized (mPackages) {
11958            mPackages.remove(ps.name);
11959            final PackageParser.Package pkg = ps.pkg;
11960            if (pkg != null) {
11961                cleanPackageDataStructuresLILPw(pkg, chatty);
11962            }
11963        }
11964    }
11965
11966    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11967        if (DEBUG_INSTALL) {
11968            if (chatty)
11969                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11970        }
11971
11972        // writer
11973        synchronized (mPackages) {
11974            // Remove the parent package
11975            mPackages.remove(pkg.applicationInfo.packageName);
11976            cleanPackageDataStructuresLILPw(pkg, chatty);
11977
11978            // Remove the child packages
11979            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11980            for (int i = 0; i < childCount; i++) {
11981                PackageParser.Package childPkg = pkg.childPackages.get(i);
11982                mPackages.remove(childPkg.applicationInfo.packageName);
11983                cleanPackageDataStructuresLILPw(childPkg, chatty);
11984            }
11985        }
11986    }
11987
11988    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11989        int N = pkg.providers.size();
11990        StringBuilder r = null;
11991        int i;
11992        for (i=0; i<N; i++) {
11993            PackageParser.Provider p = pkg.providers.get(i);
11994            mProviders.removeProvider(p);
11995            if (p.info.authority == null) {
11996
11997                /* There was another ContentProvider with this authority when
11998                 * this app was installed so this authority is null,
11999                 * Ignore it as we don't have to unregister the provider.
12000                 */
12001                continue;
12002            }
12003            String names[] = p.info.authority.split(";");
12004            for (int j = 0; j < names.length; j++) {
12005                if (mProvidersByAuthority.get(names[j]) == p) {
12006                    mProvidersByAuthority.remove(names[j]);
12007                    if (DEBUG_REMOVE) {
12008                        if (chatty)
12009                            Log.d(TAG, "Unregistered content provider: " + names[j]
12010                                    + ", className = " + p.info.name + ", isSyncable = "
12011                                    + p.info.isSyncable);
12012                    }
12013                }
12014            }
12015            if (DEBUG_REMOVE && chatty) {
12016                if (r == null) {
12017                    r = new StringBuilder(256);
12018                } else {
12019                    r.append(' ');
12020                }
12021                r.append(p.info.name);
12022            }
12023        }
12024        if (r != null) {
12025            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12026        }
12027
12028        N = pkg.services.size();
12029        r = null;
12030        for (i=0; i<N; i++) {
12031            PackageParser.Service s = pkg.services.get(i);
12032            mServices.removeService(s);
12033            if (chatty) {
12034                if (r == null) {
12035                    r = new StringBuilder(256);
12036                } else {
12037                    r.append(' ');
12038                }
12039                r.append(s.info.name);
12040            }
12041        }
12042        if (r != null) {
12043            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12044        }
12045
12046        N = pkg.receivers.size();
12047        r = null;
12048        for (i=0; i<N; i++) {
12049            PackageParser.Activity a = pkg.receivers.get(i);
12050            mReceivers.removeActivity(a, "receiver");
12051            if (DEBUG_REMOVE && chatty) {
12052                if (r == null) {
12053                    r = new StringBuilder(256);
12054                } else {
12055                    r.append(' ');
12056                }
12057                r.append(a.info.name);
12058            }
12059        }
12060        if (r != null) {
12061            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12062        }
12063
12064        N = pkg.activities.size();
12065        r = null;
12066        for (i=0; i<N; i++) {
12067            PackageParser.Activity a = pkg.activities.get(i);
12068            mActivities.removeActivity(a, "activity");
12069            if (DEBUG_REMOVE && chatty) {
12070                if (r == null) {
12071                    r = new StringBuilder(256);
12072                } else {
12073                    r.append(' ');
12074                }
12075                r.append(a.info.name);
12076            }
12077        }
12078        if (r != null) {
12079            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12080        }
12081
12082        N = pkg.permissions.size();
12083        r = null;
12084        for (i=0; i<N; i++) {
12085            PackageParser.Permission p = pkg.permissions.get(i);
12086            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12087            if (bp == null) {
12088                bp = mSettings.mPermissionTrees.get(p.info.name);
12089            }
12090            if (bp != null && bp.perm == p) {
12091                bp.perm = null;
12092                if (DEBUG_REMOVE && chatty) {
12093                    if (r == null) {
12094                        r = new StringBuilder(256);
12095                    } else {
12096                        r.append(' ');
12097                    }
12098                    r.append(p.info.name);
12099                }
12100            }
12101            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12102                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12103                if (appOpPkgs != null) {
12104                    appOpPkgs.remove(pkg.packageName);
12105                }
12106            }
12107        }
12108        if (r != null) {
12109            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12110        }
12111
12112        N = pkg.requestedPermissions.size();
12113        r = null;
12114        for (i=0; i<N; i++) {
12115            String perm = pkg.requestedPermissions.get(i);
12116            BasePermission bp = mSettings.mPermissions.get(perm);
12117            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12118                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12119                if (appOpPkgs != null) {
12120                    appOpPkgs.remove(pkg.packageName);
12121                    if (appOpPkgs.isEmpty()) {
12122                        mAppOpPermissionPackages.remove(perm);
12123                    }
12124                }
12125            }
12126        }
12127        if (r != null) {
12128            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12129        }
12130
12131        N = pkg.instrumentation.size();
12132        r = null;
12133        for (i=0; i<N; i++) {
12134            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12135            mInstrumentation.remove(a.getComponentName());
12136            if (DEBUG_REMOVE && chatty) {
12137                if (r == null) {
12138                    r = new StringBuilder(256);
12139                } else {
12140                    r.append(' ');
12141                }
12142                r.append(a.info.name);
12143            }
12144        }
12145        if (r != null) {
12146            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12147        }
12148
12149        r = null;
12150        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12151            // Only system apps can hold shared libraries.
12152            if (pkg.libraryNames != null) {
12153                for (i = 0; i < pkg.libraryNames.size(); i++) {
12154                    String name = pkg.libraryNames.get(i);
12155                    if (removeSharedLibraryLPw(name, 0)) {
12156                        if (DEBUG_REMOVE && chatty) {
12157                            if (r == null) {
12158                                r = new StringBuilder(256);
12159                            } else {
12160                                r.append(' ');
12161                            }
12162                            r.append(name);
12163                        }
12164                    }
12165                }
12166            }
12167        }
12168
12169        r = null;
12170
12171        // Any package can hold static shared libraries.
12172        if (pkg.staticSharedLibName != null) {
12173            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12174                if (DEBUG_REMOVE && chatty) {
12175                    if (r == null) {
12176                        r = new StringBuilder(256);
12177                    } else {
12178                        r.append(' ');
12179                    }
12180                    r.append(pkg.staticSharedLibName);
12181                }
12182            }
12183        }
12184
12185        if (r != null) {
12186            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12187        }
12188    }
12189
12190    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12191        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12192            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12193                return true;
12194            }
12195        }
12196        return false;
12197    }
12198
12199    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12200    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12201    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12202
12203    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12204        // Update the parent permissions
12205        updatePermissionsLPw(pkg.packageName, pkg, flags);
12206        // Update the child permissions
12207        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12208        for (int i = 0; i < childCount; i++) {
12209            PackageParser.Package childPkg = pkg.childPackages.get(i);
12210            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12211        }
12212    }
12213
12214    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12215            int flags) {
12216        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12217        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12218    }
12219
12220    private void updatePermissionsLPw(String changingPkg,
12221            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12222        // Make sure there are no dangling permission trees.
12223        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12224        while (it.hasNext()) {
12225            final BasePermission bp = it.next();
12226            if (bp.packageSetting == null) {
12227                // We may not yet have parsed the package, so just see if
12228                // we still know about its settings.
12229                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12230            }
12231            if (bp.packageSetting == null) {
12232                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12233                        + " from package " + bp.sourcePackage);
12234                it.remove();
12235            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12236                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12237                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12238                            + " from package " + bp.sourcePackage);
12239                    flags |= UPDATE_PERMISSIONS_ALL;
12240                    it.remove();
12241                }
12242            }
12243        }
12244
12245        // Make sure all dynamic permissions have been assigned to a package,
12246        // and make sure there are no dangling permissions.
12247        it = mSettings.mPermissions.values().iterator();
12248        while (it.hasNext()) {
12249            final BasePermission bp = it.next();
12250            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12251                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12252                        + bp.name + " pkg=" + bp.sourcePackage
12253                        + " info=" + bp.pendingInfo);
12254                if (bp.packageSetting == null && bp.pendingInfo != null) {
12255                    final BasePermission tree = findPermissionTreeLP(bp.name);
12256                    if (tree != null && tree.perm != null) {
12257                        bp.packageSetting = tree.packageSetting;
12258                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12259                                new PermissionInfo(bp.pendingInfo));
12260                        bp.perm.info.packageName = tree.perm.info.packageName;
12261                        bp.perm.info.name = bp.name;
12262                        bp.uid = tree.uid;
12263                    }
12264                }
12265            }
12266            if (bp.packageSetting == null) {
12267                // We may not yet have parsed the package, so just see if
12268                // we still know about its settings.
12269                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12270            }
12271            if (bp.packageSetting == null) {
12272                Slog.w(TAG, "Removing dangling permission: " + bp.name
12273                        + " from package " + bp.sourcePackage);
12274                it.remove();
12275            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12276                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12277                    Slog.i(TAG, "Removing old permission: " + bp.name
12278                            + " from package " + bp.sourcePackage);
12279                    flags |= UPDATE_PERMISSIONS_ALL;
12280                    it.remove();
12281                }
12282            }
12283        }
12284
12285        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12286        // Now update the permissions for all packages, in particular
12287        // replace the granted permissions of the system packages.
12288        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12289            for (PackageParser.Package pkg : mPackages.values()) {
12290                if (pkg != pkgInfo) {
12291                    // Only replace for packages on requested volume
12292                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12293                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12294                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12295                    grantPermissionsLPw(pkg, replace, changingPkg);
12296                }
12297            }
12298        }
12299
12300        if (pkgInfo != null) {
12301            // Only replace for packages on requested volume
12302            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12303            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12304                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12305            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12306        }
12307        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12308    }
12309
12310    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12311            String packageOfInterest) {
12312        // IMPORTANT: There are two types of permissions: install and runtime.
12313        // Install time permissions are granted when the app is installed to
12314        // all device users and users added in the future. Runtime permissions
12315        // are granted at runtime explicitly to specific users. Normal and signature
12316        // protected permissions are install time permissions. Dangerous permissions
12317        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12318        // otherwise they are runtime permissions. This function does not manage
12319        // runtime permissions except for the case an app targeting Lollipop MR1
12320        // being upgraded to target a newer SDK, in which case dangerous permissions
12321        // are transformed from install time to runtime ones.
12322
12323        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12324        if (ps == null) {
12325            return;
12326        }
12327
12328        PermissionsState permissionsState = ps.getPermissionsState();
12329        PermissionsState origPermissions = permissionsState;
12330
12331        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12332
12333        boolean runtimePermissionsRevoked = false;
12334        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12335
12336        boolean changedInstallPermission = false;
12337
12338        if (replace) {
12339            ps.installPermissionsFixed = false;
12340            if (!ps.isSharedUser()) {
12341                origPermissions = new PermissionsState(permissionsState);
12342                permissionsState.reset();
12343            } else {
12344                // We need to know only about runtime permission changes since the
12345                // calling code always writes the install permissions state but
12346                // the runtime ones are written only if changed. The only cases of
12347                // changed runtime permissions here are promotion of an install to
12348                // runtime and revocation of a runtime from a shared user.
12349                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12350                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12351                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12352                    runtimePermissionsRevoked = true;
12353                }
12354            }
12355        }
12356
12357        permissionsState.setGlobalGids(mGlobalGids);
12358
12359        final int N = pkg.requestedPermissions.size();
12360        for (int i=0; i<N; i++) {
12361            final String name = pkg.requestedPermissions.get(i);
12362            final BasePermission bp = mSettings.mPermissions.get(name);
12363            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12364                    >= Build.VERSION_CODES.M;
12365
12366            if (DEBUG_INSTALL) {
12367                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12368            }
12369
12370            if (bp == null || bp.packageSetting == null) {
12371                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12372                    if (DEBUG_PERMISSIONS) {
12373                        Slog.i(TAG, "Unknown permission " + name
12374                                + " in package " + pkg.packageName);
12375                    }
12376                }
12377                continue;
12378            }
12379
12380
12381            // Limit ephemeral apps to ephemeral allowed permissions.
12382            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12383                if (DEBUG_PERMISSIONS) {
12384                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12385                            + pkg.packageName);
12386                }
12387                continue;
12388            }
12389
12390            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12391                if (DEBUG_PERMISSIONS) {
12392                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12393                            + pkg.packageName);
12394                }
12395                continue;
12396            }
12397
12398            final String perm = bp.name;
12399            boolean allowedSig = false;
12400            int grant = GRANT_DENIED;
12401
12402            // Keep track of app op permissions.
12403            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12404                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12405                if (pkgs == null) {
12406                    pkgs = new ArraySet<>();
12407                    mAppOpPermissionPackages.put(bp.name, pkgs);
12408                }
12409                pkgs.add(pkg.packageName);
12410            }
12411
12412            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12413            switch (level) {
12414                case PermissionInfo.PROTECTION_NORMAL: {
12415                    // For all apps normal permissions are install time ones.
12416                    grant = GRANT_INSTALL;
12417                } break;
12418
12419                case PermissionInfo.PROTECTION_DANGEROUS: {
12420                    // If a permission review is required for legacy apps we represent
12421                    // their permissions as always granted runtime ones since we need
12422                    // to keep the review required permission flag per user while an
12423                    // install permission's state is shared across all users.
12424                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12425                        // For legacy apps dangerous permissions are install time ones.
12426                        grant = GRANT_INSTALL;
12427                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12428                        // For legacy apps that became modern, install becomes runtime.
12429                        grant = GRANT_UPGRADE;
12430                    } else if (mPromoteSystemApps
12431                            && isSystemApp(ps)
12432                            && mExistingSystemPackages.contains(ps.name)) {
12433                        // For legacy system apps, install becomes runtime.
12434                        // We cannot check hasInstallPermission() for system apps since those
12435                        // permissions were granted implicitly and not persisted pre-M.
12436                        grant = GRANT_UPGRADE;
12437                    } else {
12438                        // For modern apps keep runtime permissions unchanged.
12439                        grant = GRANT_RUNTIME;
12440                    }
12441                } break;
12442
12443                case PermissionInfo.PROTECTION_SIGNATURE: {
12444                    // For all apps signature permissions are install time ones.
12445                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12446                    if (allowedSig) {
12447                        grant = GRANT_INSTALL;
12448                    }
12449                } break;
12450            }
12451
12452            if (DEBUG_PERMISSIONS) {
12453                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12454            }
12455
12456            if (grant != GRANT_DENIED) {
12457                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12458                    // If this is an existing, non-system package, then
12459                    // we can't add any new permissions to it.
12460                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12461                        // Except...  if this is a permission that was added
12462                        // to the platform (note: need to only do this when
12463                        // updating the platform).
12464                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12465                            grant = GRANT_DENIED;
12466                        }
12467                    }
12468                }
12469
12470                switch (grant) {
12471                    case GRANT_INSTALL: {
12472                        // Revoke this as runtime permission to handle the case of
12473                        // a runtime permission being downgraded to an install one.
12474                        // Also in permission review mode we keep dangerous permissions
12475                        // for legacy apps
12476                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12477                            if (origPermissions.getRuntimePermissionState(
12478                                    bp.name, userId) != null) {
12479                                // Revoke the runtime permission and clear the flags.
12480                                origPermissions.revokeRuntimePermission(bp, userId);
12481                                origPermissions.updatePermissionFlags(bp, userId,
12482                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12483                                // If we revoked a permission permission, we have to write.
12484                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12485                                        changedRuntimePermissionUserIds, userId);
12486                            }
12487                        }
12488                        // Grant an install permission.
12489                        if (permissionsState.grantInstallPermission(bp) !=
12490                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12491                            changedInstallPermission = true;
12492                        }
12493                    } break;
12494
12495                    case GRANT_RUNTIME: {
12496                        // Grant previously granted runtime permissions.
12497                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12498                            PermissionState permissionState = origPermissions
12499                                    .getRuntimePermissionState(bp.name, userId);
12500                            int flags = permissionState != null
12501                                    ? permissionState.getFlags() : 0;
12502                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12503                                // Don't propagate the permission in a permission review mode if
12504                                // the former was revoked, i.e. marked to not propagate on upgrade.
12505                                // Note that in a permission review mode install permissions are
12506                                // represented as constantly granted runtime ones since we need to
12507                                // keep a per user state associated with the permission. Also the
12508                                // revoke on upgrade flag is no longer applicable and is reset.
12509                                final boolean revokeOnUpgrade = (flags & PackageManager
12510                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12511                                if (revokeOnUpgrade) {
12512                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12513                                    // Since we changed the flags, we have to write.
12514                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12515                                            changedRuntimePermissionUserIds, userId);
12516                                }
12517                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12518                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12519                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12520                                        // If we cannot put the permission as it was,
12521                                        // we have to write.
12522                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12523                                                changedRuntimePermissionUserIds, userId);
12524                                    }
12525                                }
12526
12527                                // If the app supports runtime permissions no need for a review.
12528                                if (mPermissionReviewRequired
12529                                        && appSupportsRuntimePermissions
12530                                        && (flags & PackageManager
12531                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12532                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12533                                    // Since we changed the flags, we have to write.
12534                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12535                                            changedRuntimePermissionUserIds, userId);
12536                                }
12537                            } else if (mPermissionReviewRequired
12538                                    && !appSupportsRuntimePermissions) {
12539                                // For legacy apps that need a permission review, every new
12540                                // runtime permission is granted but it is pending a review.
12541                                // We also need to review only platform defined runtime
12542                                // permissions as these are the only ones the platform knows
12543                                // how to disable the API to simulate revocation as legacy
12544                                // apps don't expect to run with revoked permissions.
12545                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12546                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12547                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12548                                        // We changed the flags, hence have to write.
12549                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12550                                                changedRuntimePermissionUserIds, userId);
12551                                    }
12552                                }
12553                                if (permissionsState.grantRuntimePermission(bp, userId)
12554                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12555                                    // We changed the permission, hence have to write.
12556                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12557                                            changedRuntimePermissionUserIds, userId);
12558                                }
12559                            }
12560                            // Propagate the permission flags.
12561                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12562                        }
12563                    } break;
12564
12565                    case GRANT_UPGRADE: {
12566                        // Grant runtime permissions for a previously held install permission.
12567                        PermissionState permissionState = origPermissions
12568                                .getInstallPermissionState(bp.name);
12569                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12570
12571                        if (origPermissions.revokeInstallPermission(bp)
12572                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12573                            // We will be transferring the permission flags, so clear them.
12574                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12575                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12576                            changedInstallPermission = true;
12577                        }
12578
12579                        // If the permission is not to be promoted to runtime we ignore it and
12580                        // also its other flags as they are not applicable to install permissions.
12581                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12582                            for (int userId : currentUserIds) {
12583                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12584                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12585                                    // Transfer the permission flags.
12586                                    permissionsState.updatePermissionFlags(bp, userId,
12587                                            flags, flags);
12588                                    // If we granted the permission, we have to write.
12589                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12590                                            changedRuntimePermissionUserIds, userId);
12591                                }
12592                            }
12593                        }
12594                    } break;
12595
12596                    default: {
12597                        if (packageOfInterest == null
12598                                || packageOfInterest.equals(pkg.packageName)) {
12599                            if (DEBUG_PERMISSIONS) {
12600                                Slog.i(TAG, "Not granting permission " + perm
12601                                        + " to package " + pkg.packageName
12602                                        + " because it was previously installed without");
12603                            }
12604                        }
12605                    } break;
12606                }
12607            } else {
12608                if (permissionsState.revokeInstallPermission(bp) !=
12609                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12610                    // Also drop the permission flags.
12611                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12612                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12613                    changedInstallPermission = true;
12614                    Slog.i(TAG, "Un-granting permission " + perm
12615                            + " from package " + pkg.packageName
12616                            + " (protectionLevel=" + bp.protectionLevel
12617                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12618                            + ")");
12619                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12620                    // Don't print warning for app op permissions, since it is fine for them
12621                    // not to be granted, there is a UI for the user to decide.
12622                    if (DEBUG_PERMISSIONS
12623                            && (packageOfInterest == null
12624                                    || packageOfInterest.equals(pkg.packageName))) {
12625                        Slog.i(TAG, "Not granting permission " + perm
12626                                + " to package " + pkg.packageName
12627                                + " (protectionLevel=" + bp.protectionLevel
12628                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12629                                + ")");
12630                    }
12631                }
12632            }
12633        }
12634
12635        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12636                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12637            // This is the first that we have heard about this package, so the
12638            // permissions we have now selected are fixed until explicitly
12639            // changed.
12640            ps.installPermissionsFixed = true;
12641        }
12642
12643        // Persist the runtime permissions state for users with changes. If permissions
12644        // were revoked because no app in the shared user declares them we have to
12645        // write synchronously to avoid losing runtime permissions state.
12646        for (int userId : changedRuntimePermissionUserIds) {
12647            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12648        }
12649    }
12650
12651    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12652        boolean allowed = false;
12653        final int NP = PackageParser.NEW_PERMISSIONS.length;
12654        for (int ip=0; ip<NP; ip++) {
12655            final PackageParser.NewPermissionInfo npi
12656                    = PackageParser.NEW_PERMISSIONS[ip];
12657            if (npi.name.equals(perm)
12658                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12659                allowed = true;
12660                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12661                        + pkg.packageName);
12662                break;
12663            }
12664        }
12665        return allowed;
12666    }
12667
12668    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12669            BasePermission bp, PermissionsState origPermissions) {
12670        boolean privilegedPermission = (bp.protectionLevel
12671                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12672        boolean privappPermissionsDisable =
12673                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12674        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12675        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12676        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12677                && !platformPackage && platformPermission) {
12678            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12679                    .getPrivAppPermissions(pkg.packageName);
12680            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12681            if (!whitelisted) {
12682                Slog.w(TAG, "Privileged permission " + perm + " for package "
12683                        + pkg.packageName + " - not in privapp-permissions whitelist");
12684                // Only report violations for apps on system image
12685                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12686                    if (mPrivappPermissionsViolations == null) {
12687                        mPrivappPermissionsViolations = new ArraySet<>();
12688                    }
12689                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12690                }
12691                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12692                    return false;
12693                }
12694            }
12695        }
12696        boolean allowed = (compareSignatures(
12697                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12698                        == PackageManager.SIGNATURE_MATCH)
12699                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12700                        == PackageManager.SIGNATURE_MATCH);
12701        if (!allowed && privilegedPermission) {
12702            if (isSystemApp(pkg)) {
12703                // For updated system applications, a system permission
12704                // is granted only if it had been defined by the original application.
12705                if (pkg.isUpdatedSystemApp()) {
12706                    final PackageSetting sysPs = mSettings
12707                            .getDisabledSystemPkgLPr(pkg.packageName);
12708                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12709                        // If the original was granted this permission, we take
12710                        // that grant decision as read and propagate it to the
12711                        // update.
12712                        if (sysPs.isPrivileged()) {
12713                            allowed = true;
12714                        }
12715                    } else {
12716                        // The system apk may have been updated with an older
12717                        // version of the one on the data partition, but which
12718                        // granted a new system permission that it didn't have
12719                        // before.  In this case we do want to allow the app to
12720                        // now get the new permission if the ancestral apk is
12721                        // privileged to get it.
12722                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12723                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12724                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12725                                    allowed = true;
12726                                    break;
12727                                }
12728                            }
12729                        }
12730                        // Also if a privileged parent package on the system image or any of
12731                        // its children requested a privileged permission, the updated child
12732                        // packages can also get the permission.
12733                        if (pkg.parentPackage != null) {
12734                            final PackageSetting disabledSysParentPs = mSettings
12735                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12736                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12737                                    && disabledSysParentPs.isPrivileged()) {
12738                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12739                                    allowed = true;
12740                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12741                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12742                                    for (int i = 0; i < count; i++) {
12743                                        PackageParser.Package disabledSysChildPkg =
12744                                                disabledSysParentPs.pkg.childPackages.get(i);
12745                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12746                                                perm)) {
12747                                            allowed = true;
12748                                            break;
12749                                        }
12750                                    }
12751                                }
12752                            }
12753                        }
12754                    }
12755                } else {
12756                    allowed = isPrivilegedApp(pkg);
12757                }
12758            }
12759        }
12760        if (!allowed) {
12761            if (!allowed && (bp.protectionLevel
12762                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12763                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12764                // If this was a previously normal/dangerous permission that got moved
12765                // to a system permission as part of the runtime permission redesign, then
12766                // we still want to blindly grant it to old apps.
12767                allowed = true;
12768            }
12769            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12770                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12771                // If this permission is to be granted to the system installer and
12772                // this app is an installer, then it gets the permission.
12773                allowed = true;
12774            }
12775            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12776                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12777                // If this permission is to be granted to the system verifier and
12778                // this app is a verifier, then it gets the permission.
12779                allowed = true;
12780            }
12781            if (!allowed && (bp.protectionLevel
12782                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12783                    && isSystemApp(pkg)) {
12784                // Any pre-installed system app is allowed to get this permission.
12785                allowed = true;
12786            }
12787            if (!allowed && (bp.protectionLevel
12788                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12789                // For development permissions, a development permission
12790                // is granted only if it was already granted.
12791                allowed = origPermissions.hasInstallPermission(perm);
12792            }
12793            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12794                    && pkg.packageName.equals(mSetupWizardPackage)) {
12795                // If this permission is to be granted to the system setup wizard and
12796                // this app is a setup wizard, then it gets the permission.
12797                allowed = true;
12798            }
12799        }
12800        return allowed;
12801    }
12802
12803    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12804        final int permCount = pkg.requestedPermissions.size();
12805        for (int j = 0; j < permCount; j++) {
12806            String requestedPermission = pkg.requestedPermissions.get(j);
12807            if (permission.equals(requestedPermission)) {
12808                return true;
12809            }
12810        }
12811        return false;
12812    }
12813
12814    final class ActivityIntentResolver
12815            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12816        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12817                boolean defaultOnly, int userId) {
12818            if (!sUserManager.exists(userId)) return null;
12819            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12820            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12821        }
12822
12823        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12824                int userId) {
12825            if (!sUserManager.exists(userId)) return null;
12826            mFlags = flags;
12827            return super.queryIntent(intent, resolvedType,
12828                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12829                    userId);
12830        }
12831
12832        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12833                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12834            if (!sUserManager.exists(userId)) return null;
12835            if (packageActivities == null) {
12836                return null;
12837            }
12838            mFlags = flags;
12839            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12840            final int N = packageActivities.size();
12841            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12842                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12843
12844            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12845            for (int i = 0; i < N; ++i) {
12846                intentFilters = packageActivities.get(i).intents;
12847                if (intentFilters != null && intentFilters.size() > 0) {
12848                    PackageParser.ActivityIntentInfo[] array =
12849                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12850                    intentFilters.toArray(array);
12851                    listCut.add(array);
12852                }
12853            }
12854            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12855        }
12856
12857        /**
12858         * Finds a privileged activity that matches the specified activity names.
12859         */
12860        private PackageParser.Activity findMatchingActivity(
12861                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12862            for (PackageParser.Activity sysActivity : activityList) {
12863                if (sysActivity.info.name.equals(activityInfo.name)) {
12864                    return sysActivity;
12865                }
12866                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12867                    return sysActivity;
12868                }
12869                if (sysActivity.info.targetActivity != null) {
12870                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12871                        return sysActivity;
12872                    }
12873                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12874                        return sysActivity;
12875                    }
12876                }
12877            }
12878            return null;
12879        }
12880
12881        public class IterGenerator<E> {
12882            public Iterator<E> generate(ActivityIntentInfo info) {
12883                return null;
12884            }
12885        }
12886
12887        public class ActionIterGenerator extends IterGenerator<String> {
12888            @Override
12889            public Iterator<String> generate(ActivityIntentInfo info) {
12890                return info.actionsIterator();
12891            }
12892        }
12893
12894        public class CategoriesIterGenerator extends IterGenerator<String> {
12895            @Override
12896            public Iterator<String> generate(ActivityIntentInfo info) {
12897                return info.categoriesIterator();
12898            }
12899        }
12900
12901        public class SchemesIterGenerator extends IterGenerator<String> {
12902            @Override
12903            public Iterator<String> generate(ActivityIntentInfo info) {
12904                return info.schemesIterator();
12905            }
12906        }
12907
12908        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12909            @Override
12910            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12911                return info.authoritiesIterator();
12912            }
12913        }
12914
12915        /**
12916         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12917         * MODIFIED. Do not pass in a list that should not be changed.
12918         */
12919        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12920                IterGenerator<T> generator, Iterator<T> searchIterator) {
12921            // loop through the set of actions; every one must be found in the intent filter
12922            while (searchIterator.hasNext()) {
12923                // we must have at least one filter in the list to consider a match
12924                if (intentList.size() == 0) {
12925                    break;
12926                }
12927
12928                final T searchAction = searchIterator.next();
12929
12930                // loop through the set of intent filters
12931                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12932                while (intentIter.hasNext()) {
12933                    final ActivityIntentInfo intentInfo = intentIter.next();
12934                    boolean selectionFound = false;
12935
12936                    // loop through the intent filter's selection criteria; at least one
12937                    // of them must match the searched criteria
12938                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12939                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12940                        final T intentSelection = intentSelectionIter.next();
12941                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12942                            selectionFound = true;
12943                            break;
12944                        }
12945                    }
12946
12947                    // the selection criteria wasn't found in this filter's set; this filter
12948                    // is not a potential match
12949                    if (!selectionFound) {
12950                        intentIter.remove();
12951                    }
12952                }
12953            }
12954        }
12955
12956        private boolean isProtectedAction(ActivityIntentInfo filter) {
12957            final Iterator<String> actionsIter = filter.actionsIterator();
12958            while (actionsIter != null && actionsIter.hasNext()) {
12959                final String filterAction = actionsIter.next();
12960                if (PROTECTED_ACTIONS.contains(filterAction)) {
12961                    return true;
12962                }
12963            }
12964            return false;
12965        }
12966
12967        /**
12968         * Adjusts the priority of the given intent filter according to policy.
12969         * <p>
12970         * <ul>
12971         * <li>The priority for non privileged applications is capped to '0'</li>
12972         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12973         * <li>The priority for unbundled updates to privileged applications is capped to the
12974         *      priority defined on the system partition</li>
12975         * </ul>
12976         * <p>
12977         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12978         * allowed to obtain any priority on any action.
12979         */
12980        private void adjustPriority(
12981                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12982            // nothing to do; priority is fine as-is
12983            if (intent.getPriority() <= 0) {
12984                return;
12985            }
12986
12987            final ActivityInfo activityInfo = intent.activity.info;
12988            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12989
12990            final boolean privilegedApp =
12991                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12992            if (!privilegedApp) {
12993                // non-privileged applications can never define a priority >0
12994                if (DEBUG_FILTERS) {
12995                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12996                            + " package: " + applicationInfo.packageName
12997                            + " activity: " + intent.activity.className
12998                            + " origPrio: " + intent.getPriority());
12999                }
13000                intent.setPriority(0);
13001                return;
13002            }
13003
13004            if (systemActivities == null) {
13005                // the system package is not disabled; we're parsing the system partition
13006                if (isProtectedAction(intent)) {
13007                    if (mDeferProtectedFilters) {
13008                        // We can't deal with these just yet. No component should ever obtain a
13009                        // >0 priority for a protected actions, with ONE exception -- the setup
13010                        // wizard. The setup wizard, however, cannot be known until we're able to
13011                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13012                        // until all intent filters have been processed. Chicken, meet egg.
13013                        // Let the filter temporarily have a high priority and rectify the
13014                        // priorities after all system packages have been scanned.
13015                        mProtectedFilters.add(intent);
13016                        if (DEBUG_FILTERS) {
13017                            Slog.i(TAG, "Protected action; save for later;"
13018                                    + " package: " + applicationInfo.packageName
13019                                    + " activity: " + intent.activity.className
13020                                    + " origPrio: " + intent.getPriority());
13021                        }
13022                        return;
13023                    } else {
13024                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13025                            Slog.i(TAG, "No setup wizard;"
13026                                + " All protected intents capped to priority 0");
13027                        }
13028                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13029                            if (DEBUG_FILTERS) {
13030                                Slog.i(TAG, "Found setup wizard;"
13031                                    + " allow priority " + intent.getPriority() + ";"
13032                                    + " package: " + intent.activity.info.packageName
13033                                    + " activity: " + intent.activity.className
13034                                    + " priority: " + intent.getPriority());
13035                            }
13036                            // setup wizard gets whatever it wants
13037                            return;
13038                        }
13039                        if (DEBUG_FILTERS) {
13040                            Slog.i(TAG, "Protected action; cap priority to 0;"
13041                                    + " package: " + intent.activity.info.packageName
13042                                    + " activity: " + intent.activity.className
13043                                    + " origPrio: " + intent.getPriority());
13044                        }
13045                        intent.setPriority(0);
13046                        return;
13047                    }
13048                }
13049                // privileged apps on the system image get whatever priority they request
13050                return;
13051            }
13052
13053            // privileged app unbundled update ... try to find the same activity
13054            final PackageParser.Activity foundActivity =
13055                    findMatchingActivity(systemActivities, activityInfo);
13056            if (foundActivity == null) {
13057                // this is a new activity; it cannot obtain >0 priority
13058                if (DEBUG_FILTERS) {
13059                    Slog.i(TAG, "New activity; cap priority to 0;"
13060                            + " package: " + applicationInfo.packageName
13061                            + " activity: " + intent.activity.className
13062                            + " origPrio: " + intent.getPriority());
13063                }
13064                intent.setPriority(0);
13065                return;
13066            }
13067
13068            // found activity, now check for filter equivalence
13069
13070            // a shallow copy is enough; we modify the list, not its contents
13071            final List<ActivityIntentInfo> intentListCopy =
13072                    new ArrayList<>(foundActivity.intents);
13073            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13074
13075            // find matching action subsets
13076            final Iterator<String> actionsIterator = intent.actionsIterator();
13077            if (actionsIterator != null) {
13078                getIntentListSubset(
13079                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13080                if (intentListCopy.size() == 0) {
13081                    // no more intents to match; we're not equivalent
13082                    if (DEBUG_FILTERS) {
13083                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13084                                + " package: " + applicationInfo.packageName
13085                                + " activity: " + intent.activity.className
13086                                + " origPrio: " + intent.getPriority());
13087                    }
13088                    intent.setPriority(0);
13089                    return;
13090                }
13091            }
13092
13093            // find matching category subsets
13094            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13095            if (categoriesIterator != null) {
13096                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13097                        categoriesIterator);
13098                if (intentListCopy.size() == 0) {
13099                    // no more intents to match; we're not equivalent
13100                    if (DEBUG_FILTERS) {
13101                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13102                                + " package: " + applicationInfo.packageName
13103                                + " activity: " + intent.activity.className
13104                                + " origPrio: " + intent.getPriority());
13105                    }
13106                    intent.setPriority(0);
13107                    return;
13108                }
13109            }
13110
13111            // find matching schemes subsets
13112            final Iterator<String> schemesIterator = intent.schemesIterator();
13113            if (schemesIterator != null) {
13114                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13115                        schemesIterator);
13116                if (intentListCopy.size() == 0) {
13117                    // no more intents to match; we're not equivalent
13118                    if (DEBUG_FILTERS) {
13119                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13120                                + " package: " + applicationInfo.packageName
13121                                + " activity: " + intent.activity.className
13122                                + " origPrio: " + intent.getPriority());
13123                    }
13124                    intent.setPriority(0);
13125                    return;
13126                }
13127            }
13128
13129            // find matching authorities subsets
13130            final Iterator<IntentFilter.AuthorityEntry>
13131                    authoritiesIterator = intent.authoritiesIterator();
13132            if (authoritiesIterator != null) {
13133                getIntentListSubset(intentListCopy,
13134                        new AuthoritiesIterGenerator(),
13135                        authoritiesIterator);
13136                if (intentListCopy.size() == 0) {
13137                    // no more intents to match; we're not equivalent
13138                    if (DEBUG_FILTERS) {
13139                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13140                                + " package: " + applicationInfo.packageName
13141                                + " activity: " + intent.activity.className
13142                                + " origPrio: " + intent.getPriority());
13143                    }
13144                    intent.setPriority(0);
13145                    return;
13146                }
13147            }
13148
13149            // we found matching filter(s); app gets the max priority of all intents
13150            int cappedPriority = 0;
13151            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13152                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13153            }
13154            if (intent.getPriority() > cappedPriority) {
13155                if (DEBUG_FILTERS) {
13156                    Slog.i(TAG, "Found matching filter(s);"
13157                            + " cap priority to " + cappedPriority + ";"
13158                            + " package: " + applicationInfo.packageName
13159                            + " activity: " + intent.activity.className
13160                            + " origPrio: " + intent.getPriority());
13161                }
13162                intent.setPriority(cappedPriority);
13163                return;
13164            }
13165            // all this for nothing; the requested priority was <= what was on the system
13166        }
13167
13168        public final void addActivity(PackageParser.Activity a, String type) {
13169            mActivities.put(a.getComponentName(), a);
13170            if (DEBUG_SHOW_INFO)
13171                Log.v(
13172                TAG, "  " + type + " " +
13173                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13174            if (DEBUG_SHOW_INFO)
13175                Log.v(TAG, "    Class=" + a.info.name);
13176            final int NI = a.intents.size();
13177            for (int j=0; j<NI; j++) {
13178                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13179                if ("activity".equals(type)) {
13180                    final PackageSetting ps =
13181                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13182                    final List<PackageParser.Activity> systemActivities =
13183                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13184                    adjustPriority(systemActivities, intent);
13185                }
13186                if (DEBUG_SHOW_INFO) {
13187                    Log.v(TAG, "    IntentFilter:");
13188                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13189                }
13190                if (!intent.debugCheck()) {
13191                    Log.w(TAG, "==> For Activity " + a.info.name);
13192                }
13193                addFilter(intent);
13194            }
13195        }
13196
13197        public final void removeActivity(PackageParser.Activity a, String type) {
13198            mActivities.remove(a.getComponentName());
13199            if (DEBUG_SHOW_INFO) {
13200                Log.v(TAG, "  " + type + " "
13201                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13202                                : a.info.name) + ":");
13203                Log.v(TAG, "    Class=" + a.info.name);
13204            }
13205            final int NI = a.intents.size();
13206            for (int j=0; j<NI; j++) {
13207                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13208                if (DEBUG_SHOW_INFO) {
13209                    Log.v(TAG, "    IntentFilter:");
13210                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13211                }
13212                removeFilter(intent);
13213            }
13214        }
13215
13216        @Override
13217        protected boolean allowFilterResult(
13218                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13219            ActivityInfo filterAi = filter.activity.info;
13220            for (int i=dest.size()-1; i>=0; i--) {
13221                ActivityInfo destAi = dest.get(i).activityInfo;
13222                if (destAi.name == filterAi.name
13223                        && destAi.packageName == filterAi.packageName) {
13224                    return false;
13225                }
13226            }
13227            return true;
13228        }
13229
13230        @Override
13231        protected ActivityIntentInfo[] newArray(int size) {
13232            return new ActivityIntentInfo[size];
13233        }
13234
13235        @Override
13236        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13237            if (!sUserManager.exists(userId)) return true;
13238            PackageParser.Package p = filter.activity.owner;
13239            if (p != null) {
13240                PackageSetting ps = (PackageSetting)p.mExtras;
13241                if (ps != null) {
13242                    // System apps are never considered stopped for purposes of
13243                    // filtering, because there may be no way for the user to
13244                    // actually re-launch them.
13245                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13246                            && ps.getStopped(userId);
13247                }
13248            }
13249            return false;
13250        }
13251
13252        @Override
13253        protected boolean isPackageForFilter(String packageName,
13254                PackageParser.ActivityIntentInfo info) {
13255            return packageName.equals(info.activity.owner.packageName);
13256        }
13257
13258        @Override
13259        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13260                int match, int userId) {
13261            if (!sUserManager.exists(userId)) return null;
13262            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13263                return null;
13264            }
13265            final PackageParser.Activity activity = info.activity;
13266            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13267            if (ps == null) {
13268                return null;
13269            }
13270            final PackageUserState userState = ps.readUserState(userId);
13271            ActivityInfo ai =
13272                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13273            if (ai == null) {
13274                return null;
13275            }
13276            final boolean matchExplicitlyVisibleOnly =
13277                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13278            final boolean matchVisibleToInstantApp =
13279                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13280            final boolean componentVisible =
13281                    matchVisibleToInstantApp
13282                    && info.isVisibleToInstantApp()
13283                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13284            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13285            // throw out filters that aren't visible to ephemeral apps
13286            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13287                return null;
13288            }
13289            // throw out instant app filters if we're not explicitly requesting them
13290            if (!matchInstantApp && userState.instantApp) {
13291                return null;
13292            }
13293            // throw out instant app filters if updates are available; will trigger
13294            // instant app resolution
13295            if (userState.instantApp && ps.isUpdateAvailable()) {
13296                return null;
13297            }
13298            final ResolveInfo res = new ResolveInfo();
13299            res.activityInfo = ai;
13300            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13301                res.filter = info;
13302            }
13303            if (info != null) {
13304                res.handleAllWebDataURI = info.handleAllWebDataURI();
13305            }
13306            res.priority = info.getPriority();
13307            res.preferredOrder = activity.owner.mPreferredOrder;
13308            //System.out.println("Result: " + res.activityInfo.className +
13309            //                   " = " + res.priority);
13310            res.match = match;
13311            res.isDefault = info.hasDefault;
13312            res.labelRes = info.labelRes;
13313            res.nonLocalizedLabel = info.nonLocalizedLabel;
13314            if (userNeedsBadging(userId)) {
13315                res.noResourceId = true;
13316            } else {
13317                res.icon = info.icon;
13318            }
13319            res.iconResourceId = info.icon;
13320            res.system = res.activityInfo.applicationInfo.isSystemApp();
13321            res.isInstantAppAvailable = userState.instantApp;
13322            return res;
13323        }
13324
13325        @Override
13326        protected void sortResults(List<ResolveInfo> results) {
13327            Collections.sort(results, mResolvePrioritySorter);
13328        }
13329
13330        @Override
13331        protected void dumpFilter(PrintWriter out, String prefix,
13332                PackageParser.ActivityIntentInfo filter) {
13333            out.print(prefix); out.print(
13334                    Integer.toHexString(System.identityHashCode(filter.activity)));
13335                    out.print(' ');
13336                    filter.activity.printComponentShortName(out);
13337                    out.print(" filter ");
13338                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13339        }
13340
13341        @Override
13342        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13343            return filter.activity;
13344        }
13345
13346        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13347            PackageParser.Activity activity = (PackageParser.Activity)label;
13348            out.print(prefix); out.print(
13349                    Integer.toHexString(System.identityHashCode(activity)));
13350                    out.print(' ');
13351                    activity.printComponentShortName(out);
13352            if (count > 1) {
13353                out.print(" ("); out.print(count); out.print(" filters)");
13354            }
13355            out.println();
13356        }
13357
13358        // Keys are String (activity class name), values are Activity.
13359        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13360                = new ArrayMap<ComponentName, PackageParser.Activity>();
13361        private int mFlags;
13362    }
13363
13364    private final class ServiceIntentResolver
13365            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13366        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13367                boolean defaultOnly, int userId) {
13368            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13369            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13370        }
13371
13372        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13373                int userId) {
13374            if (!sUserManager.exists(userId)) return null;
13375            mFlags = flags;
13376            return super.queryIntent(intent, resolvedType,
13377                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13378                    userId);
13379        }
13380
13381        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13382                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13383            if (!sUserManager.exists(userId)) return null;
13384            if (packageServices == null) {
13385                return null;
13386            }
13387            mFlags = flags;
13388            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13389            final int N = packageServices.size();
13390            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13391                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13392
13393            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13394            for (int i = 0; i < N; ++i) {
13395                intentFilters = packageServices.get(i).intents;
13396                if (intentFilters != null && intentFilters.size() > 0) {
13397                    PackageParser.ServiceIntentInfo[] array =
13398                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13399                    intentFilters.toArray(array);
13400                    listCut.add(array);
13401                }
13402            }
13403            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13404        }
13405
13406        public final void addService(PackageParser.Service s) {
13407            mServices.put(s.getComponentName(), s);
13408            if (DEBUG_SHOW_INFO) {
13409                Log.v(TAG, "  "
13410                        + (s.info.nonLocalizedLabel != null
13411                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13412                Log.v(TAG, "    Class=" + s.info.name);
13413            }
13414            final int NI = s.intents.size();
13415            int j;
13416            for (j=0; j<NI; j++) {
13417                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13418                if (DEBUG_SHOW_INFO) {
13419                    Log.v(TAG, "    IntentFilter:");
13420                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13421                }
13422                if (!intent.debugCheck()) {
13423                    Log.w(TAG, "==> For Service " + s.info.name);
13424                }
13425                addFilter(intent);
13426            }
13427        }
13428
13429        public final void removeService(PackageParser.Service s) {
13430            mServices.remove(s.getComponentName());
13431            if (DEBUG_SHOW_INFO) {
13432                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13433                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13434                Log.v(TAG, "    Class=" + s.info.name);
13435            }
13436            final int NI = s.intents.size();
13437            int j;
13438            for (j=0; j<NI; j++) {
13439                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13440                if (DEBUG_SHOW_INFO) {
13441                    Log.v(TAG, "    IntentFilter:");
13442                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13443                }
13444                removeFilter(intent);
13445            }
13446        }
13447
13448        @Override
13449        protected boolean allowFilterResult(
13450                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13451            ServiceInfo filterSi = filter.service.info;
13452            for (int i=dest.size()-1; i>=0; i--) {
13453                ServiceInfo destAi = dest.get(i).serviceInfo;
13454                if (destAi.name == filterSi.name
13455                        && destAi.packageName == filterSi.packageName) {
13456                    return false;
13457                }
13458            }
13459            return true;
13460        }
13461
13462        @Override
13463        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13464            return new PackageParser.ServiceIntentInfo[size];
13465        }
13466
13467        @Override
13468        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13469            if (!sUserManager.exists(userId)) return true;
13470            PackageParser.Package p = filter.service.owner;
13471            if (p != null) {
13472                PackageSetting ps = (PackageSetting)p.mExtras;
13473                if (ps != null) {
13474                    // System apps are never considered stopped for purposes of
13475                    // filtering, because there may be no way for the user to
13476                    // actually re-launch them.
13477                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13478                            && ps.getStopped(userId);
13479                }
13480            }
13481            return false;
13482        }
13483
13484        @Override
13485        protected boolean isPackageForFilter(String packageName,
13486                PackageParser.ServiceIntentInfo info) {
13487            return packageName.equals(info.service.owner.packageName);
13488        }
13489
13490        @Override
13491        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13492                int match, int userId) {
13493            if (!sUserManager.exists(userId)) return null;
13494            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13495            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13496                return null;
13497            }
13498            final PackageParser.Service service = info.service;
13499            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13500            if (ps == null) {
13501                return null;
13502            }
13503            final PackageUserState userState = ps.readUserState(userId);
13504            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13505                    userState, userId);
13506            if (si == null) {
13507                return null;
13508            }
13509            final boolean matchVisibleToInstantApp =
13510                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13511            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13512            // throw out filters that aren't visible to ephemeral apps
13513            if (matchVisibleToInstantApp
13514                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13515                return null;
13516            }
13517            // throw out ephemeral filters if we're not explicitly requesting them
13518            if (!isInstantApp && userState.instantApp) {
13519                return null;
13520            }
13521            // throw out instant app filters if updates are available; will trigger
13522            // instant app resolution
13523            if (userState.instantApp && ps.isUpdateAvailable()) {
13524                return null;
13525            }
13526            final ResolveInfo res = new ResolveInfo();
13527            res.serviceInfo = si;
13528            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13529                res.filter = filter;
13530            }
13531            res.priority = info.getPriority();
13532            res.preferredOrder = service.owner.mPreferredOrder;
13533            res.match = match;
13534            res.isDefault = info.hasDefault;
13535            res.labelRes = info.labelRes;
13536            res.nonLocalizedLabel = info.nonLocalizedLabel;
13537            res.icon = info.icon;
13538            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13539            return res;
13540        }
13541
13542        @Override
13543        protected void sortResults(List<ResolveInfo> results) {
13544            Collections.sort(results, mResolvePrioritySorter);
13545        }
13546
13547        @Override
13548        protected void dumpFilter(PrintWriter out, String prefix,
13549                PackageParser.ServiceIntentInfo filter) {
13550            out.print(prefix); out.print(
13551                    Integer.toHexString(System.identityHashCode(filter.service)));
13552                    out.print(' ');
13553                    filter.service.printComponentShortName(out);
13554                    out.print(" filter ");
13555                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13556        }
13557
13558        @Override
13559        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13560            return filter.service;
13561        }
13562
13563        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13564            PackageParser.Service service = (PackageParser.Service)label;
13565            out.print(prefix); out.print(
13566                    Integer.toHexString(System.identityHashCode(service)));
13567                    out.print(' ');
13568                    service.printComponentShortName(out);
13569            if (count > 1) {
13570                out.print(" ("); out.print(count); out.print(" filters)");
13571            }
13572            out.println();
13573        }
13574
13575//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13576//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13577//            final List<ResolveInfo> retList = Lists.newArrayList();
13578//            while (i.hasNext()) {
13579//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13580//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13581//                    retList.add(resolveInfo);
13582//                }
13583//            }
13584//            return retList;
13585//        }
13586
13587        // Keys are String (activity class name), values are Activity.
13588        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13589                = new ArrayMap<ComponentName, PackageParser.Service>();
13590        private int mFlags;
13591    }
13592
13593    private final class ProviderIntentResolver
13594            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13595        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13596                boolean defaultOnly, int userId) {
13597            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13598            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13599        }
13600
13601        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13602                int userId) {
13603            if (!sUserManager.exists(userId))
13604                return null;
13605            mFlags = flags;
13606            return super.queryIntent(intent, resolvedType,
13607                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13608                    userId);
13609        }
13610
13611        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13612                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13613            if (!sUserManager.exists(userId))
13614                return null;
13615            if (packageProviders == null) {
13616                return null;
13617            }
13618            mFlags = flags;
13619            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13620            final int N = packageProviders.size();
13621            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13622                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13623
13624            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13625            for (int i = 0; i < N; ++i) {
13626                intentFilters = packageProviders.get(i).intents;
13627                if (intentFilters != null && intentFilters.size() > 0) {
13628                    PackageParser.ProviderIntentInfo[] array =
13629                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13630                    intentFilters.toArray(array);
13631                    listCut.add(array);
13632                }
13633            }
13634            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13635        }
13636
13637        public final void addProvider(PackageParser.Provider p) {
13638            if (mProviders.containsKey(p.getComponentName())) {
13639                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13640                return;
13641            }
13642
13643            mProviders.put(p.getComponentName(), p);
13644            if (DEBUG_SHOW_INFO) {
13645                Log.v(TAG, "  "
13646                        + (p.info.nonLocalizedLabel != null
13647                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13648                Log.v(TAG, "    Class=" + p.info.name);
13649            }
13650            final int NI = p.intents.size();
13651            int j;
13652            for (j = 0; j < NI; j++) {
13653                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13654                if (DEBUG_SHOW_INFO) {
13655                    Log.v(TAG, "    IntentFilter:");
13656                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13657                }
13658                if (!intent.debugCheck()) {
13659                    Log.w(TAG, "==> For Provider " + p.info.name);
13660                }
13661                addFilter(intent);
13662            }
13663        }
13664
13665        public final void removeProvider(PackageParser.Provider p) {
13666            mProviders.remove(p.getComponentName());
13667            if (DEBUG_SHOW_INFO) {
13668                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13669                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13670                Log.v(TAG, "    Class=" + p.info.name);
13671            }
13672            final int NI = p.intents.size();
13673            int j;
13674            for (j = 0; j < NI; j++) {
13675                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13676                if (DEBUG_SHOW_INFO) {
13677                    Log.v(TAG, "    IntentFilter:");
13678                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13679                }
13680                removeFilter(intent);
13681            }
13682        }
13683
13684        @Override
13685        protected boolean allowFilterResult(
13686                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13687            ProviderInfo filterPi = filter.provider.info;
13688            for (int i = dest.size() - 1; i >= 0; i--) {
13689                ProviderInfo destPi = dest.get(i).providerInfo;
13690                if (destPi.name == filterPi.name
13691                        && destPi.packageName == filterPi.packageName) {
13692                    return false;
13693                }
13694            }
13695            return true;
13696        }
13697
13698        @Override
13699        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13700            return new PackageParser.ProviderIntentInfo[size];
13701        }
13702
13703        @Override
13704        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13705            if (!sUserManager.exists(userId))
13706                return true;
13707            PackageParser.Package p = filter.provider.owner;
13708            if (p != null) {
13709                PackageSetting ps = (PackageSetting) p.mExtras;
13710                if (ps != null) {
13711                    // System apps are never considered stopped for purposes of
13712                    // filtering, because there may be no way for the user to
13713                    // actually re-launch them.
13714                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13715                            && ps.getStopped(userId);
13716                }
13717            }
13718            return false;
13719        }
13720
13721        @Override
13722        protected boolean isPackageForFilter(String packageName,
13723                PackageParser.ProviderIntentInfo info) {
13724            return packageName.equals(info.provider.owner.packageName);
13725        }
13726
13727        @Override
13728        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13729                int match, int userId) {
13730            if (!sUserManager.exists(userId))
13731                return null;
13732            final PackageParser.ProviderIntentInfo info = filter;
13733            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13734                return null;
13735            }
13736            final PackageParser.Provider provider = info.provider;
13737            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13738            if (ps == null) {
13739                return null;
13740            }
13741            final PackageUserState userState = ps.readUserState(userId);
13742            final boolean matchVisibleToInstantApp =
13743                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13744            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13745            // throw out filters that aren't visible to instant applications
13746            if (matchVisibleToInstantApp
13747                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13748                return null;
13749            }
13750            // throw out instant application filters if we're not explicitly requesting them
13751            if (!isInstantApp && userState.instantApp) {
13752                return null;
13753            }
13754            // throw out instant application filters if updates are available; will trigger
13755            // instant application resolution
13756            if (userState.instantApp && ps.isUpdateAvailable()) {
13757                return null;
13758            }
13759            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13760                    userState, userId);
13761            if (pi == null) {
13762                return null;
13763            }
13764            final ResolveInfo res = new ResolveInfo();
13765            res.providerInfo = pi;
13766            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13767                res.filter = filter;
13768            }
13769            res.priority = info.getPriority();
13770            res.preferredOrder = provider.owner.mPreferredOrder;
13771            res.match = match;
13772            res.isDefault = info.hasDefault;
13773            res.labelRes = info.labelRes;
13774            res.nonLocalizedLabel = info.nonLocalizedLabel;
13775            res.icon = info.icon;
13776            res.system = res.providerInfo.applicationInfo.isSystemApp();
13777            return res;
13778        }
13779
13780        @Override
13781        protected void sortResults(List<ResolveInfo> results) {
13782            Collections.sort(results, mResolvePrioritySorter);
13783        }
13784
13785        @Override
13786        protected void dumpFilter(PrintWriter out, String prefix,
13787                PackageParser.ProviderIntentInfo filter) {
13788            out.print(prefix);
13789            out.print(
13790                    Integer.toHexString(System.identityHashCode(filter.provider)));
13791            out.print(' ');
13792            filter.provider.printComponentShortName(out);
13793            out.print(" filter ");
13794            out.println(Integer.toHexString(System.identityHashCode(filter)));
13795        }
13796
13797        @Override
13798        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13799            return filter.provider;
13800        }
13801
13802        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13803            PackageParser.Provider provider = (PackageParser.Provider)label;
13804            out.print(prefix); out.print(
13805                    Integer.toHexString(System.identityHashCode(provider)));
13806                    out.print(' ');
13807                    provider.printComponentShortName(out);
13808            if (count > 1) {
13809                out.print(" ("); out.print(count); out.print(" filters)");
13810            }
13811            out.println();
13812        }
13813
13814        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13815                = new ArrayMap<ComponentName, PackageParser.Provider>();
13816        private int mFlags;
13817    }
13818
13819    static final class EphemeralIntentResolver
13820            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13821        /**
13822         * The result that has the highest defined order. Ordering applies on a
13823         * per-package basis. Mapping is from package name to Pair of order and
13824         * EphemeralResolveInfo.
13825         * <p>
13826         * NOTE: This is implemented as a field variable for convenience and efficiency.
13827         * By having a field variable, we're able to track filter ordering as soon as
13828         * a non-zero order is defined. Otherwise, multiple loops across the result set
13829         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13830         * this needs to be contained entirely within {@link #filterResults}.
13831         */
13832        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13833
13834        @Override
13835        protected AuxiliaryResolveInfo[] newArray(int size) {
13836            return new AuxiliaryResolveInfo[size];
13837        }
13838
13839        @Override
13840        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13841            return true;
13842        }
13843
13844        @Override
13845        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13846                int userId) {
13847            if (!sUserManager.exists(userId)) {
13848                return null;
13849            }
13850            final String packageName = responseObj.resolveInfo.getPackageName();
13851            final Integer order = responseObj.getOrder();
13852            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13853                    mOrderResult.get(packageName);
13854            // ordering is enabled and this item's order isn't high enough
13855            if (lastOrderResult != null && lastOrderResult.first >= order) {
13856                return null;
13857            }
13858            final InstantAppResolveInfo res = responseObj.resolveInfo;
13859            if (order > 0) {
13860                // non-zero order, enable ordering
13861                mOrderResult.put(packageName, new Pair<>(order, res));
13862            }
13863            return responseObj;
13864        }
13865
13866        @Override
13867        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13868            // only do work if ordering is enabled [most of the time it won't be]
13869            if (mOrderResult.size() == 0) {
13870                return;
13871            }
13872            int resultSize = results.size();
13873            for (int i = 0; i < resultSize; i++) {
13874                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13875                final String packageName = info.getPackageName();
13876                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13877                if (savedInfo == null) {
13878                    // package doesn't having ordering
13879                    continue;
13880                }
13881                if (savedInfo.second == info) {
13882                    // circled back to the highest ordered item; remove from order list
13883                    mOrderResult.remove(savedInfo);
13884                    if (mOrderResult.size() == 0) {
13885                        // no more ordered items
13886                        break;
13887                    }
13888                    continue;
13889                }
13890                // item has a worse order, remove it from the result list
13891                results.remove(i);
13892                resultSize--;
13893                i--;
13894            }
13895        }
13896    }
13897
13898    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13899            new Comparator<ResolveInfo>() {
13900        public int compare(ResolveInfo r1, ResolveInfo r2) {
13901            int v1 = r1.priority;
13902            int v2 = r2.priority;
13903            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13904            if (v1 != v2) {
13905                return (v1 > v2) ? -1 : 1;
13906            }
13907            v1 = r1.preferredOrder;
13908            v2 = r2.preferredOrder;
13909            if (v1 != v2) {
13910                return (v1 > v2) ? -1 : 1;
13911            }
13912            if (r1.isDefault != r2.isDefault) {
13913                return r1.isDefault ? -1 : 1;
13914            }
13915            v1 = r1.match;
13916            v2 = r2.match;
13917            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13918            if (v1 != v2) {
13919                return (v1 > v2) ? -1 : 1;
13920            }
13921            if (r1.system != r2.system) {
13922                return r1.system ? -1 : 1;
13923            }
13924            if (r1.activityInfo != null) {
13925                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13926            }
13927            if (r1.serviceInfo != null) {
13928                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13929            }
13930            if (r1.providerInfo != null) {
13931                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13932            }
13933            return 0;
13934        }
13935    };
13936
13937    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13938            new Comparator<ProviderInfo>() {
13939        public int compare(ProviderInfo p1, ProviderInfo p2) {
13940            final int v1 = p1.initOrder;
13941            final int v2 = p2.initOrder;
13942            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13943        }
13944    };
13945
13946    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13947            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13948            final int[] userIds) {
13949        mHandler.post(new Runnable() {
13950            @Override
13951            public void run() {
13952                try {
13953                    final IActivityManager am = ActivityManager.getService();
13954                    if (am == null) return;
13955                    final int[] resolvedUserIds;
13956                    if (userIds == null) {
13957                        resolvedUserIds = am.getRunningUserIds();
13958                    } else {
13959                        resolvedUserIds = userIds;
13960                    }
13961                    for (int id : resolvedUserIds) {
13962                        final Intent intent = new Intent(action,
13963                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13964                        if (extras != null) {
13965                            intent.putExtras(extras);
13966                        }
13967                        if (targetPkg != null) {
13968                            intent.setPackage(targetPkg);
13969                        }
13970                        // Modify the UID when posting to other users
13971                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13972                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13973                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13974                            intent.putExtra(Intent.EXTRA_UID, uid);
13975                        }
13976                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13977                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13978                        if (DEBUG_BROADCASTS) {
13979                            RuntimeException here = new RuntimeException("here");
13980                            here.fillInStackTrace();
13981                            Slog.d(TAG, "Sending to user " + id + ": "
13982                                    + intent.toShortString(false, true, false, false)
13983                                    + " " + intent.getExtras(), here);
13984                        }
13985                        am.broadcastIntent(null, intent, null, finishedReceiver,
13986                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13987                                null, finishedReceiver != null, false, id);
13988                    }
13989                } catch (RemoteException ex) {
13990                }
13991            }
13992        });
13993    }
13994
13995    /**
13996     * Check if the external storage media is available. This is true if there
13997     * is a mounted external storage medium or if the external storage is
13998     * emulated.
13999     */
14000    private boolean isExternalMediaAvailable() {
14001        return mMediaMounted || Environment.isExternalStorageEmulated();
14002    }
14003
14004    @Override
14005    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14006        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14007            return null;
14008        }
14009        // writer
14010        synchronized (mPackages) {
14011            if (!isExternalMediaAvailable()) {
14012                // If the external storage is no longer mounted at this point,
14013                // the caller may not have been able to delete all of this
14014                // packages files and can not delete any more.  Bail.
14015                return null;
14016            }
14017            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14018            if (lastPackage != null) {
14019                pkgs.remove(lastPackage);
14020            }
14021            if (pkgs.size() > 0) {
14022                return pkgs.get(0);
14023            }
14024        }
14025        return null;
14026    }
14027
14028    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14029        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14030                userId, andCode ? 1 : 0, packageName);
14031        if (mSystemReady) {
14032            msg.sendToTarget();
14033        } else {
14034            if (mPostSystemReadyMessages == null) {
14035                mPostSystemReadyMessages = new ArrayList<>();
14036            }
14037            mPostSystemReadyMessages.add(msg);
14038        }
14039    }
14040
14041    void startCleaningPackages() {
14042        // reader
14043        if (!isExternalMediaAvailable()) {
14044            return;
14045        }
14046        synchronized (mPackages) {
14047            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14048                return;
14049            }
14050        }
14051        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14052        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14053        IActivityManager am = ActivityManager.getService();
14054        if (am != null) {
14055            int dcsUid = -1;
14056            synchronized (mPackages) {
14057                if (!mDefaultContainerWhitelisted) {
14058                    mDefaultContainerWhitelisted = true;
14059                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14060                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14061                }
14062            }
14063            try {
14064                if (dcsUid > 0) {
14065                    am.backgroundWhitelistUid(dcsUid);
14066                }
14067                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14068                        UserHandle.USER_SYSTEM);
14069            } catch (RemoteException e) {
14070            }
14071        }
14072    }
14073
14074    @Override
14075    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14076            int installFlags, String installerPackageName, int userId) {
14077        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14078
14079        final int callingUid = Binder.getCallingUid();
14080        enforceCrossUserPermission(callingUid, userId,
14081                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14082
14083        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14084            try {
14085                if (observer != null) {
14086                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14087                }
14088            } catch (RemoteException re) {
14089            }
14090            return;
14091        }
14092
14093        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14094            installFlags |= PackageManager.INSTALL_FROM_ADB;
14095
14096        } else {
14097            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14098            // about installerPackageName.
14099
14100            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14101            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14102        }
14103
14104        UserHandle user;
14105        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14106            user = UserHandle.ALL;
14107        } else {
14108            user = new UserHandle(userId);
14109        }
14110
14111        // Only system components can circumvent runtime permissions when installing.
14112        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14113                && mContext.checkCallingOrSelfPermission(Manifest.permission
14114                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14115            throw new SecurityException("You need the "
14116                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14117                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14118        }
14119
14120        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14121                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14122            throw new IllegalArgumentException(
14123                    "New installs into ASEC containers no longer supported");
14124        }
14125
14126        final File originFile = new File(originPath);
14127        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14128
14129        final Message msg = mHandler.obtainMessage(INIT_COPY);
14130        final VerificationInfo verificationInfo = new VerificationInfo(
14131                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14132        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14133                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14134                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14135                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14136        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14137        msg.obj = params;
14138
14139        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14140                System.identityHashCode(msg.obj));
14141        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14142                System.identityHashCode(msg.obj));
14143
14144        mHandler.sendMessage(msg);
14145    }
14146
14147
14148    /**
14149     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14150     * it is acting on behalf on an enterprise or the user).
14151     *
14152     * Note that the ordering of the conditionals in this method is important. The checks we perform
14153     * are as follows, in this order:
14154     *
14155     * 1) If the install is being performed by a system app, we can trust the app to have set the
14156     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14157     *    what it is.
14158     * 2) If the install is being performed by a device or profile owner app, the install reason
14159     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14160     *    set the install reason correctly. If the app targets an older SDK version where install
14161     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14162     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14163     * 3) In all other cases, the install is being performed by a regular app that is neither part
14164     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14165     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14166     *    set to enterprise policy and if so, change it to unknown instead.
14167     */
14168    private int fixUpInstallReason(String installerPackageName, int installerUid,
14169            int installReason) {
14170        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14171                == PERMISSION_GRANTED) {
14172            // If the install is being performed by a system app, we trust that app to have set the
14173            // install reason correctly.
14174            return installReason;
14175        }
14176
14177        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14178            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14179        if (dpm != null) {
14180            ComponentName owner = null;
14181            try {
14182                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14183                if (owner == null) {
14184                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14185                }
14186            } catch (RemoteException e) {
14187            }
14188            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14189                // If the install is being performed by a device or profile owner, the install
14190                // reason should be enterprise policy.
14191                return PackageManager.INSTALL_REASON_POLICY;
14192            }
14193        }
14194
14195        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14196            // If the install is being performed by a regular app (i.e. neither system app nor
14197            // device or profile owner), we have no reason to believe that the app is acting on
14198            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14199            // change it to unknown instead.
14200            return PackageManager.INSTALL_REASON_UNKNOWN;
14201        }
14202
14203        // If the install is being performed by a regular app and the install reason was set to any
14204        // value but enterprise policy, leave the install reason unchanged.
14205        return installReason;
14206    }
14207
14208    void installStage(String packageName, File stagedDir, String stagedCid,
14209            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14210            String installerPackageName, int installerUid, UserHandle user,
14211            Certificate[][] certificates) {
14212        if (DEBUG_EPHEMERAL) {
14213            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14214                Slog.d(TAG, "Ephemeral install of " + packageName);
14215            }
14216        }
14217        final VerificationInfo verificationInfo = new VerificationInfo(
14218                sessionParams.originatingUri, sessionParams.referrerUri,
14219                sessionParams.originatingUid, installerUid);
14220
14221        final OriginInfo origin;
14222        if (stagedDir != null) {
14223            origin = OriginInfo.fromStagedFile(stagedDir);
14224        } else {
14225            origin = OriginInfo.fromStagedContainer(stagedCid);
14226        }
14227
14228        final Message msg = mHandler.obtainMessage(INIT_COPY);
14229        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14230                sessionParams.installReason);
14231        final InstallParams params = new InstallParams(origin, null, observer,
14232                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14233                verificationInfo, user, sessionParams.abiOverride,
14234                sessionParams.grantedRuntimePermissions, certificates, installReason);
14235        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14236        msg.obj = params;
14237
14238        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14239                System.identityHashCode(msg.obj));
14240        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14241                System.identityHashCode(msg.obj));
14242
14243        mHandler.sendMessage(msg);
14244    }
14245
14246    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14247            int userId) {
14248        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14249        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14250
14251        // Send a session commit broadcast
14252        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14253        info.installReason = pkgSetting.getInstallReason(userId);
14254        info.appPackageName = packageName;
14255        sendSessionCommitBroadcast(info, userId);
14256    }
14257
14258    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14259        if (ArrayUtils.isEmpty(userIds)) {
14260            return;
14261        }
14262        Bundle extras = new Bundle(1);
14263        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14264        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14265
14266        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14267                packageName, extras, 0, null, null, userIds);
14268        if (isSystem) {
14269            mHandler.post(() -> {
14270                        for (int userId : userIds) {
14271                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14272                        }
14273                    }
14274            );
14275        }
14276    }
14277
14278    /**
14279     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14280     * automatically without needing an explicit launch.
14281     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14282     */
14283    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14284        // If user is not running, the app didn't miss any broadcast
14285        if (!mUserManagerInternal.isUserRunning(userId)) {
14286            return;
14287        }
14288        final IActivityManager am = ActivityManager.getService();
14289        try {
14290            // Deliver LOCKED_BOOT_COMPLETED first
14291            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14292                    .setPackage(packageName);
14293            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14294            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14295                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14296
14297            // Deliver BOOT_COMPLETED only if user is unlocked
14298            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14299                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14300                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14301                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14302            }
14303        } catch (RemoteException e) {
14304            throw e.rethrowFromSystemServer();
14305        }
14306    }
14307
14308    @Override
14309    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14310            int userId) {
14311        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14312        PackageSetting pkgSetting;
14313        final int callingUid = Binder.getCallingUid();
14314        enforceCrossUserPermission(callingUid, userId,
14315                true /* requireFullPermission */, true /* checkShell */,
14316                "setApplicationHiddenSetting for user " + userId);
14317
14318        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14319            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14320            return false;
14321        }
14322
14323        long callingId = Binder.clearCallingIdentity();
14324        try {
14325            boolean sendAdded = false;
14326            boolean sendRemoved = false;
14327            // writer
14328            synchronized (mPackages) {
14329                pkgSetting = mSettings.mPackages.get(packageName);
14330                if (pkgSetting == null) {
14331                    return false;
14332                }
14333                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14334                    return false;
14335                }
14336                // Do not allow "android" is being disabled
14337                if ("android".equals(packageName)) {
14338                    Slog.w(TAG, "Cannot hide package: android");
14339                    return false;
14340                }
14341                // Cannot hide static shared libs as they are considered
14342                // a part of the using app (emulating static linking). Also
14343                // static libs are installed always on internal storage.
14344                PackageParser.Package pkg = mPackages.get(packageName);
14345                if (pkg != null && pkg.staticSharedLibName != null) {
14346                    Slog.w(TAG, "Cannot hide package: " + packageName
14347                            + " providing static shared library: "
14348                            + pkg.staticSharedLibName);
14349                    return false;
14350                }
14351                // Only allow protected packages to hide themselves.
14352                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14353                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14354                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14355                    return false;
14356                }
14357
14358                if (pkgSetting.getHidden(userId) != hidden) {
14359                    pkgSetting.setHidden(hidden, userId);
14360                    mSettings.writePackageRestrictionsLPr(userId);
14361                    if (hidden) {
14362                        sendRemoved = true;
14363                    } else {
14364                        sendAdded = true;
14365                    }
14366                }
14367            }
14368            if (sendAdded) {
14369                sendPackageAddedForUser(packageName, pkgSetting, userId);
14370                return true;
14371            }
14372            if (sendRemoved) {
14373                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14374                        "hiding pkg");
14375                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14376                return true;
14377            }
14378        } finally {
14379            Binder.restoreCallingIdentity(callingId);
14380        }
14381        return false;
14382    }
14383
14384    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14385            int userId) {
14386        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14387        info.removedPackage = packageName;
14388        info.installerPackageName = pkgSetting.installerPackageName;
14389        info.removedUsers = new int[] {userId};
14390        info.broadcastUsers = new int[] {userId};
14391        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14392        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14393    }
14394
14395    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14396        if (pkgList.length > 0) {
14397            Bundle extras = new Bundle(1);
14398            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14399
14400            sendPackageBroadcast(
14401                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14402                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14403                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14404                    new int[] {userId});
14405        }
14406    }
14407
14408    /**
14409     * Returns true if application is not found or there was an error. Otherwise it returns
14410     * the hidden state of the package for the given user.
14411     */
14412    @Override
14413    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14414        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14415        final int callingUid = Binder.getCallingUid();
14416        enforceCrossUserPermission(callingUid, userId,
14417                true /* requireFullPermission */, false /* checkShell */,
14418                "getApplicationHidden for user " + userId);
14419        PackageSetting ps;
14420        long callingId = Binder.clearCallingIdentity();
14421        try {
14422            // writer
14423            synchronized (mPackages) {
14424                ps = mSettings.mPackages.get(packageName);
14425                if (ps == null) {
14426                    return true;
14427                }
14428                if (filterAppAccessLPr(ps, callingUid, userId)) {
14429                    return true;
14430                }
14431                return ps.getHidden(userId);
14432            }
14433        } finally {
14434            Binder.restoreCallingIdentity(callingId);
14435        }
14436    }
14437
14438    /**
14439     * @hide
14440     */
14441    @Override
14442    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14443            int installReason) {
14444        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14445                null);
14446        PackageSetting pkgSetting;
14447        final int callingUid = Binder.getCallingUid();
14448        enforceCrossUserPermission(callingUid, userId,
14449                true /* requireFullPermission */, true /* checkShell */,
14450                "installExistingPackage for user " + userId);
14451        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14452            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14453        }
14454
14455        long callingId = Binder.clearCallingIdentity();
14456        try {
14457            boolean installed = false;
14458            final boolean instantApp =
14459                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14460            final boolean fullApp =
14461                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14462
14463            // writer
14464            synchronized (mPackages) {
14465                pkgSetting = mSettings.mPackages.get(packageName);
14466                if (pkgSetting == null) {
14467                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14468                }
14469                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14470                    // only allow the existing package to be used if it's installed as a full
14471                    // application for at least one user
14472                    boolean installAllowed = false;
14473                    for (int checkUserId : sUserManager.getUserIds()) {
14474                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14475                        if (installAllowed) {
14476                            break;
14477                        }
14478                    }
14479                    if (!installAllowed) {
14480                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14481                    }
14482                }
14483                if (!pkgSetting.getInstalled(userId)) {
14484                    pkgSetting.setInstalled(true, userId);
14485                    pkgSetting.setHidden(false, userId);
14486                    pkgSetting.setInstallReason(installReason, userId);
14487                    mSettings.writePackageRestrictionsLPr(userId);
14488                    mSettings.writeKernelMappingLPr(pkgSetting);
14489                    installed = true;
14490                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14491                    // upgrade app from instant to full; we don't allow app downgrade
14492                    installed = true;
14493                }
14494                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14495            }
14496
14497            if (installed) {
14498                if (pkgSetting.pkg != null) {
14499                    synchronized (mInstallLock) {
14500                        // We don't need to freeze for a brand new install
14501                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14502                    }
14503                }
14504                sendPackageAddedForUser(packageName, pkgSetting, userId);
14505                synchronized (mPackages) {
14506                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14507                }
14508            }
14509        } finally {
14510            Binder.restoreCallingIdentity(callingId);
14511        }
14512
14513        return PackageManager.INSTALL_SUCCEEDED;
14514    }
14515
14516    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14517            boolean instantApp, boolean fullApp) {
14518        // no state specified; do nothing
14519        if (!instantApp && !fullApp) {
14520            return;
14521        }
14522        if (userId != UserHandle.USER_ALL) {
14523            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14524                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14525            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14526                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14527            }
14528        } else {
14529            for (int currentUserId : sUserManager.getUserIds()) {
14530                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14531                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14532                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14533                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14534                }
14535            }
14536        }
14537    }
14538
14539    boolean isUserRestricted(int userId, String restrictionKey) {
14540        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14541        if (restrictions.getBoolean(restrictionKey, false)) {
14542            Log.w(TAG, "User is restricted: " + restrictionKey);
14543            return true;
14544        }
14545        return false;
14546    }
14547
14548    @Override
14549    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14550            int userId) {
14551        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14552        final int callingUid = Binder.getCallingUid();
14553        enforceCrossUserPermission(callingUid, userId,
14554                true /* requireFullPermission */, true /* checkShell */,
14555                "setPackagesSuspended for user " + userId);
14556
14557        if (ArrayUtils.isEmpty(packageNames)) {
14558            return packageNames;
14559        }
14560
14561        // List of package names for whom the suspended state has changed.
14562        List<String> changedPackages = new ArrayList<>(packageNames.length);
14563        // List of package names for whom the suspended state is not set as requested in this
14564        // method.
14565        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14566        long callingId = Binder.clearCallingIdentity();
14567        try {
14568            for (int i = 0; i < packageNames.length; i++) {
14569                String packageName = packageNames[i];
14570                boolean changed = false;
14571                final int appId;
14572                synchronized (mPackages) {
14573                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14574                    if (pkgSetting == null
14575                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14576                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14577                                + "\". Skipping suspending/un-suspending.");
14578                        unactionedPackages.add(packageName);
14579                        continue;
14580                    }
14581                    appId = pkgSetting.appId;
14582                    if (pkgSetting.getSuspended(userId) != suspended) {
14583                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14584                            unactionedPackages.add(packageName);
14585                            continue;
14586                        }
14587                        pkgSetting.setSuspended(suspended, userId);
14588                        mSettings.writePackageRestrictionsLPr(userId);
14589                        changed = true;
14590                        changedPackages.add(packageName);
14591                    }
14592                }
14593
14594                if (changed && suspended) {
14595                    killApplication(packageName, UserHandle.getUid(userId, appId),
14596                            "suspending package");
14597                }
14598            }
14599        } finally {
14600            Binder.restoreCallingIdentity(callingId);
14601        }
14602
14603        if (!changedPackages.isEmpty()) {
14604            sendPackagesSuspendedForUser(changedPackages.toArray(
14605                    new String[changedPackages.size()]), userId, suspended);
14606        }
14607
14608        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14609    }
14610
14611    @Override
14612    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14613        final int callingUid = Binder.getCallingUid();
14614        enforceCrossUserPermission(callingUid, userId,
14615                true /* requireFullPermission */, false /* checkShell */,
14616                "isPackageSuspendedForUser for user " + userId);
14617        synchronized (mPackages) {
14618            final PackageSetting ps = mSettings.mPackages.get(packageName);
14619            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14620                throw new IllegalArgumentException("Unknown target package: " + packageName);
14621            }
14622            return ps.getSuspended(userId);
14623        }
14624    }
14625
14626    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14627        if (isPackageDeviceAdmin(packageName, userId)) {
14628            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14629                    + "\": has an active device admin");
14630            return false;
14631        }
14632
14633        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14634        if (packageName.equals(activeLauncherPackageName)) {
14635            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14636                    + "\": contains the active launcher");
14637            return false;
14638        }
14639
14640        if (packageName.equals(mRequiredInstallerPackage)) {
14641            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14642                    + "\": required for package installation");
14643            return false;
14644        }
14645
14646        if (packageName.equals(mRequiredUninstallerPackage)) {
14647            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14648                    + "\": required for package uninstallation");
14649            return false;
14650        }
14651
14652        if (packageName.equals(mRequiredVerifierPackage)) {
14653            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14654                    + "\": required for package verification");
14655            return false;
14656        }
14657
14658        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14659            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14660                    + "\": is the default dialer");
14661            return false;
14662        }
14663
14664        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14665            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14666                    + "\": protected package");
14667            return false;
14668        }
14669
14670        // Cannot suspend static shared libs as they are considered
14671        // a part of the using app (emulating static linking). Also
14672        // static libs are installed always on internal storage.
14673        PackageParser.Package pkg = mPackages.get(packageName);
14674        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14675            Slog.w(TAG, "Cannot suspend package: " + packageName
14676                    + " providing static shared library: "
14677                    + pkg.staticSharedLibName);
14678            return false;
14679        }
14680
14681        return true;
14682    }
14683
14684    private String getActiveLauncherPackageName(int userId) {
14685        Intent intent = new Intent(Intent.ACTION_MAIN);
14686        intent.addCategory(Intent.CATEGORY_HOME);
14687        ResolveInfo resolveInfo = resolveIntent(
14688                intent,
14689                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14690                PackageManager.MATCH_DEFAULT_ONLY,
14691                userId);
14692
14693        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14694    }
14695
14696    private String getDefaultDialerPackageName(int userId) {
14697        synchronized (mPackages) {
14698            return mSettings.getDefaultDialerPackageNameLPw(userId);
14699        }
14700    }
14701
14702    @Override
14703    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14704        mContext.enforceCallingOrSelfPermission(
14705                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14706                "Only package verification agents can verify applications");
14707
14708        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14709        final PackageVerificationResponse response = new PackageVerificationResponse(
14710                verificationCode, Binder.getCallingUid());
14711        msg.arg1 = id;
14712        msg.obj = response;
14713        mHandler.sendMessage(msg);
14714    }
14715
14716    @Override
14717    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14718            long millisecondsToDelay) {
14719        mContext.enforceCallingOrSelfPermission(
14720                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14721                "Only package verification agents can extend verification timeouts");
14722
14723        final PackageVerificationState state = mPendingVerification.get(id);
14724        final PackageVerificationResponse response = new PackageVerificationResponse(
14725                verificationCodeAtTimeout, Binder.getCallingUid());
14726
14727        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14728            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14729        }
14730        if (millisecondsToDelay < 0) {
14731            millisecondsToDelay = 0;
14732        }
14733        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14734                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14735            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14736        }
14737
14738        if ((state != null) && !state.timeoutExtended()) {
14739            state.extendTimeout();
14740
14741            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14742            msg.arg1 = id;
14743            msg.obj = response;
14744            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14745        }
14746    }
14747
14748    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14749            int verificationCode, UserHandle user) {
14750        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14751        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14752        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14753        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14754        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14755
14756        mContext.sendBroadcastAsUser(intent, user,
14757                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14758    }
14759
14760    private ComponentName matchComponentForVerifier(String packageName,
14761            List<ResolveInfo> receivers) {
14762        ActivityInfo targetReceiver = null;
14763
14764        final int NR = receivers.size();
14765        for (int i = 0; i < NR; i++) {
14766            final ResolveInfo info = receivers.get(i);
14767            if (info.activityInfo == null) {
14768                continue;
14769            }
14770
14771            if (packageName.equals(info.activityInfo.packageName)) {
14772                targetReceiver = info.activityInfo;
14773                break;
14774            }
14775        }
14776
14777        if (targetReceiver == null) {
14778            return null;
14779        }
14780
14781        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14782    }
14783
14784    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14785            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14786        if (pkgInfo.verifiers.length == 0) {
14787            return null;
14788        }
14789
14790        final int N = pkgInfo.verifiers.length;
14791        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14792        for (int i = 0; i < N; i++) {
14793            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14794
14795            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14796                    receivers);
14797            if (comp == null) {
14798                continue;
14799            }
14800
14801            final int verifierUid = getUidForVerifier(verifierInfo);
14802            if (verifierUid == -1) {
14803                continue;
14804            }
14805
14806            if (DEBUG_VERIFY) {
14807                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14808                        + " with the correct signature");
14809            }
14810            sufficientVerifiers.add(comp);
14811            verificationState.addSufficientVerifier(verifierUid);
14812        }
14813
14814        return sufficientVerifiers;
14815    }
14816
14817    private int getUidForVerifier(VerifierInfo verifierInfo) {
14818        synchronized (mPackages) {
14819            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14820            if (pkg == null) {
14821                return -1;
14822            } else if (pkg.mSignatures.length != 1) {
14823                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14824                        + " has more than one signature; ignoring");
14825                return -1;
14826            }
14827
14828            /*
14829             * If the public key of the package's signature does not match
14830             * our expected public key, then this is a different package and
14831             * we should skip.
14832             */
14833
14834            final byte[] expectedPublicKey;
14835            try {
14836                final Signature verifierSig = pkg.mSignatures[0];
14837                final PublicKey publicKey = verifierSig.getPublicKey();
14838                expectedPublicKey = publicKey.getEncoded();
14839            } catch (CertificateException e) {
14840                return -1;
14841            }
14842
14843            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14844
14845            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14846                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14847                        + " does not have the expected public key; ignoring");
14848                return -1;
14849            }
14850
14851            return pkg.applicationInfo.uid;
14852        }
14853    }
14854
14855    @Override
14856    public void finishPackageInstall(int token, boolean didLaunch) {
14857        enforceSystemOrRoot("Only the system is allowed to finish installs");
14858
14859        if (DEBUG_INSTALL) {
14860            Slog.v(TAG, "BM finishing package install for " + token);
14861        }
14862        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14863
14864        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14865        mHandler.sendMessage(msg);
14866    }
14867
14868    /**
14869     * Get the verification agent timeout.  Used for both the APK verifier and the
14870     * intent filter verifier.
14871     *
14872     * @return verification timeout in milliseconds
14873     */
14874    private long getVerificationTimeout() {
14875        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14876                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14877                DEFAULT_VERIFICATION_TIMEOUT);
14878    }
14879
14880    /**
14881     * Get the default verification agent response code.
14882     *
14883     * @return default verification response code
14884     */
14885    private int getDefaultVerificationResponse(UserHandle user) {
14886        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14887            return PackageManager.VERIFICATION_REJECT;
14888        }
14889        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14890                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14891                DEFAULT_VERIFICATION_RESPONSE);
14892    }
14893
14894    /**
14895     * Check whether or not package verification has been enabled.
14896     *
14897     * @return true if verification should be performed
14898     */
14899    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14900        if (!DEFAULT_VERIFY_ENABLE) {
14901            return false;
14902        }
14903
14904        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14905
14906        // Check if installing from ADB
14907        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14908            // Do not run verification in a test harness environment
14909            if (ActivityManager.isRunningInTestHarness()) {
14910                return false;
14911            }
14912            if (ensureVerifyAppsEnabled) {
14913                return true;
14914            }
14915            // Check if the developer does not want package verification for ADB installs
14916            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14917                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14918                return false;
14919            }
14920        } else {
14921            // only when not installed from ADB, skip verification for instant apps when
14922            // the installer and verifier are the same.
14923            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14924                if (mInstantAppInstallerActivity != null
14925                        && mInstantAppInstallerActivity.packageName.equals(
14926                                mRequiredVerifierPackage)) {
14927                    try {
14928                        mContext.getSystemService(AppOpsManager.class)
14929                                .checkPackage(installerUid, mRequiredVerifierPackage);
14930                        if (DEBUG_VERIFY) {
14931                            Slog.i(TAG, "disable verification for instant app");
14932                        }
14933                        return false;
14934                    } catch (SecurityException ignore) { }
14935                }
14936            }
14937        }
14938
14939        if (ensureVerifyAppsEnabled) {
14940            return true;
14941        }
14942
14943        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14944                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14945    }
14946
14947    @Override
14948    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14949            throws RemoteException {
14950        mContext.enforceCallingOrSelfPermission(
14951                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14952                "Only intentfilter verification agents can verify applications");
14953
14954        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14955        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14956                Binder.getCallingUid(), verificationCode, failedDomains);
14957        msg.arg1 = id;
14958        msg.obj = response;
14959        mHandler.sendMessage(msg);
14960    }
14961
14962    @Override
14963    public int getIntentVerificationStatus(String packageName, int userId) {
14964        final int callingUid = Binder.getCallingUid();
14965        if (getInstantAppPackageName(callingUid) != null) {
14966            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14967        }
14968        synchronized (mPackages) {
14969            final PackageSetting ps = mSettings.mPackages.get(packageName);
14970            if (ps == null
14971                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14972                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14973            }
14974            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14975        }
14976    }
14977
14978    @Override
14979    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14980        mContext.enforceCallingOrSelfPermission(
14981                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14982
14983        boolean result = false;
14984        synchronized (mPackages) {
14985            final PackageSetting ps = mSettings.mPackages.get(packageName);
14986            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14987                return false;
14988            }
14989            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14990        }
14991        if (result) {
14992            scheduleWritePackageRestrictionsLocked(userId);
14993        }
14994        return result;
14995    }
14996
14997    @Override
14998    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14999            String packageName) {
15000        final int callingUid = Binder.getCallingUid();
15001        if (getInstantAppPackageName(callingUid) != null) {
15002            return ParceledListSlice.emptyList();
15003        }
15004        synchronized (mPackages) {
15005            final PackageSetting ps = mSettings.mPackages.get(packageName);
15006            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15007                return ParceledListSlice.emptyList();
15008            }
15009            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15010        }
15011    }
15012
15013    @Override
15014    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15015        if (TextUtils.isEmpty(packageName)) {
15016            return ParceledListSlice.emptyList();
15017        }
15018        final int callingUid = Binder.getCallingUid();
15019        final int callingUserId = UserHandle.getUserId(callingUid);
15020        synchronized (mPackages) {
15021            PackageParser.Package pkg = mPackages.get(packageName);
15022            if (pkg == null || pkg.activities == null) {
15023                return ParceledListSlice.emptyList();
15024            }
15025            if (pkg.mExtras == null) {
15026                return ParceledListSlice.emptyList();
15027            }
15028            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15029            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15030                return ParceledListSlice.emptyList();
15031            }
15032            final int count = pkg.activities.size();
15033            ArrayList<IntentFilter> result = new ArrayList<>();
15034            for (int n=0; n<count; n++) {
15035                PackageParser.Activity activity = pkg.activities.get(n);
15036                if (activity.intents != null && activity.intents.size() > 0) {
15037                    result.addAll(activity.intents);
15038                }
15039            }
15040            return new ParceledListSlice<>(result);
15041        }
15042    }
15043
15044    @Override
15045    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15046        mContext.enforceCallingOrSelfPermission(
15047                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15048
15049        synchronized (mPackages) {
15050            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15051            if (packageName != null) {
15052                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15053                        packageName, userId);
15054            }
15055            return result;
15056        }
15057    }
15058
15059    @Override
15060    public String getDefaultBrowserPackageName(int userId) {
15061        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15062            return null;
15063        }
15064        synchronized (mPackages) {
15065            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15066        }
15067    }
15068
15069    /**
15070     * Get the "allow unknown sources" setting.
15071     *
15072     * @return the current "allow unknown sources" setting
15073     */
15074    private int getUnknownSourcesSettings() {
15075        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15076                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15077                -1);
15078    }
15079
15080    @Override
15081    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15082        final int callingUid = Binder.getCallingUid();
15083        if (getInstantAppPackageName(callingUid) != null) {
15084            return;
15085        }
15086        // writer
15087        synchronized (mPackages) {
15088            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15089            if (targetPackageSetting == null
15090                    || filterAppAccessLPr(
15091                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15092                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15093            }
15094
15095            PackageSetting installerPackageSetting;
15096            if (installerPackageName != null) {
15097                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15098                if (installerPackageSetting == null) {
15099                    throw new IllegalArgumentException("Unknown installer package: "
15100                            + installerPackageName);
15101                }
15102            } else {
15103                installerPackageSetting = null;
15104            }
15105
15106            Signature[] callerSignature;
15107            Object obj = mSettings.getUserIdLPr(callingUid);
15108            if (obj != null) {
15109                if (obj instanceof SharedUserSetting) {
15110                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15111                } else if (obj instanceof PackageSetting) {
15112                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15113                } else {
15114                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15115                }
15116            } else {
15117                throw new SecurityException("Unknown calling UID: " + callingUid);
15118            }
15119
15120            // Verify: can't set installerPackageName to a package that is
15121            // not signed with the same cert as the caller.
15122            if (installerPackageSetting != null) {
15123                if (compareSignatures(callerSignature,
15124                        installerPackageSetting.signatures.mSignatures)
15125                        != PackageManager.SIGNATURE_MATCH) {
15126                    throw new SecurityException(
15127                            "Caller does not have same cert as new installer package "
15128                            + installerPackageName);
15129                }
15130            }
15131
15132            // Verify: if target already has an installer package, it must
15133            // be signed with the same cert as the caller.
15134            if (targetPackageSetting.installerPackageName != null) {
15135                PackageSetting setting = mSettings.mPackages.get(
15136                        targetPackageSetting.installerPackageName);
15137                // If the currently set package isn't valid, then it's always
15138                // okay to change it.
15139                if (setting != null) {
15140                    if (compareSignatures(callerSignature,
15141                            setting.signatures.mSignatures)
15142                            != PackageManager.SIGNATURE_MATCH) {
15143                        throw new SecurityException(
15144                                "Caller does not have same cert as old installer package "
15145                                + targetPackageSetting.installerPackageName);
15146                    }
15147                }
15148            }
15149
15150            // Okay!
15151            targetPackageSetting.installerPackageName = installerPackageName;
15152            if (installerPackageName != null) {
15153                mSettings.mInstallerPackages.add(installerPackageName);
15154            }
15155            scheduleWriteSettingsLocked();
15156        }
15157    }
15158
15159    @Override
15160    public void setApplicationCategoryHint(String packageName, int categoryHint,
15161            String callerPackageName) {
15162        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15163            throw new SecurityException("Instant applications don't have access to this method");
15164        }
15165        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15166                callerPackageName);
15167        synchronized (mPackages) {
15168            PackageSetting ps = mSettings.mPackages.get(packageName);
15169            if (ps == null) {
15170                throw new IllegalArgumentException("Unknown target package " + packageName);
15171            }
15172            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15173                throw new IllegalArgumentException("Unknown target package " + packageName);
15174            }
15175            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15176                throw new IllegalArgumentException("Calling package " + callerPackageName
15177                        + " is not installer for " + packageName);
15178            }
15179
15180            if (ps.categoryHint != categoryHint) {
15181                ps.categoryHint = categoryHint;
15182                scheduleWriteSettingsLocked();
15183            }
15184        }
15185    }
15186
15187    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15188        // Queue up an async operation since the package installation may take a little while.
15189        mHandler.post(new Runnable() {
15190            public void run() {
15191                mHandler.removeCallbacks(this);
15192                 // Result object to be returned
15193                PackageInstalledInfo res = new PackageInstalledInfo();
15194                res.setReturnCode(currentStatus);
15195                res.uid = -1;
15196                res.pkg = null;
15197                res.removedInfo = null;
15198                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15199                    args.doPreInstall(res.returnCode);
15200                    synchronized (mInstallLock) {
15201                        installPackageTracedLI(args, res);
15202                    }
15203                    args.doPostInstall(res.returnCode, res.uid);
15204                }
15205
15206                // A restore should be performed at this point if (a) the install
15207                // succeeded, (b) the operation is not an update, and (c) the new
15208                // package has not opted out of backup participation.
15209                final boolean update = res.removedInfo != null
15210                        && res.removedInfo.removedPackage != null;
15211                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15212                boolean doRestore = !update
15213                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15214
15215                // Set up the post-install work request bookkeeping.  This will be used
15216                // and cleaned up by the post-install event handling regardless of whether
15217                // there's a restore pass performed.  Token values are >= 1.
15218                int token;
15219                if (mNextInstallToken < 0) mNextInstallToken = 1;
15220                token = mNextInstallToken++;
15221
15222                PostInstallData data = new PostInstallData(args, res);
15223                mRunningInstalls.put(token, data);
15224                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15225
15226                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15227                    // Pass responsibility to the Backup Manager.  It will perform a
15228                    // restore if appropriate, then pass responsibility back to the
15229                    // Package Manager to run the post-install observer callbacks
15230                    // and broadcasts.
15231                    IBackupManager bm = IBackupManager.Stub.asInterface(
15232                            ServiceManager.getService(Context.BACKUP_SERVICE));
15233                    if (bm != null) {
15234                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15235                                + " to BM for possible restore");
15236                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15237                        try {
15238                            // TODO: http://b/22388012
15239                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15240                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15241                            } else {
15242                                doRestore = false;
15243                            }
15244                        } catch (RemoteException e) {
15245                            // can't happen; the backup manager is local
15246                        } catch (Exception e) {
15247                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15248                            doRestore = false;
15249                        }
15250                    } else {
15251                        Slog.e(TAG, "Backup Manager not found!");
15252                        doRestore = false;
15253                    }
15254                }
15255
15256                if (!doRestore) {
15257                    // No restore possible, or the Backup Manager was mysteriously not
15258                    // available -- just fire the post-install work request directly.
15259                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15260
15261                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15262
15263                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15264                    mHandler.sendMessage(msg);
15265                }
15266            }
15267        });
15268    }
15269
15270    /**
15271     * Callback from PackageSettings whenever an app is first transitioned out of the
15272     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15273     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15274     * here whether the app is the target of an ongoing install, and only send the
15275     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15276     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15277     * handling.
15278     */
15279    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15280        // Serialize this with the rest of the install-process message chain.  In the
15281        // restore-at-install case, this Runnable will necessarily run before the
15282        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15283        // are coherent.  In the non-restore case, the app has already completed install
15284        // and been launched through some other means, so it is not in a problematic
15285        // state for observers to see the FIRST_LAUNCH signal.
15286        mHandler.post(new Runnable() {
15287            @Override
15288            public void run() {
15289                for (int i = 0; i < mRunningInstalls.size(); i++) {
15290                    final PostInstallData data = mRunningInstalls.valueAt(i);
15291                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15292                        continue;
15293                    }
15294                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15295                        // right package; but is it for the right user?
15296                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15297                            if (userId == data.res.newUsers[uIndex]) {
15298                                if (DEBUG_BACKUP) {
15299                                    Slog.i(TAG, "Package " + pkgName
15300                                            + " being restored so deferring FIRST_LAUNCH");
15301                                }
15302                                return;
15303                            }
15304                        }
15305                    }
15306                }
15307                // didn't find it, so not being restored
15308                if (DEBUG_BACKUP) {
15309                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15310                }
15311                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15312            }
15313        });
15314    }
15315
15316    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15317        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15318                installerPkg, null, userIds);
15319    }
15320
15321    private abstract class HandlerParams {
15322        private static final int MAX_RETRIES = 4;
15323
15324        /**
15325         * Number of times startCopy() has been attempted and had a non-fatal
15326         * error.
15327         */
15328        private int mRetries = 0;
15329
15330        /** User handle for the user requesting the information or installation. */
15331        private final UserHandle mUser;
15332        String traceMethod;
15333        int traceCookie;
15334
15335        HandlerParams(UserHandle user) {
15336            mUser = user;
15337        }
15338
15339        UserHandle getUser() {
15340            return mUser;
15341        }
15342
15343        HandlerParams setTraceMethod(String traceMethod) {
15344            this.traceMethod = traceMethod;
15345            return this;
15346        }
15347
15348        HandlerParams setTraceCookie(int traceCookie) {
15349            this.traceCookie = traceCookie;
15350            return this;
15351        }
15352
15353        final boolean startCopy() {
15354            boolean res;
15355            try {
15356                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15357
15358                if (++mRetries > MAX_RETRIES) {
15359                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15360                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15361                    handleServiceError();
15362                    return false;
15363                } else {
15364                    handleStartCopy();
15365                    res = true;
15366                }
15367            } catch (RemoteException e) {
15368                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15369                mHandler.sendEmptyMessage(MCS_RECONNECT);
15370                res = false;
15371            }
15372            handleReturnCode();
15373            return res;
15374        }
15375
15376        final void serviceError() {
15377            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15378            handleServiceError();
15379            handleReturnCode();
15380        }
15381
15382        abstract void handleStartCopy() throws RemoteException;
15383        abstract void handleServiceError();
15384        abstract void handleReturnCode();
15385    }
15386
15387    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15388        for (File path : paths) {
15389            try {
15390                mcs.clearDirectory(path.getAbsolutePath());
15391            } catch (RemoteException e) {
15392            }
15393        }
15394    }
15395
15396    static class OriginInfo {
15397        /**
15398         * Location where install is coming from, before it has been
15399         * copied/renamed into place. This could be a single monolithic APK
15400         * file, or a cluster directory. This location may be untrusted.
15401         */
15402        final File file;
15403        final String cid;
15404
15405        /**
15406         * Flag indicating that {@link #file} or {@link #cid} has already been
15407         * staged, meaning downstream users don't need to defensively copy the
15408         * contents.
15409         */
15410        final boolean staged;
15411
15412        /**
15413         * Flag indicating that {@link #file} or {@link #cid} is an already
15414         * installed app that is being moved.
15415         */
15416        final boolean existing;
15417
15418        final String resolvedPath;
15419        final File resolvedFile;
15420
15421        static OriginInfo fromNothing() {
15422            return new OriginInfo(null, null, false, false);
15423        }
15424
15425        static OriginInfo fromUntrustedFile(File file) {
15426            return new OriginInfo(file, null, false, false);
15427        }
15428
15429        static OriginInfo fromExistingFile(File file) {
15430            return new OriginInfo(file, null, false, true);
15431        }
15432
15433        static OriginInfo fromStagedFile(File file) {
15434            return new OriginInfo(file, null, true, false);
15435        }
15436
15437        static OriginInfo fromStagedContainer(String cid) {
15438            return new OriginInfo(null, cid, true, false);
15439        }
15440
15441        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15442            this.file = file;
15443            this.cid = cid;
15444            this.staged = staged;
15445            this.existing = existing;
15446
15447            if (cid != null) {
15448                resolvedPath = PackageHelper.getSdDir(cid);
15449                resolvedFile = new File(resolvedPath);
15450            } else if (file != null) {
15451                resolvedPath = file.getAbsolutePath();
15452                resolvedFile = file;
15453            } else {
15454                resolvedPath = null;
15455                resolvedFile = null;
15456            }
15457        }
15458    }
15459
15460    static class MoveInfo {
15461        final int moveId;
15462        final String fromUuid;
15463        final String toUuid;
15464        final String packageName;
15465        final String dataAppName;
15466        final int appId;
15467        final String seinfo;
15468        final int targetSdkVersion;
15469
15470        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15471                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15472            this.moveId = moveId;
15473            this.fromUuid = fromUuid;
15474            this.toUuid = toUuid;
15475            this.packageName = packageName;
15476            this.dataAppName = dataAppName;
15477            this.appId = appId;
15478            this.seinfo = seinfo;
15479            this.targetSdkVersion = targetSdkVersion;
15480        }
15481    }
15482
15483    static class VerificationInfo {
15484        /** A constant used to indicate that a uid value is not present. */
15485        public static final int NO_UID = -1;
15486
15487        /** URI referencing where the package was downloaded from. */
15488        final Uri originatingUri;
15489
15490        /** HTTP referrer URI associated with the originatingURI. */
15491        final Uri referrer;
15492
15493        /** UID of the application that the install request originated from. */
15494        final int originatingUid;
15495
15496        /** UID of application requesting the install */
15497        final int installerUid;
15498
15499        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15500            this.originatingUri = originatingUri;
15501            this.referrer = referrer;
15502            this.originatingUid = originatingUid;
15503            this.installerUid = installerUid;
15504        }
15505    }
15506
15507    class InstallParams extends HandlerParams {
15508        final OriginInfo origin;
15509        final MoveInfo move;
15510        final IPackageInstallObserver2 observer;
15511        int installFlags;
15512        final String installerPackageName;
15513        final String volumeUuid;
15514        private InstallArgs mArgs;
15515        private int mRet;
15516        final String packageAbiOverride;
15517        final String[] grantedRuntimePermissions;
15518        final VerificationInfo verificationInfo;
15519        final Certificate[][] certificates;
15520        final int installReason;
15521
15522        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15523                int installFlags, String installerPackageName, String volumeUuid,
15524                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15525                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15526            super(user);
15527            this.origin = origin;
15528            this.move = move;
15529            this.observer = observer;
15530            this.installFlags = installFlags;
15531            this.installerPackageName = installerPackageName;
15532            this.volumeUuid = volumeUuid;
15533            this.verificationInfo = verificationInfo;
15534            this.packageAbiOverride = packageAbiOverride;
15535            this.grantedRuntimePermissions = grantedPermissions;
15536            this.certificates = certificates;
15537            this.installReason = installReason;
15538        }
15539
15540        @Override
15541        public String toString() {
15542            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15543                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15544        }
15545
15546        private int installLocationPolicy(PackageInfoLite pkgLite) {
15547            String packageName = pkgLite.packageName;
15548            int installLocation = pkgLite.installLocation;
15549            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15550            // reader
15551            synchronized (mPackages) {
15552                // Currently installed package which the new package is attempting to replace or
15553                // null if no such package is installed.
15554                PackageParser.Package installedPkg = mPackages.get(packageName);
15555                // Package which currently owns the data which the new package will own if installed.
15556                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15557                // will be null whereas dataOwnerPkg will contain information about the package
15558                // which was uninstalled while keeping its data.
15559                PackageParser.Package dataOwnerPkg = installedPkg;
15560                if (dataOwnerPkg  == null) {
15561                    PackageSetting ps = mSettings.mPackages.get(packageName);
15562                    if (ps != null) {
15563                        dataOwnerPkg = ps.pkg;
15564                    }
15565                }
15566
15567                if (dataOwnerPkg != null) {
15568                    // If installed, the package will get access to data left on the device by its
15569                    // predecessor. As a security measure, this is permited only if this is not a
15570                    // version downgrade or if the predecessor package is marked as debuggable and
15571                    // a downgrade is explicitly requested.
15572                    //
15573                    // On debuggable platform builds, downgrades are permitted even for
15574                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15575                    // not offer security guarantees and thus it's OK to disable some security
15576                    // mechanisms to make debugging/testing easier on those builds. However, even on
15577                    // debuggable builds downgrades of packages are permitted only if requested via
15578                    // installFlags. This is because we aim to keep the behavior of debuggable
15579                    // platform builds as close as possible to the behavior of non-debuggable
15580                    // platform builds.
15581                    final boolean downgradeRequested =
15582                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15583                    final boolean packageDebuggable =
15584                                (dataOwnerPkg.applicationInfo.flags
15585                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15586                    final boolean downgradePermitted =
15587                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15588                    if (!downgradePermitted) {
15589                        try {
15590                            checkDowngrade(dataOwnerPkg, pkgLite);
15591                        } catch (PackageManagerException e) {
15592                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15593                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15594                        }
15595                    }
15596                }
15597
15598                if (installedPkg != null) {
15599                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15600                        // Check for updated system application.
15601                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15602                            if (onSd) {
15603                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15604                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15605                            }
15606                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15607                        } else {
15608                            if (onSd) {
15609                                // Install flag overrides everything.
15610                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15611                            }
15612                            // If current upgrade specifies particular preference
15613                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15614                                // Application explicitly specified internal.
15615                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15616                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15617                                // App explictly prefers external. Let policy decide
15618                            } else {
15619                                // Prefer previous location
15620                                if (isExternal(installedPkg)) {
15621                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15622                                }
15623                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15624                            }
15625                        }
15626                    } else {
15627                        // Invalid install. Return error code
15628                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15629                    }
15630                }
15631            }
15632            // All the special cases have been taken care of.
15633            // Return result based on recommended install location.
15634            if (onSd) {
15635                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15636            }
15637            return pkgLite.recommendedInstallLocation;
15638        }
15639
15640        /*
15641         * Invoke remote method to get package information and install
15642         * location values. Override install location based on default
15643         * policy if needed and then create install arguments based
15644         * on the install location.
15645         */
15646        public void handleStartCopy() throws RemoteException {
15647            int ret = PackageManager.INSTALL_SUCCEEDED;
15648
15649            // If we're already staged, we've firmly committed to an install location
15650            if (origin.staged) {
15651                if (origin.file != null) {
15652                    installFlags |= PackageManager.INSTALL_INTERNAL;
15653                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15654                } else if (origin.cid != null) {
15655                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15656                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15657                } else {
15658                    throw new IllegalStateException("Invalid stage location");
15659                }
15660            }
15661
15662            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15663            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15664            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15665            PackageInfoLite pkgLite = null;
15666
15667            if (onInt && onSd) {
15668                // Check if both bits are set.
15669                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15670                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15671            } else if (onSd && ephemeral) {
15672                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15673                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15674            } else {
15675                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15676                        packageAbiOverride);
15677
15678                if (DEBUG_EPHEMERAL && ephemeral) {
15679                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15680                }
15681
15682                /*
15683                 * If we have too little free space, try to free cache
15684                 * before giving up.
15685                 */
15686                if (!origin.staged && pkgLite.recommendedInstallLocation
15687                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15688                    // TODO: focus freeing disk space on the target device
15689                    final StorageManager storage = StorageManager.from(mContext);
15690                    final long lowThreshold = storage.getStorageLowBytes(
15691                            Environment.getDataDirectory());
15692
15693                    final long sizeBytes = mContainerService.calculateInstalledSize(
15694                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15695
15696                    try {
15697                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15698                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15699                                installFlags, packageAbiOverride);
15700                    } catch (InstallerException e) {
15701                        Slog.w(TAG, "Failed to free cache", e);
15702                    }
15703
15704                    /*
15705                     * The cache free must have deleted the file we
15706                     * downloaded to install.
15707                     *
15708                     * TODO: fix the "freeCache" call to not delete
15709                     *       the file we care about.
15710                     */
15711                    if (pkgLite.recommendedInstallLocation
15712                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15713                        pkgLite.recommendedInstallLocation
15714                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15715                    }
15716                }
15717            }
15718
15719            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15720                int loc = pkgLite.recommendedInstallLocation;
15721                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15722                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15723                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15724                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15725                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15726                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15727                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15728                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15729                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15730                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15731                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15732                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15733                } else {
15734                    // Override with defaults if needed.
15735                    loc = installLocationPolicy(pkgLite);
15736                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15737                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15738                    } else if (!onSd && !onInt) {
15739                        // Override install location with flags
15740                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15741                            // Set the flag to install on external media.
15742                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15743                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15744                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15745                            if (DEBUG_EPHEMERAL) {
15746                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15747                            }
15748                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15749                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15750                                    |PackageManager.INSTALL_INTERNAL);
15751                        } else {
15752                            // Make sure the flag for installing on external
15753                            // media is unset
15754                            installFlags |= PackageManager.INSTALL_INTERNAL;
15755                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15756                        }
15757                    }
15758                }
15759            }
15760
15761            final InstallArgs args = createInstallArgs(this);
15762            mArgs = args;
15763
15764            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15765                // TODO: http://b/22976637
15766                // Apps installed for "all" users use the device owner to verify the app
15767                UserHandle verifierUser = getUser();
15768                if (verifierUser == UserHandle.ALL) {
15769                    verifierUser = UserHandle.SYSTEM;
15770                }
15771
15772                /*
15773                 * Determine if we have any installed package verifiers. If we
15774                 * do, then we'll defer to them to verify the packages.
15775                 */
15776                final int requiredUid = mRequiredVerifierPackage == null ? -1
15777                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15778                                verifierUser.getIdentifier());
15779                final int installerUid =
15780                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15781                if (!origin.existing && requiredUid != -1
15782                        && isVerificationEnabled(
15783                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15784                    final Intent verification = new Intent(
15785                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15786                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15787                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15788                            PACKAGE_MIME_TYPE);
15789                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15790
15791                    // Query all live verifiers based on current user state
15792                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15793                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15794
15795                    if (DEBUG_VERIFY) {
15796                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15797                                + verification.toString() + " with " + pkgLite.verifiers.length
15798                                + " optional verifiers");
15799                    }
15800
15801                    final int verificationId = mPendingVerificationToken++;
15802
15803                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15804
15805                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15806                            installerPackageName);
15807
15808                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15809                            installFlags);
15810
15811                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15812                            pkgLite.packageName);
15813
15814                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15815                            pkgLite.versionCode);
15816
15817                    if (verificationInfo != null) {
15818                        if (verificationInfo.originatingUri != null) {
15819                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15820                                    verificationInfo.originatingUri);
15821                        }
15822                        if (verificationInfo.referrer != null) {
15823                            verification.putExtra(Intent.EXTRA_REFERRER,
15824                                    verificationInfo.referrer);
15825                        }
15826                        if (verificationInfo.originatingUid >= 0) {
15827                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15828                                    verificationInfo.originatingUid);
15829                        }
15830                        if (verificationInfo.installerUid >= 0) {
15831                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15832                                    verificationInfo.installerUid);
15833                        }
15834                    }
15835
15836                    final PackageVerificationState verificationState = new PackageVerificationState(
15837                            requiredUid, args);
15838
15839                    mPendingVerification.append(verificationId, verificationState);
15840
15841                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15842                            receivers, verificationState);
15843
15844                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15845                    final long idleDuration = getVerificationTimeout();
15846
15847                    /*
15848                     * If any sufficient verifiers were listed in the package
15849                     * manifest, attempt to ask them.
15850                     */
15851                    if (sufficientVerifiers != null) {
15852                        final int N = sufficientVerifiers.size();
15853                        if (N == 0) {
15854                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15855                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15856                        } else {
15857                            for (int i = 0; i < N; i++) {
15858                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15859                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15860                                        verifierComponent.getPackageName(), idleDuration,
15861                                        verifierUser.getIdentifier(), false, "package verifier");
15862
15863                                final Intent sufficientIntent = new Intent(verification);
15864                                sufficientIntent.setComponent(verifierComponent);
15865                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15866                            }
15867                        }
15868                    }
15869
15870                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15871                            mRequiredVerifierPackage, receivers);
15872                    if (ret == PackageManager.INSTALL_SUCCEEDED
15873                            && mRequiredVerifierPackage != null) {
15874                        Trace.asyncTraceBegin(
15875                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15876                        /*
15877                         * Send the intent to the required verification agent,
15878                         * but only start the verification timeout after the
15879                         * target BroadcastReceivers have run.
15880                         */
15881                        verification.setComponent(requiredVerifierComponent);
15882                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15883                                mRequiredVerifierPackage, idleDuration,
15884                                verifierUser.getIdentifier(), false, "package verifier");
15885                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15886                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15887                                new BroadcastReceiver() {
15888                                    @Override
15889                                    public void onReceive(Context context, Intent intent) {
15890                                        final Message msg = mHandler
15891                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15892                                        msg.arg1 = verificationId;
15893                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15894                                    }
15895                                }, null, 0, null, null);
15896
15897                        /*
15898                         * We don't want the copy to proceed until verification
15899                         * succeeds, so null out this field.
15900                         */
15901                        mArgs = null;
15902                    }
15903                } else {
15904                    /*
15905                     * No package verification is enabled, so immediately start
15906                     * the remote call to initiate copy using temporary file.
15907                     */
15908                    ret = args.copyApk(mContainerService, true);
15909                }
15910            }
15911
15912            mRet = ret;
15913        }
15914
15915        @Override
15916        void handleReturnCode() {
15917            // If mArgs is null, then MCS couldn't be reached. When it
15918            // reconnects, it will try again to install. At that point, this
15919            // will succeed.
15920            if (mArgs != null) {
15921                processPendingInstall(mArgs, mRet);
15922            }
15923        }
15924
15925        @Override
15926        void handleServiceError() {
15927            mArgs = createInstallArgs(this);
15928            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15929        }
15930
15931        public boolean isForwardLocked() {
15932            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15933        }
15934    }
15935
15936    /**
15937     * Used during creation of InstallArgs
15938     *
15939     * @param installFlags package installation flags
15940     * @return true if should be installed on external storage
15941     */
15942    private static boolean installOnExternalAsec(int installFlags) {
15943        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
15944            return false;
15945        }
15946        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
15947            return true;
15948        }
15949        return false;
15950    }
15951
15952    /**
15953     * Used during creation of InstallArgs
15954     *
15955     * @param installFlags package installation flags
15956     * @return true if should be installed as forward locked
15957     */
15958    private static boolean installForwardLocked(int installFlags) {
15959        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15960    }
15961
15962    private InstallArgs createInstallArgs(InstallParams params) {
15963        if (params.move != null) {
15964            return new MoveInstallArgs(params);
15965        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15966            return new AsecInstallArgs(params);
15967        } else {
15968            return new FileInstallArgs(params);
15969        }
15970    }
15971
15972    /**
15973     * Create args that describe an existing installed package. Typically used
15974     * when cleaning up old installs, or used as a move source.
15975     */
15976    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15977            String resourcePath, String[] instructionSets) {
15978        final boolean isInAsec;
15979        if (installOnExternalAsec(installFlags)) {
15980            /* Apps on SD card are always in ASEC containers. */
15981            isInAsec = true;
15982        } else if (installForwardLocked(installFlags)
15983                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
15984            /*
15985             * Forward-locked apps are only in ASEC containers if they're the
15986             * new style
15987             */
15988            isInAsec = true;
15989        } else {
15990            isInAsec = false;
15991        }
15992
15993        if (isInAsec) {
15994            return new AsecInstallArgs(codePath, instructionSets,
15995                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
15996        } else {
15997            return new FileInstallArgs(codePath, resourcePath, instructionSets);
15998        }
15999    }
16000
16001    static abstract class InstallArgs {
16002        /** @see InstallParams#origin */
16003        final OriginInfo origin;
16004        /** @see InstallParams#move */
16005        final MoveInfo move;
16006
16007        final IPackageInstallObserver2 observer;
16008        // Always refers to PackageManager flags only
16009        final int installFlags;
16010        final String installerPackageName;
16011        final String volumeUuid;
16012        final UserHandle user;
16013        final String abiOverride;
16014        final String[] installGrantPermissions;
16015        /** If non-null, drop an async trace when the install completes */
16016        final String traceMethod;
16017        final int traceCookie;
16018        final Certificate[][] certificates;
16019        final int installReason;
16020
16021        // The list of instruction sets supported by this app. This is currently
16022        // only used during the rmdex() phase to clean up resources. We can get rid of this
16023        // if we move dex files under the common app path.
16024        /* nullable */ String[] instructionSets;
16025
16026        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16027                int installFlags, String installerPackageName, String volumeUuid,
16028                UserHandle user, String[] instructionSets,
16029                String abiOverride, String[] installGrantPermissions,
16030                String traceMethod, int traceCookie, Certificate[][] certificates,
16031                int installReason) {
16032            this.origin = origin;
16033            this.move = move;
16034            this.installFlags = installFlags;
16035            this.observer = observer;
16036            this.installerPackageName = installerPackageName;
16037            this.volumeUuid = volumeUuid;
16038            this.user = user;
16039            this.instructionSets = instructionSets;
16040            this.abiOverride = abiOverride;
16041            this.installGrantPermissions = installGrantPermissions;
16042            this.traceMethod = traceMethod;
16043            this.traceCookie = traceCookie;
16044            this.certificates = certificates;
16045            this.installReason = installReason;
16046        }
16047
16048        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16049        abstract int doPreInstall(int status);
16050
16051        /**
16052         * Rename package into final resting place. All paths on the given
16053         * scanned package should be updated to reflect the rename.
16054         */
16055        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16056        abstract int doPostInstall(int status, int uid);
16057
16058        /** @see PackageSettingBase#codePathString */
16059        abstract String getCodePath();
16060        /** @see PackageSettingBase#resourcePathString */
16061        abstract String getResourcePath();
16062
16063        // Need installer lock especially for dex file removal.
16064        abstract void cleanUpResourcesLI();
16065        abstract boolean doPostDeleteLI(boolean delete);
16066
16067        /**
16068         * Called before the source arguments are copied. This is used mostly
16069         * for MoveParams when it needs to read the source file to put it in the
16070         * destination.
16071         */
16072        int doPreCopy() {
16073            return PackageManager.INSTALL_SUCCEEDED;
16074        }
16075
16076        /**
16077         * Called after the source arguments are copied. This is used mostly for
16078         * MoveParams when it needs to read the source file to put it in the
16079         * destination.
16080         */
16081        int doPostCopy(int uid) {
16082            return PackageManager.INSTALL_SUCCEEDED;
16083        }
16084
16085        protected boolean isFwdLocked() {
16086            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16087        }
16088
16089        protected boolean isExternalAsec() {
16090            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16091        }
16092
16093        protected boolean isEphemeral() {
16094            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16095        }
16096
16097        UserHandle getUser() {
16098            return user;
16099        }
16100    }
16101
16102    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16103        if (!allCodePaths.isEmpty()) {
16104            if (instructionSets == null) {
16105                throw new IllegalStateException("instructionSet == null");
16106            }
16107            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16108            for (String codePath : allCodePaths) {
16109                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16110                    try {
16111                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16112                    } catch (InstallerException ignored) {
16113                    }
16114                }
16115            }
16116        }
16117    }
16118
16119    /**
16120     * Logic to handle installation of non-ASEC applications, including copying
16121     * and renaming logic.
16122     */
16123    class FileInstallArgs extends InstallArgs {
16124        private File codeFile;
16125        private File resourceFile;
16126
16127        // Example topology:
16128        // /data/app/com.example/base.apk
16129        // /data/app/com.example/split_foo.apk
16130        // /data/app/com.example/lib/arm/libfoo.so
16131        // /data/app/com.example/lib/arm64/libfoo.so
16132        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16133
16134        /** New install */
16135        FileInstallArgs(InstallParams params) {
16136            super(params.origin, params.move, params.observer, params.installFlags,
16137                    params.installerPackageName, params.volumeUuid,
16138                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16139                    params.grantedRuntimePermissions,
16140                    params.traceMethod, params.traceCookie, params.certificates,
16141                    params.installReason);
16142            if (isFwdLocked()) {
16143                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16144            }
16145        }
16146
16147        /** Existing install */
16148        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16149            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16150                    null, null, null, 0, null /*certificates*/,
16151                    PackageManager.INSTALL_REASON_UNKNOWN);
16152            this.codeFile = (codePath != null) ? new File(codePath) : null;
16153            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16154        }
16155
16156        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16157            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16158            try {
16159                return doCopyApk(imcs, temp);
16160            } finally {
16161                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16162            }
16163        }
16164
16165        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16166            if (origin.staged) {
16167                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16168                codeFile = origin.file;
16169                resourceFile = origin.file;
16170                return PackageManager.INSTALL_SUCCEEDED;
16171            }
16172
16173            try {
16174                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16175                final File tempDir =
16176                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16177                codeFile = tempDir;
16178                resourceFile = tempDir;
16179            } catch (IOException e) {
16180                Slog.w(TAG, "Failed to create copy file: " + e);
16181                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16182            }
16183
16184            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16185                @Override
16186                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16187                    if (!FileUtils.isValidExtFilename(name)) {
16188                        throw new IllegalArgumentException("Invalid filename: " + name);
16189                    }
16190                    try {
16191                        final File file = new File(codeFile, name);
16192                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16193                                O_RDWR | O_CREAT, 0644);
16194                        Os.chmod(file.getAbsolutePath(), 0644);
16195                        return new ParcelFileDescriptor(fd);
16196                    } catch (ErrnoException e) {
16197                        throw new RemoteException("Failed to open: " + e.getMessage());
16198                    }
16199                }
16200            };
16201
16202            int ret = PackageManager.INSTALL_SUCCEEDED;
16203            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16204            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16205                Slog.e(TAG, "Failed to copy package");
16206                return ret;
16207            }
16208
16209            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16210            NativeLibraryHelper.Handle handle = null;
16211            try {
16212                handle = NativeLibraryHelper.Handle.create(codeFile);
16213                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16214                        abiOverride);
16215            } catch (IOException e) {
16216                Slog.e(TAG, "Copying native libraries failed", e);
16217                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16218            } finally {
16219                IoUtils.closeQuietly(handle);
16220            }
16221
16222            return ret;
16223        }
16224
16225        int doPreInstall(int status) {
16226            if (status != PackageManager.INSTALL_SUCCEEDED) {
16227                cleanUp();
16228            }
16229            return status;
16230        }
16231
16232        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16233            if (status != PackageManager.INSTALL_SUCCEEDED) {
16234                cleanUp();
16235                return false;
16236            }
16237
16238            final File targetDir = codeFile.getParentFile();
16239            final File beforeCodeFile = codeFile;
16240            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16241
16242            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16243            try {
16244                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16245            } catch (ErrnoException e) {
16246                Slog.w(TAG, "Failed to rename", e);
16247                return false;
16248            }
16249
16250            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16251                Slog.w(TAG, "Failed to restorecon");
16252                return false;
16253            }
16254
16255            // Reflect the rename internally
16256            codeFile = afterCodeFile;
16257            resourceFile = afterCodeFile;
16258
16259            // Reflect the rename in scanned details
16260            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16261            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16262                    afterCodeFile, pkg.baseCodePath));
16263            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16264                    afterCodeFile, pkg.splitCodePaths));
16265
16266            // Reflect the rename in app info
16267            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16268            pkg.setApplicationInfoCodePath(pkg.codePath);
16269            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16270            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16271            pkg.setApplicationInfoResourcePath(pkg.codePath);
16272            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16273            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16274
16275            return true;
16276        }
16277
16278        int doPostInstall(int status, int uid) {
16279            if (status != PackageManager.INSTALL_SUCCEEDED) {
16280                cleanUp();
16281            }
16282            return status;
16283        }
16284
16285        @Override
16286        String getCodePath() {
16287            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16288        }
16289
16290        @Override
16291        String getResourcePath() {
16292            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16293        }
16294
16295        private boolean cleanUp() {
16296            if (codeFile == null || !codeFile.exists()) {
16297                return false;
16298            }
16299
16300            removeCodePathLI(codeFile);
16301
16302            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16303                resourceFile.delete();
16304            }
16305
16306            return true;
16307        }
16308
16309        void cleanUpResourcesLI() {
16310            // Try enumerating all code paths before deleting
16311            List<String> allCodePaths = Collections.EMPTY_LIST;
16312            if (codeFile != null && codeFile.exists()) {
16313                try {
16314                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16315                    allCodePaths = pkg.getAllCodePaths();
16316                } catch (PackageParserException e) {
16317                    // Ignored; we tried our best
16318                }
16319            }
16320
16321            cleanUp();
16322            removeDexFiles(allCodePaths, instructionSets);
16323        }
16324
16325        boolean doPostDeleteLI(boolean delete) {
16326            // XXX err, shouldn't we respect the delete flag?
16327            cleanUpResourcesLI();
16328            return true;
16329        }
16330    }
16331
16332    private boolean isAsecExternal(String cid) {
16333        final String asecPath = PackageHelper.getSdFilesystem(cid);
16334        return !asecPath.startsWith(mAsecInternalPath);
16335    }
16336
16337    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16338            PackageManagerException {
16339        if (copyRet < 0) {
16340            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16341                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16342                throw new PackageManagerException(copyRet, message);
16343            }
16344        }
16345    }
16346
16347    /**
16348     * Extract the StorageManagerService "container ID" from the full code path of an
16349     * .apk.
16350     */
16351    static String cidFromCodePath(String fullCodePath) {
16352        int eidx = fullCodePath.lastIndexOf("/");
16353        String subStr1 = fullCodePath.substring(0, eidx);
16354        int sidx = subStr1.lastIndexOf("/");
16355        return subStr1.substring(sidx+1, eidx);
16356    }
16357
16358    /**
16359     * Logic to handle installation of ASEC applications, including copying and
16360     * renaming logic.
16361     */
16362    class AsecInstallArgs extends InstallArgs {
16363        static final String RES_FILE_NAME = "pkg.apk";
16364        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16365
16366        String cid;
16367        String packagePath;
16368        String resourcePath;
16369
16370        /** New install */
16371        AsecInstallArgs(InstallParams params) {
16372            super(params.origin, params.move, params.observer, params.installFlags,
16373                    params.installerPackageName, params.volumeUuid,
16374                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16375                    params.grantedRuntimePermissions,
16376                    params.traceMethod, params.traceCookie, params.certificates,
16377                    params.installReason);
16378        }
16379
16380        /** Existing install */
16381        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16382                        boolean isExternal, boolean isForwardLocked) {
16383            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16384                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16385                    instructionSets, null, null, null, 0, null /*certificates*/,
16386                    PackageManager.INSTALL_REASON_UNKNOWN);
16387            // Hackily pretend we're still looking at a full code path
16388            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16389                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16390            }
16391
16392            // Extract cid from fullCodePath
16393            int eidx = fullCodePath.lastIndexOf("/");
16394            String subStr1 = fullCodePath.substring(0, eidx);
16395            int sidx = subStr1.lastIndexOf("/");
16396            cid = subStr1.substring(sidx+1, eidx);
16397            setMountPath(subStr1);
16398        }
16399
16400        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16401            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16402                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16403                    instructionSets, null, null, null, 0, null /*certificates*/,
16404                    PackageManager.INSTALL_REASON_UNKNOWN);
16405            this.cid = cid;
16406            setMountPath(PackageHelper.getSdDir(cid));
16407        }
16408
16409        void createCopyFile() {
16410            cid = mInstallerService.allocateExternalStageCidLegacy();
16411        }
16412
16413        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16414            if (origin.staged && origin.cid != null) {
16415                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16416                cid = origin.cid;
16417                setMountPath(PackageHelper.getSdDir(cid));
16418                return PackageManager.INSTALL_SUCCEEDED;
16419            }
16420
16421            if (temp) {
16422                createCopyFile();
16423            } else {
16424                /*
16425                 * Pre-emptively destroy the container since it's destroyed if
16426                 * copying fails due to it existing anyway.
16427                 */
16428                PackageHelper.destroySdDir(cid);
16429            }
16430
16431            final String newMountPath = imcs.copyPackageToContainer(
16432                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16433                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16434
16435            if (newMountPath != null) {
16436                setMountPath(newMountPath);
16437                return PackageManager.INSTALL_SUCCEEDED;
16438            } else {
16439                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16440            }
16441        }
16442
16443        @Override
16444        String getCodePath() {
16445            return packagePath;
16446        }
16447
16448        @Override
16449        String getResourcePath() {
16450            return resourcePath;
16451        }
16452
16453        int doPreInstall(int status) {
16454            if (status != PackageManager.INSTALL_SUCCEEDED) {
16455                // Destroy container
16456                PackageHelper.destroySdDir(cid);
16457            } else {
16458                boolean mounted = PackageHelper.isContainerMounted(cid);
16459                if (!mounted) {
16460                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16461                            Process.SYSTEM_UID);
16462                    if (newMountPath != null) {
16463                        setMountPath(newMountPath);
16464                    } else {
16465                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16466                    }
16467                }
16468            }
16469            return status;
16470        }
16471
16472        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16473            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16474            String newMountPath = null;
16475            if (PackageHelper.isContainerMounted(cid)) {
16476                // Unmount the container
16477                if (!PackageHelper.unMountSdDir(cid)) {
16478                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16479                    return false;
16480                }
16481            }
16482            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16483                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16484                        " which might be stale. Will try to clean up.");
16485                // Clean up the stale container and proceed to recreate.
16486                if (!PackageHelper.destroySdDir(newCacheId)) {
16487                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16488                    return false;
16489                }
16490                // Successfully cleaned up stale container. Try to rename again.
16491                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16492                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16493                            + " inspite of cleaning it up.");
16494                    return false;
16495                }
16496            }
16497            if (!PackageHelper.isContainerMounted(newCacheId)) {
16498                Slog.w(TAG, "Mounting container " + newCacheId);
16499                newMountPath = PackageHelper.mountSdDir(newCacheId,
16500                        getEncryptKey(), Process.SYSTEM_UID);
16501            } else {
16502                newMountPath = PackageHelper.getSdDir(newCacheId);
16503            }
16504            if (newMountPath == null) {
16505                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16506                return false;
16507            }
16508            Log.i(TAG, "Succesfully renamed " + cid +
16509                    " to " + newCacheId +
16510                    " at new path: " + newMountPath);
16511            cid = newCacheId;
16512
16513            final File beforeCodeFile = new File(packagePath);
16514            setMountPath(newMountPath);
16515            final File afterCodeFile = new File(packagePath);
16516
16517            // Reflect the rename in scanned details
16518            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16519            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16520                    afterCodeFile, pkg.baseCodePath));
16521            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16522                    afterCodeFile, pkg.splitCodePaths));
16523
16524            // Reflect the rename in app info
16525            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16526            pkg.setApplicationInfoCodePath(pkg.codePath);
16527            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16528            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16529            pkg.setApplicationInfoResourcePath(pkg.codePath);
16530            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16531            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16532
16533            return true;
16534        }
16535
16536        private void setMountPath(String mountPath) {
16537            final File mountFile = new File(mountPath);
16538
16539            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16540            if (monolithicFile.exists()) {
16541                packagePath = monolithicFile.getAbsolutePath();
16542                if (isFwdLocked()) {
16543                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16544                } else {
16545                    resourcePath = packagePath;
16546                }
16547            } else {
16548                packagePath = mountFile.getAbsolutePath();
16549                resourcePath = packagePath;
16550            }
16551        }
16552
16553        int doPostInstall(int status, int uid) {
16554            if (status != PackageManager.INSTALL_SUCCEEDED) {
16555                cleanUp();
16556            } else {
16557                final int groupOwner;
16558                final String protectedFile;
16559                if (isFwdLocked()) {
16560                    groupOwner = UserHandle.getSharedAppGid(uid);
16561                    protectedFile = RES_FILE_NAME;
16562                } else {
16563                    groupOwner = -1;
16564                    protectedFile = null;
16565                }
16566
16567                if (uid < Process.FIRST_APPLICATION_UID
16568                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16569                    Slog.e(TAG, "Failed to finalize " + cid);
16570                    PackageHelper.destroySdDir(cid);
16571                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16572                }
16573
16574                boolean mounted = PackageHelper.isContainerMounted(cid);
16575                if (!mounted) {
16576                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16577                }
16578            }
16579            return status;
16580        }
16581
16582        private void cleanUp() {
16583            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16584
16585            // Destroy secure container
16586            PackageHelper.destroySdDir(cid);
16587        }
16588
16589        private List<String> getAllCodePaths() {
16590            final File codeFile = new File(getCodePath());
16591            if (codeFile != null && codeFile.exists()) {
16592                try {
16593                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16594                    return pkg.getAllCodePaths();
16595                } catch (PackageParserException e) {
16596                    // Ignored; we tried our best
16597                }
16598            }
16599            return Collections.EMPTY_LIST;
16600        }
16601
16602        void cleanUpResourcesLI() {
16603            // Enumerate all code paths before deleting
16604            cleanUpResourcesLI(getAllCodePaths());
16605        }
16606
16607        private void cleanUpResourcesLI(List<String> allCodePaths) {
16608            cleanUp();
16609            removeDexFiles(allCodePaths, instructionSets);
16610        }
16611
16612        String getPackageName() {
16613            return getAsecPackageName(cid);
16614        }
16615
16616        boolean doPostDeleteLI(boolean delete) {
16617            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16618            final List<String> allCodePaths = getAllCodePaths();
16619            boolean mounted = PackageHelper.isContainerMounted(cid);
16620            if (mounted) {
16621                // Unmount first
16622                if (PackageHelper.unMountSdDir(cid)) {
16623                    mounted = false;
16624                }
16625            }
16626            if (!mounted && delete) {
16627                cleanUpResourcesLI(allCodePaths);
16628            }
16629            return !mounted;
16630        }
16631
16632        @Override
16633        int doPreCopy() {
16634            if (isFwdLocked()) {
16635                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16636                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16637                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16638                }
16639            }
16640
16641            return PackageManager.INSTALL_SUCCEEDED;
16642        }
16643
16644        @Override
16645        int doPostCopy(int uid) {
16646            if (isFwdLocked()) {
16647                if (uid < Process.FIRST_APPLICATION_UID
16648                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16649                                RES_FILE_NAME)) {
16650                    Slog.e(TAG, "Failed to finalize " + cid);
16651                    PackageHelper.destroySdDir(cid);
16652                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16653                }
16654            }
16655
16656            return PackageManager.INSTALL_SUCCEEDED;
16657        }
16658    }
16659
16660    /**
16661     * Logic to handle movement of existing installed applications.
16662     */
16663    class MoveInstallArgs extends InstallArgs {
16664        private File codeFile;
16665        private File resourceFile;
16666
16667        /** New install */
16668        MoveInstallArgs(InstallParams params) {
16669            super(params.origin, params.move, params.observer, params.installFlags,
16670                    params.installerPackageName, params.volumeUuid,
16671                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16672                    params.grantedRuntimePermissions,
16673                    params.traceMethod, params.traceCookie, params.certificates,
16674                    params.installReason);
16675        }
16676
16677        int copyApk(IMediaContainerService imcs, boolean temp) {
16678            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16679                    + move.fromUuid + " to " + move.toUuid);
16680            synchronized (mInstaller) {
16681                try {
16682                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16683                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16684                } catch (InstallerException e) {
16685                    Slog.w(TAG, "Failed to move app", e);
16686                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16687                }
16688            }
16689
16690            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16691            resourceFile = codeFile;
16692            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16693
16694            return PackageManager.INSTALL_SUCCEEDED;
16695        }
16696
16697        int doPreInstall(int status) {
16698            if (status != PackageManager.INSTALL_SUCCEEDED) {
16699                cleanUp(move.toUuid);
16700            }
16701            return status;
16702        }
16703
16704        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16705            if (status != PackageManager.INSTALL_SUCCEEDED) {
16706                cleanUp(move.toUuid);
16707                return false;
16708            }
16709
16710            // Reflect the move in app info
16711            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16712            pkg.setApplicationInfoCodePath(pkg.codePath);
16713            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16714            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16715            pkg.setApplicationInfoResourcePath(pkg.codePath);
16716            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16717            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16718
16719            return true;
16720        }
16721
16722        int doPostInstall(int status, int uid) {
16723            if (status == PackageManager.INSTALL_SUCCEEDED) {
16724                cleanUp(move.fromUuid);
16725            } else {
16726                cleanUp(move.toUuid);
16727            }
16728            return status;
16729        }
16730
16731        @Override
16732        String getCodePath() {
16733            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16734        }
16735
16736        @Override
16737        String getResourcePath() {
16738            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16739        }
16740
16741        private boolean cleanUp(String volumeUuid) {
16742            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16743                    move.dataAppName);
16744            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16745            final int[] userIds = sUserManager.getUserIds();
16746            synchronized (mInstallLock) {
16747                // Clean up both app data and code
16748                // All package moves are frozen until finished
16749                for (int userId : userIds) {
16750                    try {
16751                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16752                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16753                    } catch (InstallerException e) {
16754                        Slog.w(TAG, String.valueOf(e));
16755                    }
16756                }
16757                removeCodePathLI(codeFile);
16758            }
16759            return true;
16760        }
16761
16762        void cleanUpResourcesLI() {
16763            throw new UnsupportedOperationException();
16764        }
16765
16766        boolean doPostDeleteLI(boolean delete) {
16767            throw new UnsupportedOperationException();
16768        }
16769    }
16770
16771    static String getAsecPackageName(String packageCid) {
16772        int idx = packageCid.lastIndexOf("-");
16773        if (idx == -1) {
16774            return packageCid;
16775        }
16776        return packageCid.substring(0, idx);
16777    }
16778
16779    // Utility method used to create code paths based on package name and available index.
16780    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16781        String idxStr = "";
16782        int idx = 1;
16783        // Fall back to default value of idx=1 if prefix is not
16784        // part of oldCodePath
16785        if (oldCodePath != null) {
16786            String subStr = oldCodePath;
16787            // Drop the suffix right away
16788            if (suffix != null && subStr.endsWith(suffix)) {
16789                subStr = subStr.substring(0, subStr.length() - suffix.length());
16790            }
16791            // If oldCodePath already contains prefix find out the
16792            // ending index to either increment or decrement.
16793            int sidx = subStr.lastIndexOf(prefix);
16794            if (sidx != -1) {
16795                subStr = subStr.substring(sidx + prefix.length());
16796                if (subStr != null) {
16797                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16798                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16799                    }
16800                    try {
16801                        idx = Integer.parseInt(subStr);
16802                        if (idx <= 1) {
16803                            idx++;
16804                        } else {
16805                            idx--;
16806                        }
16807                    } catch(NumberFormatException e) {
16808                    }
16809                }
16810            }
16811        }
16812        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16813        return prefix + idxStr;
16814    }
16815
16816    private File getNextCodePath(File targetDir, String packageName) {
16817        File result;
16818        SecureRandom random = new SecureRandom();
16819        byte[] bytes = new byte[16];
16820        do {
16821            random.nextBytes(bytes);
16822            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16823            result = new File(targetDir, packageName + "-" + suffix);
16824        } while (result.exists());
16825        return result;
16826    }
16827
16828    // Utility method that returns the relative package path with respect
16829    // to the installation directory. Like say for /data/data/com.test-1.apk
16830    // string com.test-1 is returned.
16831    static String deriveCodePathName(String codePath) {
16832        if (codePath == null) {
16833            return null;
16834        }
16835        final File codeFile = new File(codePath);
16836        final String name = codeFile.getName();
16837        if (codeFile.isDirectory()) {
16838            return name;
16839        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16840            final int lastDot = name.lastIndexOf('.');
16841            return name.substring(0, lastDot);
16842        } else {
16843            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16844            return null;
16845        }
16846    }
16847
16848    static class PackageInstalledInfo {
16849        String name;
16850        int uid;
16851        // The set of users that originally had this package installed.
16852        int[] origUsers;
16853        // The set of users that now have this package installed.
16854        int[] newUsers;
16855        PackageParser.Package pkg;
16856        int returnCode;
16857        String returnMsg;
16858        PackageRemovedInfo removedInfo;
16859        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16860
16861        public void setError(int code, String msg) {
16862            setReturnCode(code);
16863            setReturnMessage(msg);
16864            Slog.w(TAG, msg);
16865        }
16866
16867        public void setError(String msg, PackageParserException e) {
16868            setReturnCode(e.error);
16869            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16870            Slog.w(TAG, msg, e);
16871        }
16872
16873        public void setError(String msg, PackageManagerException e) {
16874            returnCode = e.error;
16875            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16876            Slog.w(TAG, msg, e);
16877        }
16878
16879        public void setReturnCode(int returnCode) {
16880            this.returnCode = returnCode;
16881            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16882            for (int i = 0; i < childCount; i++) {
16883                addedChildPackages.valueAt(i).returnCode = returnCode;
16884            }
16885        }
16886
16887        private void setReturnMessage(String returnMsg) {
16888            this.returnMsg = returnMsg;
16889            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16890            for (int i = 0; i < childCount; i++) {
16891                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16892            }
16893        }
16894
16895        // In some error cases we want to convey more info back to the observer
16896        String origPackage;
16897        String origPermission;
16898    }
16899
16900    /*
16901     * Install a non-existing package.
16902     */
16903    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16904            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16905            PackageInstalledInfo res, int installReason) {
16906        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16907
16908        // Remember this for later, in case we need to rollback this install
16909        String pkgName = pkg.packageName;
16910
16911        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16912
16913        synchronized(mPackages) {
16914            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16915            if (renamedPackage != null) {
16916                // A package with the same name is already installed, though
16917                // it has been renamed to an older name.  The package we
16918                // are trying to install should be installed as an update to
16919                // the existing one, but that has not been requested, so bail.
16920                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16921                        + " without first uninstalling package running as "
16922                        + renamedPackage);
16923                return;
16924            }
16925            if (mPackages.containsKey(pkgName)) {
16926                // Don't allow installation over an existing package with the same name.
16927                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16928                        + " without first uninstalling.");
16929                return;
16930            }
16931        }
16932
16933        try {
16934            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16935                    System.currentTimeMillis(), user);
16936
16937            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16938
16939            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16940                prepareAppDataAfterInstallLIF(newPackage);
16941
16942            } else {
16943                // Remove package from internal structures, but keep around any
16944                // data that might have already existed
16945                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16946                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16947            }
16948        } catch (PackageManagerException e) {
16949            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16950        }
16951
16952        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16953    }
16954
16955    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16956        // Can't rotate keys during boot or if sharedUser.
16957        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
16958                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16959            return false;
16960        }
16961        // app is using upgradeKeySets; make sure all are valid
16962        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16963        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16964        for (int i = 0; i < upgradeKeySets.length; i++) {
16965            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16966                Slog.wtf(TAG, "Package "
16967                         + (oldPs.name != null ? oldPs.name : "<null>")
16968                         + " contains upgrade-key-set reference to unknown key-set: "
16969                         + upgradeKeySets[i]
16970                         + " reverting to signatures check.");
16971                return false;
16972            }
16973        }
16974        return true;
16975    }
16976
16977    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
16978        // Upgrade keysets are being used.  Determine if new package has a superset of the
16979        // required keys.
16980        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16981        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16982        for (int i = 0; i < upgradeKeySets.length; i++) {
16983            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16984            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16985                return true;
16986            }
16987        }
16988        return false;
16989    }
16990
16991    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16992        try (DigestInputStream digestStream =
16993                new DigestInputStream(new FileInputStream(file), digest)) {
16994            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16995        }
16996    }
16997
16998    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16999            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17000            int installReason) {
17001        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17002
17003        final PackageParser.Package oldPackage;
17004        final PackageSetting ps;
17005        final String pkgName = pkg.packageName;
17006        final int[] allUsers;
17007        final int[] installedUsers;
17008
17009        synchronized(mPackages) {
17010            oldPackage = mPackages.get(pkgName);
17011            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17012
17013            // don't allow upgrade to target a release SDK from a pre-release SDK
17014            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17015                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17016            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17017                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17018            if (oldTargetsPreRelease
17019                    && !newTargetsPreRelease
17020                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17021                Slog.w(TAG, "Can't install package targeting released sdk");
17022                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17023                return;
17024            }
17025
17026            ps = mSettings.mPackages.get(pkgName);
17027
17028            // verify signatures are valid
17029            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17030                if (!checkUpgradeKeySetLP(ps, pkg)) {
17031                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17032                            "New package not signed by keys specified by upgrade-keysets: "
17033                                    + pkgName);
17034                    return;
17035                }
17036            } else {
17037                // default to original signature matching
17038                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17039                        != PackageManager.SIGNATURE_MATCH) {
17040                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17041                            "New package has a different signature: " + pkgName);
17042                    return;
17043                }
17044            }
17045
17046            // don't allow a system upgrade unless the upgrade hash matches
17047            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17048                byte[] digestBytes = null;
17049                try {
17050                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17051                    updateDigest(digest, new File(pkg.baseCodePath));
17052                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17053                        for (String path : pkg.splitCodePaths) {
17054                            updateDigest(digest, new File(path));
17055                        }
17056                    }
17057                    digestBytes = digest.digest();
17058                } catch (NoSuchAlgorithmException | IOException e) {
17059                    res.setError(INSTALL_FAILED_INVALID_APK,
17060                            "Could not compute hash: " + pkgName);
17061                    return;
17062                }
17063                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17064                    res.setError(INSTALL_FAILED_INVALID_APK,
17065                            "New package fails restrict-update check: " + pkgName);
17066                    return;
17067                }
17068                // retain upgrade restriction
17069                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17070            }
17071
17072            // Check for shared user id changes
17073            String invalidPackageName =
17074                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17075            if (invalidPackageName != null) {
17076                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17077                        "Package " + invalidPackageName + " tried to change user "
17078                                + oldPackage.mSharedUserId);
17079                return;
17080            }
17081
17082            // In case of rollback, remember per-user/profile install state
17083            allUsers = sUserManager.getUserIds();
17084            installedUsers = ps.queryInstalledUsers(allUsers, true);
17085
17086            // don't allow an upgrade from full to ephemeral
17087            if (isInstantApp) {
17088                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17089                    for (int currentUser : allUsers) {
17090                        if (!ps.getInstantApp(currentUser)) {
17091                            // can't downgrade from full to instant
17092                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17093                                    + " for user: " + currentUser);
17094                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17095                            return;
17096                        }
17097                    }
17098                } else if (!ps.getInstantApp(user.getIdentifier())) {
17099                    // can't downgrade from full to instant
17100                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17101                            + " for user: " + user.getIdentifier());
17102                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17103                    return;
17104                }
17105            }
17106        }
17107
17108        // Update what is removed
17109        res.removedInfo = new PackageRemovedInfo(this);
17110        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17111        res.removedInfo.removedPackage = oldPackage.packageName;
17112        res.removedInfo.installerPackageName = ps.installerPackageName;
17113        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17114        res.removedInfo.isUpdate = true;
17115        res.removedInfo.origUsers = installedUsers;
17116        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17117        for (int i = 0; i < installedUsers.length; i++) {
17118            final int userId = installedUsers[i];
17119            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17120        }
17121
17122        final int childCount = (oldPackage.childPackages != null)
17123                ? oldPackage.childPackages.size() : 0;
17124        for (int i = 0; i < childCount; i++) {
17125            boolean childPackageUpdated = false;
17126            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17127            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17128            if (res.addedChildPackages != null) {
17129                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17130                if (childRes != null) {
17131                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17132                    childRes.removedInfo.removedPackage = childPkg.packageName;
17133                    if (childPs != null) {
17134                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17135                    }
17136                    childRes.removedInfo.isUpdate = true;
17137                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17138                    childPackageUpdated = true;
17139                }
17140            }
17141            if (!childPackageUpdated) {
17142                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17143                childRemovedRes.removedPackage = childPkg.packageName;
17144                if (childPs != null) {
17145                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17146                }
17147                childRemovedRes.isUpdate = false;
17148                childRemovedRes.dataRemoved = true;
17149                synchronized (mPackages) {
17150                    if (childPs != null) {
17151                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17152                    }
17153                }
17154                if (res.removedInfo.removedChildPackages == null) {
17155                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17156                }
17157                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17158            }
17159        }
17160
17161        boolean sysPkg = (isSystemApp(oldPackage));
17162        if (sysPkg) {
17163            // Set the system/privileged flags as needed
17164            final boolean privileged =
17165                    (oldPackage.applicationInfo.privateFlags
17166                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17167            final int systemPolicyFlags = policyFlags
17168                    | PackageParser.PARSE_IS_SYSTEM
17169                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17170
17171            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17172                    user, allUsers, installerPackageName, res, installReason);
17173        } else {
17174            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17175                    user, allUsers, installerPackageName, res, installReason);
17176        }
17177    }
17178
17179    @Override
17180    public List<String> getPreviousCodePaths(String packageName) {
17181        final int callingUid = Binder.getCallingUid();
17182        final List<String> result = new ArrayList<>();
17183        if (getInstantAppPackageName(callingUid) != null) {
17184            return result;
17185        }
17186        final PackageSetting ps = mSettings.mPackages.get(packageName);
17187        if (ps != null
17188                && ps.oldCodePaths != null
17189                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17190            result.addAll(ps.oldCodePaths);
17191        }
17192        return result;
17193    }
17194
17195    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17196            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17197            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17198            int installReason) {
17199        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17200                + deletedPackage);
17201
17202        String pkgName = deletedPackage.packageName;
17203        boolean deletedPkg = true;
17204        boolean addedPkg = false;
17205        boolean updatedSettings = false;
17206        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17207        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17208                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17209
17210        final long origUpdateTime = (pkg.mExtras != null)
17211                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17212
17213        // First delete the existing package while retaining the data directory
17214        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17215                res.removedInfo, true, pkg)) {
17216            // If the existing package wasn't successfully deleted
17217            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17218            deletedPkg = false;
17219        } else {
17220            // Successfully deleted the old package; proceed with replace.
17221
17222            // If deleted package lived in a container, give users a chance to
17223            // relinquish resources before killing.
17224            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17225                if (DEBUG_INSTALL) {
17226                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17227                }
17228                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17229                final ArrayList<String> pkgList = new ArrayList<String>(1);
17230                pkgList.add(deletedPackage.applicationInfo.packageName);
17231                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17232            }
17233
17234            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17235                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17236            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17237
17238            try {
17239                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17240                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17241                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17242                        installReason);
17243
17244                // Update the in-memory copy of the previous code paths.
17245                PackageSetting ps = mSettings.mPackages.get(pkgName);
17246                if (!killApp) {
17247                    if (ps.oldCodePaths == null) {
17248                        ps.oldCodePaths = new ArraySet<>();
17249                    }
17250                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17251                    if (deletedPackage.splitCodePaths != null) {
17252                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17253                    }
17254                } else {
17255                    ps.oldCodePaths = null;
17256                }
17257                if (ps.childPackageNames != null) {
17258                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17259                        final String childPkgName = ps.childPackageNames.get(i);
17260                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17261                        childPs.oldCodePaths = ps.oldCodePaths;
17262                    }
17263                }
17264                // set instant app status, but, only if it's explicitly specified
17265                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17266                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17267                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17268                prepareAppDataAfterInstallLIF(newPackage);
17269                addedPkg = true;
17270                mDexManager.notifyPackageUpdated(newPackage.packageName,
17271                        newPackage.baseCodePath, newPackage.splitCodePaths);
17272            } catch (PackageManagerException e) {
17273                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17274            }
17275        }
17276
17277        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17278            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17279
17280            // Revert all internal state mutations and added folders for the failed install
17281            if (addedPkg) {
17282                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17283                        res.removedInfo, true, null);
17284            }
17285
17286            // Restore the old package
17287            if (deletedPkg) {
17288                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17289                File restoreFile = new File(deletedPackage.codePath);
17290                // Parse old package
17291                boolean oldExternal = isExternal(deletedPackage);
17292                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17293                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17294                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17295                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17296                try {
17297                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17298                            null);
17299                } catch (PackageManagerException e) {
17300                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17301                            + e.getMessage());
17302                    return;
17303                }
17304
17305                synchronized (mPackages) {
17306                    // Ensure the installer package name up to date
17307                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17308
17309                    // Update permissions for restored package
17310                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17311
17312                    mSettings.writeLPr();
17313                }
17314
17315                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17316            }
17317        } else {
17318            synchronized (mPackages) {
17319                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17320                if (ps != null) {
17321                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17322                    if (res.removedInfo.removedChildPackages != null) {
17323                        final int childCount = res.removedInfo.removedChildPackages.size();
17324                        // Iterate in reverse as we may modify the collection
17325                        for (int i = childCount - 1; i >= 0; i--) {
17326                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17327                            if (res.addedChildPackages.containsKey(childPackageName)) {
17328                                res.removedInfo.removedChildPackages.removeAt(i);
17329                            } else {
17330                                PackageRemovedInfo childInfo = res.removedInfo
17331                                        .removedChildPackages.valueAt(i);
17332                                childInfo.removedForAllUsers = mPackages.get(
17333                                        childInfo.removedPackage) == null;
17334                            }
17335                        }
17336                    }
17337                }
17338            }
17339        }
17340    }
17341
17342    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17343            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17344            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17345            int installReason) {
17346        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17347                + ", old=" + deletedPackage);
17348
17349        final boolean disabledSystem;
17350
17351        // Remove existing system package
17352        removePackageLI(deletedPackage, true);
17353
17354        synchronized (mPackages) {
17355            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17356        }
17357        if (!disabledSystem) {
17358            // We didn't need to disable the .apk as a current system package,
17359            // which means we are replacing another update that is already
17360            // installed.  We need to make sure to delete the older one's .apk.
17361            res.removedInfo.args = createInstallArgsForExisting(0,
17362                    deletedPackage.applicationInfo.getCodePath(),
17363                    deletedPackage.applicationInfo.getResourcePath(),
17364                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17365        } else {
17366            res.removedInfo.args = null;
17367        }
17368
17369        // Successfully disabled the old package. Now proceed with re-installation
17370        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17371                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17372        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17373
17374        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17375        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17376                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17377
17378        PackageParser.Package newPackage = null;
17379        try {
17380            // Add the package to the internal data structures
17381            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17382
17383            // Set the update and install times
17384            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17385            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17386                    System.currentTimeMillis());
17387
17388            // Update the package dynamic state if succeeded
17389            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17390                // Now that the install succeeded make sure we remove data
17391                // directories for any child package the update removed.
17392                final int deletedChildCount = (deletedPackage.childPackages != null)
17393                        ? deletedPackage.childPackages.size() : 0;
17394                final int newChildCount = (newPackage.childPackages != null)
17395                        ? newPackage.childPackages.size() : 0;
17396                for (int i = 0; i < deletedChildCount; i++) {
17397                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17398                    boolean childPackageDeleted = true;
17399                    for (int j = 0; j < newChildCount; j++) {
17400                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17401                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17402                            childPackageDeleted = false;
17403                            break;
17404                        }
17405                    }
17406                    if (childPackageDeleted) {
17407                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17408                                deletedChildPkg.packageName);
17409                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17410                            PackageRemovedInfo removedChildRes = res.removedInfo
17411                                    .removedChildPackages.get(deletedChildPkg.packageName);
17412                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17413                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17414                        }
17415                    }
17416                }
17417
17418                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17419                        installReason);
17420                prepareAppDataAfterInstallLIF(newPackage);
17421
17422                mDexManager.notifyPackageUpdated(newPackage.packageName,
17423                            newPackage.baseCodePath, newPackage.splitCodePaths);
17424            }
17425        } catch (PackageManagerException e) {
17426            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17427            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17428        }
17429
17430        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17431            // Re installation failed. Restore old information
17432            // Remove new pkg information
17433            if (newPackage != null) {
17434                removeInstalledPackageLI(newPackage, true);
17435            }
17436            // Add back the old system package
17437            try {
17438                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17439            } catch (PackageManagerException e) {
17440                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17441            }
17442
17443            synchronized (mPackages) {
17444                if (disabledSystem) {
17445                    enableSystemPackageLPw(deletedPackage);
17446                }
17447
17448                // Ensure the installer package name up to date
17449                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17450
17451                // Update permissions for restored package
17452                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17453
17454                mSettings.writeLPr();
17455            }
17456
17457            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17458                    + " after failed upgrade");
17459        }
17460    }
17461
17462    /**
17463     * Checks whether the parent or any of the child packages have a change shared
17464     * user. For a package to be a valid update the shred users of the parent and
17465     * the children should match. We may later support changing child shared users.
17466     * @param oldPkg The updated package.
17467     * @param newPkg The update package.
17468     * @return The shared user that change between the versions.
17469     */
17470    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17471            PackageParser.Package newPkg) {
17472        // Check parent shared user
17473        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17474            return newPkg.packageName;
17475        }
17476        // Check child shared users
17477        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17478        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17479        for (int i = 0; i < newChildCount; i++) {
17480            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17481            // If this child was present, did it have the same shared user?
17482            for (int j = 0; j < oldChildCount; j++) {
17483                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17484                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17485                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17486                    return newChildPkg.packageName;
17487                }
17488            }
17489        }
17490        return null;
17491    }
17492
17493    private void removeNativeBinariesLI(PackageSetting ps) {
17494        // Remove the lib path for the parent package
17495        if (ps != null) {
17496            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17497            // Remove the lib path for the child packages
17498            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17499            for (int i = 0; i < childCount; i++) {
17500                PackageSetting childPs = null;
17501                synchronized (mPackages) {
17502                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17503                }
17504                if (childPs != null) {
17505                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17506                            .legacyNativeLibraryPathString);
17507                }
17508            }
17509        }
17510    }
17511
17512    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17513        // Enable the parent package
17514        mSettings.enableSystemPackageLPw(pkg.packageName);
17515        // Enable the child packages
17516        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17517        for (int i = 0; i < childCount; i++) {
17518            PackageParser.Package childPkg = pkg.childPackages.get(i);
17519            mSettings.enableSystemPackageLPw(childPkg.packageName);
17520        }
17521    }
17522
17523    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17524            PackageParser.Package newPkg) {
17525        // Disable the parent package (parent always replaced)
17526        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17527        // Disable the child packages
17528        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17529        for (int i = 0; i < childCount; i++) {
17530            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17531            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17532            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17533        }
17534        return disabled;
17535    }
17536
17537    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17538            String installerPackageName) {
17539        // Enable the parent package
17540        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17541        // Enable the child packages
17542        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17543        for (int i = 0; i < childCount; i++) {
17544            PackageParser.Package childPkg = pkg.childPackages.get(i);
17545            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17546        }
17547    }
17548
17549    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17550        // Collect all used permissions in the UID
17551        ArraySet<String> usedPermissions = new ArraySet<>();
17552        final int packageCount = su.packages.size();
17553        for (int i = 0; i < packageCount; i++) {
17554            PackageSetting ps = su.packages.valueAt(i);
17555            if (ps.pkg == null) {
17556                continue;
17557            }
17558            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17559            for (int j = 0; j < requestedPermCount; j++) {
17560                String permission = ps.pkg.requestedPermissions.get(j);
17561                BasePermission bp = mSettings.mPermissions.get(permission);
17562                if (bp != null) {
17563                    usedPermissions.add(permission);
17564                }
17565            }
17566        }
17567
17568        PermissionsState permissionsState = su.getPermissionsState();
17569        // Prune install permissions
17570        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17571        final int installPermCount = installPermStates.size();
17572        for (int i = installPermCount - 1; i >= 0;  i--) {
17573            PermissionState permissionState = installPermStates.get(i);
17574            if (!usedPermissions.contains(permissionState.getName())) {
17575                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17576                if (bp != null) {
17577                    permissionsState.revokeInstallPermission(bp);
17578                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17579                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17580                }
17581            }
17582        }
17583
17584        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17585
17586        // Prune runtime permissions
17587        for (int userId : allUserIds) {
17588            List<PermissionState> runtimePermStates = permissionsState
17589                    .getRuntimePermissionStates(userId);
17590            final int runtimePermCount = runtimePermStates.size();
17591            for (int i = runtimePermCount - 1; i >= 0; i--) {
17592                PermissionState permissionState = runtimePermStates.get(i);
17593                if (!usedPermissions.contains(permissionState.getName())) {
17594                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17595                    if (bp != null) {
17596                        permissionsState.revokeRuntimePermission(bp, userId);
17597                        permissionsState.updatePermissionFlags(bp, userId,
17598                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17599                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17600                                runtimePermissionChangedUserIds, userId);
17601                    }
17602                }
17603            }
17604        }
17605
17606        return runtimePermissionChangedUserIds;
17607    }
17608
17609    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17610            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17611        // Update the parent package setting
17612        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17613                res, user, installReason);
17614        // Update the child packages setting
17615        final int childCount = (newPackage.childPackages != null)
17616                ? newPackage.childPackages.size() : 0;
17617        for (int i = 0; i < childCount; i++) {
17618            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17619            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17620            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17621                    childRes.origUsers, childRes, user, installReason);
17622        }
17623    }
17624
17625    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17626            String installerPackageName, int[] allUsers, int[] installedForUsers,
17627            PackageInstalledInfo res, UserHandle user, int installReason) {
17628        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17629
17630        String pkgName = newPackage.packageName;
17631        synchronized (mPackages) {
17632            //write settings. the installStatus will be incomplete at this stage.
17633            //note that the new package setting would have already been
17634            //added to mPackages. It hasn't been persisted yet.
17635            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17636            // TODO: Remove this write? It's also written at the end of this method
17637            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17638            mSettings.writeLPr();
17639            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17640        }
17641
17642        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17643        synchronized (mPackages) {
17644            updatePermissionsLPw(newPackage.packageName, newPackage,
17645                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17646                            ? UPDATE_PERMISSIONS_ALL : 0));
17647            // For system-bundled packages, we assume that installing an upgraded version
17648            // of the package implies that the user actually wants to run that new code,
17649            // so we enable the package.
17650            PackageSetting ps = mSettings.mPackages.get(pkgName);
17651            final int userId = user.getIdentifier();
17652            if (ps != null) {
17653                if (isSystemApp(newPackage)) {
17654                    if (DEBUG_INSTALL) {
17655                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17656                    }
17657                    // Enable system package for requested users
17658                    if (res.origUsers != null) {
17659                        for (int origUserId : res.origUsers) {
17660                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17661                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17662                                        origUserId, installerPackageName);
17663                            }
17664                        }
17665                    }
17666                    // Also convey the prior install/uninstall state
17667                    if (allUsers != null && installedForUsers != null) {
17668                        for (int currentUserId : allUsers) {
17669                            final boolean installed = ArrayUtils.contains(
17670                                    installedForUsers, currentUserId);
17671                            if (DEBUG_INSTALL) {
17672                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17673                            }
17674                            ps.setInstalled(installed, currentUserId);
17675                        }
17676                        // these install state changes will be persisted in the
17677                        // upcoming call to mSettings.writeLPr().
17678                    }
17679                }
17680                // It's implied that when a user requests installation, they want the app to be
17681                // installed and enabled.
17682                if (userId != UserHandle.USER_ALL) {
17683                    ps.setInstalled(true, userId);
17684                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17685                }
17686
17687                // When replacing an existing package, preserve the original install reason for all
17688                // users that had the package installed before.
17689                final Set<Integer> previousUserIds = new ArraySet<>();
17690                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17691                    final int installReasonCount = res.removedInfo.installReasons.size();
17692                    for (int i = 0; i < installReasonCount; i++) {
17693                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17694                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17695                        ps.setInstallReason(previousInstallReason, previousUserId);
17696                        previousUserIds.add(previousUserId);
17697                    }
17698                }
17699
17700                // Set install reason for users that are having the package newly installed.
17701                if (userId == UserHandle.USER_ALL) {
17702                    for (int currentUserId : sUserManager.getUserIds()) {
17703                        if (!previousUserIds.contains(currentUserId)) {
17704                            ps.setInstallReason(installReason, currentUserId);
17705                        }
17706                    }
17707                } else if (!previousUserIds.contains(userId)) {
17708                    ps.setInstallReason(installReason, userId);
17709                }
17710                mSettings.writeKernelMappingLPr(ps);
17711            }
17712            res.name = pkgName;
17713            res.uid = newPackage.applicationInfo.uid;
17714            res.pkg = newPackage;
17715            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17716            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17717            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17718            //to update install status
17719            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17720            mSettings.writeLPr();
17721            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17722        }
17723
17724        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17725    }
17726
17727    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17728        try {
17729            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17730            installPackageLI(args, res);
17731        } finally {
17732            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17733        }
17734    }
17735
17736    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17737        final int installFlags = args.installFlags;
17738        final String installerPackageName = args.installerPackageName;
17739        final String volumeUuid = args.volumeUuid;
17740        final File tmpPackageFile = new File(args.getCodePath());
17741        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17742        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17743                || (args.volumeUuid != null));
17744        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17745        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17746        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17747        boolean replace = false;
17748        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17749        if (args.move != null) {
17750            // moving a complete application; perform an initial scan on the new install location
17751            scanFlags |= SCAN_INITIAL;
17752        }
17753        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17754            scanFlags |= SCAN_DONT_KILL_APP;
17755        }
17756        if (instantApp) {
17757            scanFlags |= SCAN_AS_INSTANT_APP;
17758        }
17759        if (fullApp) {
17760            scanFlags |= SCAN_AS_FULL_APP;
17761        }
17762
17763        // Result object to be returned
17764        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17765
17766        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17767
17768        // Sanity check
17769        if (instantApp && (forwardLocked || onExternal)) {
17770            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17771                    + " external=" + onExternal);
17772            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17773            return;
17774        }
17775
17776        // Retrieve PackageSettings and parse package
17777        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17778                | PackageParser.PARSE_ENFORCE_CODE
17779                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17780                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17781                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17782                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17783        PackageParser pp = new PackageParser();
17784        pp.setSeparateProcesses(mSeparateProcesses);
17785        pp.setDisplayMetrics(mMetrics);
17786        pp.setCallback(mPackageParserCallback);
17787
17788        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17789        final PackageParser.Package pkg;
17790        try {
17791            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17792        } catch (PackageParserException e) {
17793            res.setError("Failed parse during installPackageLI", e);
17794            return;
17795        } finally {
17796            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17797        }
17798
17799        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17800        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17801            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17802            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17803                    "Instant app package must target O");
17804            return;
17805        }
17806        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17807            Slog.w(TAG, "Instant app package " + pkg.packageName
17808                    + " does not target targetSandboxVersion 2");
17809            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17810                    "Instant app package must use targetSanboxVersion 2");
17811            return;
17812        }
17813
17814        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17815            // Static shared libraries have synthetic package names
17816            renameStaticSharedLibraryPackage(pkg);
17817
17818            // No static shared libs on external storage
17819            if (onExternal) {
17820                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17821                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17822                        "Packages declaring static-shared libs cannot be updated");
17823                return;
17824            }
17825        }
17826
17827        // If we are installing a clustered package add results for the children
17828        if (pkg.childPackages != null) {
17829            synchronized (mPackages) {
17830                final int childCount = pkg.childPackages.size();
17831                for (int i = 0; i < childCount; i++) {
17832                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17833                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17834                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17835                    childRes.pkg = childPkg;
17836                    childRes.name = childPkg.packageName;
17837                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17838                    if (childPs != null) {
17839                        childRes.origUsers = childPs.queryInstalledUsers(
17840                                sUserManager.getUserIds(), true);
17841                    }
17842                    if ((mPackages.containsKey(childPkg.packageName))) {
17843                        childRes.removedInfo = new PackageRemovedInfo(this);
17844                        childRes.removedInfo.removedPackage = childPkg.packageName;
17845                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17846                    }
17847                    if (res.addedChildPackages == null) {
17848                        res.addedChildPackages = new ArrayMap<>();
17849                    }
17850                    res.addedChildPackages.put(childPkg.packageName, childRes);
17851                }
17852            }
17853        }
17854
17855        // If package doesn't declare API override, mark that we have an install
17856        // time CPU ABI override.
17857        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17858            pkg.cpuAbiOverride = args.abiOverride;
17859        }
17860
17861        String pkgName = res.name = pkg.packageName;
17862        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17863            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17864                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17865                return;
17866            }
17867        }
17868
17869        try {
17870            // either use what we've been given or parse directly from the APK
17871            if (args.certificates != null) {
17872                try {
17873                    PackageParser.populateCertificates(pkg, args.certificates);
17874                } catch (PackageParserException e) {
17875                    // there was something wrong with the certificates we were given;
17876                    // try to pull them from the APK
17877                    PackageParser.collectCertificates(pkg, parseFlags);
17878                }
17879            } else {
17880                PackageParser.collectCertificates(pkg, parseFlags);
17881            }
17882        } catch (PackageParserException e) {
17883            res.setError("Failed collect during installPackageLI", e);
17884            return;
17885        }
17886
17887        // Get rid of all references to package scan path via parser.
17888        pp = null;
17889        String oldCodePath = null;
17890        boolean systemApp = false;
17891        synchronized (mPackages) {
17892            // Check if installing already existing package
17893            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17894                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17895                if (pkg.mOriginalPackages != null
17896                        && pkg.mOriginalPackages.contains(oldName)
17897                        && mPackages.containsKey(oldName)) {
17898                    // This package is derived from an original package,
17899                    // and this device has been updating from that original
17900                    // name.  We must continue using the original name, so
17901                    // rename the new package here.
17902                    pkg.setPackageName(oldName);
17903                    pkgName = pkg.packageName;
17904                    replace = true;
17905                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17906                            + oldName + " pkgName=" + pkgName);
17907                } else if (mPackages.containsKey(pkgName)) {
17908                    // This package, under its official name, already exists
17909                    // on the device; we should replace it.
17910                    replace = true;
17911                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17912                }
17913
17914                // Child packages are installed through the parent package
17915                if (pkg.parentPackage != null) {
17916                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17917                            "Package " + pkg.packageName + " is child of package "
17918                                    + pkg.parentPackage.parentPackage + ". Child packages "
17919                                    + "can be updated only through the parent package.");
17920                    return;
17921                }
17922
17923                if (replace) {
17924                    // Prevent apps opting out from runtime permissions
17925                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17926                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17927                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17928                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17929                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17930                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17931                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17932                                        + " doesn't support runtime permissions but the old"
17933                                        + " target SDK " + oldTargetSdk + " does.");
17934                        return;
17935                    }
17936                    // Prevent apps from downgrading their targetSandbox.
17937                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17938                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17939                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17940                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17941                                "Package " + pkg.packageName + " new target sandbox "
17942                                + newTargetSandbox + " is incompatible with the previous value of"
17943                                + oldTargetSandbox + ".");
17944                        return;
17945                    }
17946
17947                    // Prevent installing of child packages
17948                    if (oldPackage.parentPackage != null) {
17949                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17950                                "Package " + pkg.packageName + " is child of package "
17951                                        + oldPackage.parentPackage + ". Child packages "
17952                                        + "can be updated only through the parent package.");
17953                        return;
17954                    }
17955                }
17956            }
17957
17958            PackageSetting ps = mSettings.mPackages.get(pkgName);
17959            if (ps != null) {
17960                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17961
17962                // Static shared libs have same package with different versions where
17963                // we internally use a synthetic package name to allow multiple versions
17964                // of the same package, therefore we need to compare signatures against
17965                // the package setting for the latest library version.
17966                PackageSetting signatureCheckPs = ps;
17967                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17968                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17969                    if (libraryEntry != null) {
17970                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17971                    }
17972                }
17973
17974                // Quick sanity check that we're signed correctly if updating;
17975                // we'll check this again later when scanning, but we want to
17976                // bail early here before tripping over redefined permissions.
17977                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17978                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17979                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17980                                + pkg.packageName + " upgrade keys do not match the "
17981                                + "previously installed version");
17982                        return;
17983                    }
17984                } else {
17985                    try {
17986                        verifySignaturesLP(signatureCheckPs, pkg);
17987                    } catch (PackageManagerException e) {
17988                        res.setError(e.error, e.getMessage());
17989                        return;
17990                    }
17991                }
17992
17993                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17994                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17995                    systemApp = (ps.pkg.applicationInfo.flags &
17996                            ApplicationInfo.FLAG_SYSTEM) != 0;
17997                }
17998                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17999            }
18000
18001            int N = pkg.permissions.size();
18002            for (int i = N-1; i >= 0; i--) {
18003                PackageParser.Permission perm = pkg.permissions.get(i);
18004                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18005
18006                // Don't allow anyone but the system to define ephemeral permissions.
18007                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18008                        && !systemApp) {
18009                    Slog.w(TAG, "Non-System package " + pkg.packageName
18010                            + " attempting to delcare ephemeral permission "
18011                            + perm.info.name + "; Removing ephemeral.");
18012                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18013                }
18014                // Check whether the newly-scanned package wants to define an already-defined perm
18015                if (bp != null) {
18016                    // If the defining package is signed with our cert, it's okay.  This
18017                    // also includes the "updating the same package" case, of course.
18018                    // "updating same package" could also involve key-rotation.
18019                    final boolean sigsOk;
18020                    if (bp.sourcePackage.equals(pkg.packageName)
18021                            && (bp.packageSetting instanceof PackageSetting)
18022                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18023                                    scanFlags))) {
18024                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18025                    } else {
18026                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18027                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18028                    }
18029                    if (!sigsOk) {
18030                        // If the owning package is the system itself, we log but allow
18031                        // install to proceed; we fail the install on all other permission
18032                        // redefinitions.
18033                        if (!bp.sourcePackage.equals("android")) {
18034                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18035                                    + pkg.packageName + " attempting to redeclare permission "
18036                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18037                            res.origPermission = perm.info.name;
18038                            res.origPackage = bp.sourcePackage;
18039                            return;
18040                        } else {
18041                            Slog.w(TAG, "Package " + pkg.packageName
18042                                    + " attempting to redeclare system permission "
18043                                    + perm.info.name + "; ignoring new declaration");
18044                            pkg.permissions.remove(i);
18045                        }
18046                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18047                        // Prevent apps to change protection level to dangerous from any other
18048                        // type as this would allow a privilege escalation where an app adds a
18049                        // normal/signature permission in other app's group and later redefines
18050                        // it as dangerous leading to the group auto-grant.
18051                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18052                                == PermissionInfo.PROTECTION_DANGEROUS) {
18053                            if (bp != null && !bp.isRuntime()) {
18054                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18055                                        + "non-runtime permission " + perm.info.name
18056                                        + " to runtime; keeping old protection level");
18057                                perm.info.protectionLevel = bp.protectionLevel;
18058                            }
18059                        }
18060                    }
18061                }
18062            }
18063        }
18064
18065        if (systemApp) {
18066            if (onExternal) {
18067                // Abort update; system app can't be replaced with app on sdcard
18068                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18069                        "Cannot install updates to system apps on sdcard");
18070                return;
18071            } else if (instantApp) {
18072                // Abort update; system app can't be replaced with an instant app
18073                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18074                        "Cannot update a system app with an instant app");
18075                return;
18076            }
18077        }
18078
18079        if (args.move != null) {
18080            // We did an in-place move, so dex is ready to roll
18081            scanFlags |= SCAN_NO_DEX;
18082            scanFlags |= SCAN_MOVE;
18083
18084            synchronized (mPackages) {
18085                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18086                if (ps == null) {
18087                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18088                            "Missing settings for moved package " + pkgName);
18089                }
18090
18091                // We moved the entire application as-is, so bring over the
18092                // previously derived ABI information.
18093                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18094                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18095            }
18096
18097        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18098            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18099            scanFlags |= SCAN_NO_DEX;
18100
18101            try {
18102                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18103                    args.abiOverride : pkg.cpuAbiOverride);
18104                final boolean extractNativeLibs = !pkg.isLibrary();
18105                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18106                        extractNativeLibs, mAppLib32InstallDir);
18107            } catch (PackageManagerException pme) {
18108                Slog.e(TAG, "Error deriving application ABI", pme);
18109                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18110                return;
18111            }
18112
18113            // Shared libraries for the package need to be updated.
18114            synchronized (mPackages) {
18115                try {
18116                    updateSharedLibrariesLPr(pkg, null);
18117                } catch (PackageManagerException e) {
18118                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18119                }
18120            }
18121
18122            // dexopt can take some time to complete, so, for instant apps, we skip this
18123            // step during installation. Instead, we'll take extra time the first time the
18124            // instant app starts. It's preferred to do it this way to provide continuous
18125            // progress to the user instead of mysteriously blocking somewhere in the
18126            // middle of running an instant app.
18127            if (!instantApp) {
18128                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18129                // Do not run PackageDexOptimizer through the local performDexOpt
18130                // method because `pkg` may not be in `mPackages` yet.
18131                //
18132                // Also, don't fail application installs if the dexopt step fails.
18133                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18134                        null /* instructionSets */, false /* checkProfiles */,
18135                        getCompilerFilterForReason(REASON_INSTALL),
18136                        getOrCreateCompilerPackageStats(pkg),
18137                        mDexManager.isUsedByOtherApps(pkg.packageName));
18138                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18139            }
18140
18141            // Notify BackgroundDexOptService that the package has been changed.
18142            // If this is an update of a package which used to fail to compile,
18143            // BDOS will remove it from its blacklist.
18144            // TODO: Layering violation
18145            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18146        }
18147
18148        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18149            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18150            return;
18151        }
18152
18153        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18154
18155        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18156                "installPackageLI")) {
18157            if (replace) {
18158                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18159                    // Static libs have a synthetic package name containing the version
18160                    // and cannot be updated as an update would get a new package name,
18161                    // unless this is the exact same version code which is useful for
18162                    // development.
18163                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18164                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18165                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18166                                + "static-shared libs cannot be updated");
18167                        return;
18168                    }
18169                }
18170                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18171                        installerPackageName, res, args.installReason);
18172            } else {
18173                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18174                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18175            }
18176        }
18177
18178        synchronized (mPackages) {
18179            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18180            if (ps != null) {
18181                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18182                ps.setUpdateAvailable(false /*updateAvailable*/);
18183            }
18184
18185            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18186            for (int i = 0; i < childCount; i++) {
18187                PackageParser.Package childPkg = pkg.childPackages.get(i);
18188                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18189                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18190                if (childPs != null) {
18191                    childRes.newUsers = childPs.queryInstalledUsers(
18192                            sUserManager.getUserIds(), true);
18193                }
18194            }
18195
18196            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18197                updateSequenceNumberLP(ps, res.newUsers);
18198                updateInstantAppInstallerLocked(pkgName);
18199            }
18200        }
18201    }
18202
18203    private void startIntentFilterVerifications(int userId, boolean replacing,
18204            PackageParser.Package pkg) {
18205        if (mIntentFilterVerifierComponent == null) {
18206            Slog.w(TAG, "No IntentFilter verification will not be done as "
18207                    + "there is no IntentFilterVerifier available!");
18208            return;
18209        }
18210
18211        final int verifierUid = getPackageUid(
18212                mIntentFilterVerifierComponent.getPackageName(),
18213                MATCH_DEBUG_TRIAGED_MISSING,
18214                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18215
18216        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18217        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18218        mHandler.sendMessage(msg);
18219
18220        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18221        for (int i = 0; i < childCount; i++) {
18222            PackageParser.Package childPkg = pkg.childPackages.get(i);
18223            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18224            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18225            mHandler.sendMessage(msg);
18226        }
18227    }
18228
18229    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18230            PackageParser.Package pkg) {
18231        int size = pkg.activities.size();
18232        if (size == 0) {
18233            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18234                    "No activity, so no need to verify any IntentFilter!");
18235            return;
18236        }
18237
18238        final boolean hasDomainURLs = hasDomainURLs(pkg);
18239        if (!hasDomainURLs) {
18240            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18241                    "No domain URLs, so no need to verify any IntentFilter!");
18242            return;
18243        }
18244
18245        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18246                + " if any IntentFilter from the " + size
18247                + " Activities needs verification ...");
18248
18249        int count = 0;
18250        final String packageName = pkg.packageName;
18251
18252        synchronized (mPackages) {
18253            // If this is a new install and we see that we've already run verification for this
18254            // package, we have nothing to do: it means the state was restored from backup.
18255            if (!replacing) {
18256                IntentFilterVerificationInfo ivi =
18257                        mSettings.getIntentFilterVerificationLPr(packageName);
18258                if (ivi != null) {
18259                    if (DEBUG_DOMAIN_VERIFICATION) {
18260                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18261                                + ivi.getStatusString());
18262                    }
18263                    return;
18264                }
18265            }
18266
18267            // If any filters need to be verified, then all need to be.
18268            boolean needToVerify = false;
18269            for (PackageParser.Activity a : pkg.activities) {
18270                for (ActivityIntentInfo filter : a.intents) {
18271                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18272                        if (DEBUG_DOMAIN_VERIFICATION) {
18273                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18274                        }
18275                        needToVerify = true;
18276                        break;
18277                    }
18278                }
18279            }
18280
18281            if (needToVerify) {
18282                final int verificationId = mIntentFilterVerificationToken++;
18283                for (PackageParser.Activity a : pkg.activities) {
18284                    for (ActivityIntentInfo filter : a.intents) {
18285                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18286                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18287                                    "Verification needed for IntentFilter:" + filter.toString());
18288                            mIntentFilterVerifier.addOneIntentFilterVerification(
18289                                    verifierUid, userId, verificationId, filter, packageName);
18290                            count++;
18291                        }
18292                    }
18293                }
18294            }
18295        }
18296
18297        if (count > 0) {
18298            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18299                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18300                    +  " for userId:" + userId);
18301            mIntentFilterVerifier.startVerifications(userId);
18302        } else {
18303            if (DEBUG_DOMAIN_VERIFICATION) {
18304                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18305            }
18306        }
18307    }
18308
18309    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18310        final ComponentName cn  = filter.activity.getComponentName();
18311        final String packageName = cn.getPackageName();
18312
18313        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18314                packageName);
18315        if (ivi == null) {
18316            return true;
18317        }
18318        int status = ivi.getStatus();
18319        switch (status) {
18320            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18321            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18322                return true;
18323
18324            default:
18325                // Nothing to do
18326                return false;
18327        }
18328    }
18329
18330    private static boolean isMultiArch(ApplicationInfo info) {
18331        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18332    }
18333
18334    private static boolean isExternal(PackageParser.Package pkg) {
18335        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18336    }
18337
18338    private static boolean isExternal(PackageSetting ps) {
18339        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18340    }
18341
18342    private static boolean isSystemApp(PackageParser.Package pkg) {
18343        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18344    }
18345
18346    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18347        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18348    }
18349
18350    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18351        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18352    }
18353
18354    private static boolean isSystemApp(PackageSetting ps) {
18355        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18356    }
18357
18358    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18359        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18360    }
18361
18362    private int packageFlagsToInstallFlags(PackageSetting ps) {
18363        int installFlags = 0;
18364        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18365            // This existing package was an external ASEC install when we have
18366            // the external flag without a UUID
18367            installFlags |= PackageManager.INSTALL_EXTERNAL;
18368        }
18369        if (ps.isForwardLocked()) {
18370            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18371        }
18372        return installFlags;
18373    }
18374
18375    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18376        if (isExternal(pkg)) {
18377            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18378                return StorageManager.UUID_PRIMARY_PHYSICAL;
18379            } else {
18380                return pkg.volumeUuid;
18381            }
18382        } else {
18383            return StorageManager.UUID_PRIVATE_INTERNAL;
18384        }
18385    }
18386
18387    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18388        if (isExternal(pkg)) {
18389            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18390                return mSettings.getExternalVersion();
18391            } else {
18392                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18393            }
18394        } else {
18395            return mSettings.getInternalVersion();
18396        }
18397    }
18398
18399    private void deleteTempPackageFiles() {
18400        final FilenameFilter filter = new FilenameFilter() {
18401            public boolean accept(File dir, String name) {
18402                return name.startsWith("vmdl") && name.endsWith(".tmp");
18403            }
18404        };
18405        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18406            file.delete();
18407        }
18408    }
18409
18410    @Override
18411    public void deletePackageAsUser(String packageName, int versionCode,
18412            IPackageDeleteObserver observer, int userId, int flags) {
18413        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18414                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18415    }
18416
18417    @Override
18418    public void deletePackageVersioned(VersionedPackage versionedPackage,
18419            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18420        final int callingUid = Binder.getCallingUid();
18421        mContext.enforceCallingOrSelfPermission(
18422                android.Manifest.permission.DELETE_PACKAGES, null);
18423        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18424        Preconditions.checkNotNull(versionedPackage);
18425        Preconditions.checkNotNull(observer);
18426        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18427                PackageManager.VERSION_CODE_HIGHEST,
18428                Integer.MAX_VALUE, "versionCode must be >= -1");
18429
18430        final String packageName = versionedPackage.getPackageName();
18431        final int versionCode = versionedPackage.getVersionCode();
18432        final String internalPackageName;
18433        synchronized (mPackages) {
18434            // Normalize package name to handle renamed packages and static libs
18435            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18436                    versionedPackage.getVersionCode());
18437        }
18438
18439        final int uid = Binder.getCallingUid();
18440        if (!isOrphaned(internalPackageName)
18441                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18442            try {
18443                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18444                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18445                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18446                observer.onUserActionRequired(intent);
18447            } catch (RemoteException re) {
18448            }
18449            return;
18450        }
18451        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18452        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18453        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18454            mContext.enforceCallingOrSelfPermission(
18455                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18456                    "deletePackage for user " + userId);
18457        }
18458
18459        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18460            try {
18461                observer.onPackageDeleted(packageName,
18462                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18463            } catch (RemoteException re) {
18464            }
18465            return;
18466        }
18467
18468        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18469            try {
18470                observer.onPackageDeleted(packageName,
18471                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18472            } catch (RemoteException re) {
18473            }
18474            return;
18475        }
18476
18477        if (DEBUG_REMOVE) {
18478            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18479                    + " deleteAllUsers: " + deleteAllUsers + " version="
18480                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18481                    ? "VERSION_CODE_HIGHEST" : versionCode));
18482        }
18483        // Queue up an async operation since the package deletion may take a little while.
18484        mHandler.post(new Runnable() {
18485            public void run() {
18486                mHandler.removeCallbacks(this);
18487                int returnCode;
18488                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18489                boolean doDeletePackage = true;
18490                if (ps != null) {
18491                    final boolean targetIsInstantApp =
18492                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18493                    doDeletePackage = !targetIsInstantApp
18494                            || canViewInstantApps;
18495                }
18496                if (doDeletePackage) {
18497                    if (!deleteAllUsers) {
18498                        returnCode = deletePackageX(internalPackageName, versionCode,
18499                                userId, deleteFlags);
18500                    } else {
18501                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18502                                internalPackageName, users);
18503                        // If nobody is blocking uninstall, proceed with delete for all users
18504                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18505                            returnCode = deletePackageX(internalPackageName, versionCode,
18506                                    userId, deleteFlags);
18507                        } else {
18508                            // Otherwise uninstall individually for users with blockUninstalls=false
18509                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18510                            for (int userId : users) {
18511                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18512                                    returnCode = deletePackageX(internalPackageName, versionCode,
18513                                            userId, userFlags);
18514                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18515                                        Slog.w(TAG, "Package delete failed for user " + userId
18516                                                + ", returnCode " + returnCode);
18517                                    }
18518                                }
18519                            }
18520                            // The app has only been marked uninstalled for certain users.
18521                            // We still need to report that delete was blocked
18522                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18523                        }
18524                    }
18525                } else {
18526                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18527                }
18528                try {
18529                    observer.onPackageDeleted(packageName, returnCode, null);
18530                } catch (RemoteException e) {
18531                    Log.i(TAG, "Observer no longer exists.");
18532                } //end catch
18533            } //end run
18534        });
18535    }
18536
18537    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18538        if (pkg.staticSharedLibName != null) {
18539            return pkg.manifestPackageName;
18540        }
18541        return pkg.packageName;
18542    }
18543
18544    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18545        // Handle renamed packages
18546        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18547        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18548
18549        // Is this a static library?
18550        SparseArray<SharedLibraryEntry> versionedLib =
18551                mStaticLibsByDeclaringPackage.get(packageName);
18552        if (versionedLib == null || versionedLib.size() <= 0) {
18553            return packageName;
18554        }
18555
18556        // Figure out which lib versions the caller can see
18557        SparseIntArray versionsCallerCanSee = null;
18558        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18559        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18560                && callingAppId != Process.ROOT_UID) {
18561            versionsCallerCanSee = new SparseIntArray();
18562            String libName = versionedLib.valueAt(0).info.getName();
18563            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18564            if (uidPackages != null) {
18565                for (String uidPackage : uidPackages) {
18566                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18567                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18568                    if (libIdx >= 0) {
18569                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18570                        versionsCallerCanSee.append(libVersion, libVersion);
18571                    }
18572                }
18573            }
18574        }
18575
18576        // Caller can see nothing - done
18577        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18578            return packageName;
18579        }
18580
18581        // Find the version the caller can see and the app version code
18582        SharedLibraryEntry highestVersion = null;
18583        final int versionCount = versionedLib.size();
18584        for (int i = 0; i < versionCount; i++) {
18585            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18586            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18587                    libEntry.info.getVersion()) < 0) {
18588                continue;
18589            }
18590            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18591            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18592                if (libVersionCode == versionCode) {
18593                    return libEntry.apk;
18594                }
18595            } else if (highestVersion == null) {
18596                highestVersion = libEntry;
18597            } else if (libVersionCode  > highestVersion.info
18598                    .getDeclaringPackage().getVersionCode()) {
18599                highestVersion = libEntry;
18600            }
18601        }
18602
18603        if (highestVersion != null) {
18604            return highestVersion.apk;
18605        }
18606
18607        return packageName;
18608    }
18609
18610    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18611        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18612              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18613            return true;
18614        }
18615        final int callingUserId = UserHandle.getUserId(callingUid);
18616        // If the caller installed the pkgName, then allow it to silently uninstall.
18617        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18618            return true;
18619        }
18620
18621        // Allow package verifier to silently uninstall.
18622        if (mRequiredVerifierPackage != null &&
18623                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18624            return true;
18625        }
18626
18627        // Allow package uninstaller to silently uninstall.
18628        if (mRequiredUninstallerPackage != null &&
18629                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18630            return true;
18631        }
18632
18633        // Allow storage manager to silently uninstall.
18634        if (mStorageManagerPackage != null &&
18635                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18636            return true;
18637        }
18638        return false;
18639    }
18640
18641    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18642        int[] result = EMPTY_INT_ARRAY;
18643        for (int userId : userIds) {
18644            if (getBlockUninstallForUser(packageName, userId)) {
18645                result = ArrayUtils.appendInt(result, userId);
18646            }
18647        }
18648        return result;
18649    }
18650
18651    @Override
18652    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18653        final int callingUid = Binder.getCallingUid();
18654        if (getInstantAppPackageName(callingUid) != null
18655                && !isCallerSameApp(packageName, callingUid)) {
18656            return false;
18657        }
18658        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18659    }
18660
18661    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18662        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18663                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18664        try {
18665            if (dpm != null) {
18666                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18667                        /* callingUserOnly =*/ false);
18668                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18669                        : deviceOwnerComponentName.getPackageName();
18670                // Does the package contains the device owner?
18671                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18672                // this check is probably not needed, since DO should be registered as a device
18673                // admin on some user too. (Original bug for this: b/17657954)
18674                if (packageName.equals(deviceOwnerPackageName)) {
18675                    return true;
18676                }
18677                // Does it contain a device admin for any user?
18678                int[] users;
18679                if (userId == UserHandle.USER_ALL) {
18680                    users = sUserManager.getUserIds();
18681                } else {
18682                    users = new int[]{userId};
18683                }
18684                for (int i = 0; i < users.length; ++i) {
18685                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18686                        return true;
18687                    }
18688                }
18689            }
18690        } catch (RemoteException e) {
18691        }
18692        return false;
18693    }
18694
18695    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18696        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18697    }
18698
18699    /**
18700     *  This method is an internal method that could be get invoked either
18701     *  to delete an installed package or to clean up a failed installation.
18702     *  After deleting an installed package, a broadcast is sent to notify any
18703     *  listeners that the package has been removed. For cleaning up a failed
18704     *  installation, the broadcast is not necessary since the package's
18705     *  installation wouldn't have sent the initial broadcast either
18706     *  The key steps in deleting a package are
18707     *  deleting the package information in internal structures like mPackages,
18708     *  deleting the packages base directories through installd
18709     *  updating mSettings to reflect current status
18710     *  persisting settings for later use
18711     *  sending a broadcast if necessary
18712     */
18713    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18714        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18715        final boolean res;
18716
18717        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18718                ? UserHandle.USER_ALL : userId;
18719
18720        if (isPackageDeviceAdmin(packageName, removeUser)) {
18721            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18722            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18723        }
18724
18725        PackageSetting uninstalledPs = null;
18726        PackageParser.Package pkg = null;
18727
18728        // for the uninstall-updates case and restricted profiles, remember the per-
18729        // user handle installed state
18730        int[] allUsers;
18731        synchronized (mPackages) {
18732            uninstalledPs = mSettings.mPackages.get(packageName);
18733            if (uninstalledPs == null) {
18734                Slog.w(TAG, "Not removing non-existent package " + packageName);
18735                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18736            }
18737
18738            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18739                    && uninstalledPs.versionCode != versionCode) {
18740                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18741                        + uninstalledPs.versionCode + " != " + versionCode);
18742                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18743            }
18744
18745            // Static shared libs can be declared by any package, so let us not
18746            // allow removing a package if it provides a lib others depend on.
18747            pkg = mPackages.get(packageName);
18748
18749            allUsers = sUserManager.getUserIds();
18750
18751            if (pkg != null && pkg.staticSharedLibName != null) {
18752                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18753                        pkg.staticSharedLibVersion);
18754                if (libEntry != null) {
18755                    for (int currUserId : allUsers) {
18756                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18757                            continue;
18758                        }
18759                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18760                                libEntry.info, 0, currUserId);
18761                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18762                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18763                                    + " hosting lib " + libEntry.info.getName() + " version "
18764                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18765                                    + " for user " + currUserId);
18766                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18767                        }
18768                    }
18769                }
18770            }
18771
18772            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18773        }
18774
18775        final int freezeUser;
18776        if (isUpdatedSystemApp(uninstalledPs)
18777                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18778            // We're downgrading a system app, which will apply to all users, so
18779            // freeze them all during the downgrade
18780            freezeUser = UserHandle.USER_ALL;
18781        } else {
18782            freezeUser = removeUser;
18783        }
18784
18785        synchronized (mInstallLock) {
18786            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18787            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18788                    deleteFlags, "deletePackageX")) {
18789                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18790                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18791            }
18792            synchronized (mPackages) {
18793                if (res) {
18794                    if (pkg != null) {
18795                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18796                    }
18797                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18798                    updateInstantAppInstallerLocked(packageName);
18799                }
18800            }
18801        }
18802
18803        if (res) {
18804            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18805            info.sendPackageRemovedBroadcasts(killApp);
18806            info.sendSystemPackageUpdatedBroadcasts();
18807            info.sendSystemPackageAppearedBroadcasts();
18808        }
18809        // Force a gc here.
18810        Runtime.getRuntime().gc();
18811        // Delete the resources here after sending the broadcast to let
18812        // other processes clean up before deleting resources.
18813        if (info.args != null) {
18814            synchronized (mInstallLock) {
18815                info.args.doPostDeleteLI(true);
18816            }
18817        }
18818
18819        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18820    }
18821
18822    static class PackageRemovedInfo {
18823        final PackageSender packageSender;
18824        String removedPackage;
18825        String installerPackageName;
18826        int uid = -1;
18827        int removedAppId = -1;
18828        int[] origUsers;
18829        int[] removedUsers = null;
18830        int[] broadcastUsers = null;
18831        SparseArray<Integer> installReasons;
18832        boolean isRemovedPackageSystemUpdate = false;
18833        boolean isUpdate;
18834        boolean dataRemoved;
18835        boolean removedForAllUsers;
18836        boolean isStaticSharedLib;
18837        // Clean up resources deleted packages.
18838        InstallArgs args = null;
18839        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18840        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18841
18842        PackageRemovedInfo(PackageSender packageSender) {
18843            this.packageSender = packageSender;
18844        }
18845
18846        void sendPackageRemovedBroadcasts(boolean killApp) {
18847            sendPackageRemovedBroadcastInternal(killApp);
18848            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18849            for (int i = 0; i < childCount; i++) {
18850                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18851                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18852            }
18853        }
18854
18855        void sendSystemPackageUpdatedBroadcasts() {
18856            if (isRemovedPackageSystemUpdate) {
18857                sendSystemPackageUpdatedBroadcastsInternal();
18858                final int childCount = (removedChildPackages != null)
18859                        ? removedChildPackages.size() : 0;
18860                for (int i = 0; i < childCount; i++) {
18861                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18862                    if (childInfo.isRemovedPackageSystemUpdate) {
18863                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18864                    }
18865                }
18866            }
18867        }
18868
18869        void sendSystemPackageAppearedBroadcasts() {
18870            final int packageCount = (appearedChildPackages != null)
18871                    ? appearedChildPackages.size() : 0;
18872            for (int i = 0; i < packageCount; i++) {
18873                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18874                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18875                    true, UserHandle.getAppId(installedInfo.uid),
18876                    installedInfo.newUsers);
18877            }
18878        }
18879
18880        private void sendSystemPackageUpdatedBroadcastsInternal() {
18881            Bundle extras = new Bundle(2);
18882            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18883            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18884            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18885                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18886            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18887                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18888            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18889                null, null, 0, removedPackage, null, null);
18890            if (installerPackageName != null) {
18891                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18892                        removedPackage, extras, 0 /*flags*/,
18893                        installerPackageName, null, null);
18894                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18895                        removedPackage, extras, 0 /*flags*/,
18896                        installerPackageName, null, null);
18897            }
18898        }
18899
18900        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18901            // Don't send static shared library removal broadcasts as these
18902            // libs are visible only the the apps that depend on them an one
18903            // cannot remove the library if it has a dependency.
18904            if (isStaticSharedLib) {
18905                return;
18906            }
18907            Bundle extras = new Bundle(2);
18908            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18909            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18910            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18911            if (isUpdate || isRemovedPackageSystemUpdate) {
18912                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18913            }
18914            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18915            if (removedPackage != null) {
18916                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18917                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18918                if (installerPackageName != null) {
18919                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18920                            removedPackage, extras, 0 /*flags*/,
18921                            installerPackageName, null, broadcastUsers);
18922                }
18923                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18924                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18925                        removedPackage, extras,
18926                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18927                        null, null, broadcastUsers);
18928                }
18929            }
18930            if (removedAppId >= 0) {
18931                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
18932                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
18933            }
18934        }
18935
18936        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18937            removedUsers = userIds;
18938            if (removedUsers == null) {
18939                broadcastUsers = null;
18940                return;
18941            }
18942
18943            broadcastUsers = EMPTY_INT_ARRAY;
18944            for (int i = userIds.length - 1; i >= 0; --i) {
18945                final int userId = userIds[i];
18946                if (deletedPackageSetting.getInstantApp(userId)) {
18947                    continue;
18948                }
18949                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18950            }
18951        }
18952    }
18953
18954    /*
18955     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18956     * flag is not set, the data directory is removed as well.
18957     * make sure this flag is set for partially installed apps. If not its meaningless to
18958     * delete a partially installed application.
18959     */
18960    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18961            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18962        String packageName = ps.name;
18963        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18964        // Retrieve object to delete permissions for shared user later on
18965        final PackageParser.Package deletedPkg;
18966        final PackageSetting deletedPs;
18967        // reader
18968        synchronized (mPackages) {
18969            deletedPkg = mPackages.get(packageName);
18970            deletedPs = mSettings.mPackages.get(packageName);
18971            if (outInfo != null) {
18972                outInfo.removedPackage = packageName;
18973                outInfo.installerPackageName = ps.installerPackageName;
18974                outInfo.isStaticSharedLib = deletedPkg != null
18975                        && deletedPkg.staticSharedLibName != null;
18976                outInfo.populateUsers(deletedPs == null ? null
18977                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18978            }
18979        }
18980
18981        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
18982
18983        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18984            final PackageParser.Package resolvedPkg;
18985            if (deletedPkg != null) {
18986                resolvedPkg = deletedPkg;
18987            } else {
18988                // We don't have a parsed package when it lives on an ejected
18989                // adopted storage device, so fake something together
18990                resolvedPkg = new PackageParser.Package(ps.name);
18991                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18992            }
18993            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18994                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18995            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18996            if (outInfo != null) {
18997                outInfo.dataRemoved = true;
18998            }
18999            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19000        }
19001
19002        int removedAppId = -1;
19003
19004        // writer
19005        synchronized (mPackages) {
19006            boolean installedStateChanged = false;
19007            if (deletedPs != null) {
19008                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19009                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19010                    clearDefaultBrowserIfNeeded(packageName);
19011                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19012                    removedAppId = mSettings.removePackageLPw(packageName);
19013                    if (outInfo != null) {
19014                        outInfo.removedAppId = removedAppId;
19015                    }
19016                    updatePermissionsLPw(deletedPs.name, null, 0);
19017                    if (deletedPs.sharedUser != null) {
19018                        // Remove permissions associated with package. Since runtime
19019                        // permissions are per user we have to kill the removed package
19020                        // or packages running under the shared user of the removed
19021                        // package if revoking the permissions requested only by the removed
19022                        // package is successful and this causes a change in gids.
19023                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19024                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19025                                    userId);
19026                            if (userIdToKill == UserHandle.USER_ALL
19027                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19028                                // If gids changed for this user, kill all affected packages.
19029                                mHandler.post(new Runnable() {
19030                                    @Override
19031                                    public void run() {
19032                                        // This has to happen with no lock held.
19033                                        killApplication(deletedPs.name, deletedPs.appId,
19034                                                KILL_APP_REASON_GIDS_CHANGED);
19035                                    }
19036                                });
19037                                break;
19038                            }
19039                        }
19040                    }
19041                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19042                }
19043                // make sure to preserve per-user disabled state if this removal was just
19044                // a downgrade of a system app to the factory package
19045                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19046                    if (DEBUG_REMOVE) {
19047                        Slog.d(TAG, "Propagating install state across downgrade");
19048                    }
19049                    for (int userId : allUserHandles) {
19050                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19051                        if (DEBUG_REMOVE) {
19052                            Slog.d(TAG, "    user " + userId + " => " + installed);
19053                        }
19054                        if (installed != ps.getInstalled(userId)) {
19055                            installedStateChanged = true;
19056                        }
19057                        ps.setInstalled(installed, userId);
19058                    }
19059                }
19060            }
19061            // can downgrade to reader
19062            if (writeSettings) {
19063                // Save settings now
19064                mSettings.writeLPr();
19065            }
19066            if (installedStateChanged) {
19067                mSettings.writeKernelMappingLPr(ps);
19068            }
19069        }
19070        if (removedAppId != -1) {
19071            // A user ID was deleted here. Go through all users and remove it
19072            // from KeyStore.
19073            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19074        }
19075    }
19076
19077    static boolean locationIsPrivileged(File path) {
19078        try {
19079            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19080                    .getCanonicalPath();
19081            return path.getCanonicalPath().startsWith(privilegedAppDir);
19082        } catch (IOException e) {
19083            Slog.e(TAG, "Unable to access code path " + path);
19084        }
19085        return false;
19086    }
19087
19088    /*
19089     * Tries to delete system package.
19090     */
19091    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19092            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19093            boolean writeSettings) {
19094        if (deletedPs.parentPackageName != null) {
19095            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19096            return false;
19097        }
19098
19099        final boolean applyUserRestrictions
19100                = (allUserHandles != null) && (outInfo.origUsers != null);
19101        final PackageSetting disabledPs;
19102        // Confirm if the system package has been updated
19103        // An updated system app can be deleted. This will also have to restore
19104        // the system pkg from system partition
19105        // reader
19106        synchronized (mPackages) {
19107            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19108        }
19109
19110        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19111                + " disabledPs=" + disabledPs);
19112
19113        if (disabledPs == null) {
19114            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19115            return false;
19116        } else if (DEBUG_REMOVE) {
19117            Slog.d(TAG, "Deleting system pkg from data partition");
19118        }
19119
19120        if (DEBUG_REMOVE) {
19121            if (applyUserRestrictions) {
19122                Slog.d(TAG, "Remembering install states:");
19123                for (int userId : allUserHandles) {
19124                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19125                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19126                }
19127            }
19128        }
19129
19130        // Delete the updated package
19131        outInfo.isRemovedPackageSystemUpdate = true;
19132        if (outInfo.removedChildPackages != null) {
19133            final int childCount = (deletedPs.childPackageNames != null)
19134                    ? deletedPs.childPackageNames.size() : 0;
19135            for (int i = 0; i < childCount; i++) {
19136                String childPackageName = deletedPs.childPackageNames.get(i);
19137                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19138                        .contains(childPackageName)) {
19139                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19140                            childPackageName);
19141                    if (childInfo != null) {
19142                        childInfo.isRemovedPackageSystemUpdate = true;
19143                    }
19144                }
19145            }
19146        }
19147
19148        if (disabledPs.versionCode < deletedPs.versionCode) {
19149            // Delete data for downgrades
19150            flags &= ~PackageManager.DELETE_KEEP_DATA;
19151        } else {
19152            // Preserve data by setting flag
19153            flags |= PackageManager.DELETE_KEEP_DATA;
19154        }
19155
19156        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19157                outInfo, writeSettings, disabledPs.pkg);
19158        if (!ret) {
19159            return false;
19160        }
19161
19162        // writer
19163        synchronized (mPackages) {
19164            // Reinstate the old system package
19165            enableSystemPackageLPw(disabledPs.pkg);
19166            // Remove any native libraries from the upgraded package.
19167            removeNativeBinariesLI(deletedPs);
19168        }
19169
19170        // Install the system package
19171        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19172        int parseFlags = mDefParseFlags
19173                | PackageParser.PARSE_MUST_BE_APK
19174                | PackageParser.PARSE_IS_SYSTEM
19175                | PackageParser.PARSE_IS_SYSTEM_DIR;
19176        if (locationIsPrivileged(disabledPs.codePath)) {
19177            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19178        }
19179
19180        final PackageParser.Package newPkg;
19181        try {
19182            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19183                0 /* currentTime */, null);
19184        } catch (PackageManagerException e) {
19185            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19186                    + e.getMessage());
19187            return false;
19188        }
19189
19190        try {
19191            // update shared libraries for the newly re-installed system package
19192            updateSharedLibrariesLPr(newPkg, null);
19193        } catch (PackageManagerException e) {
19194            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19195        }
19196
19197        prepareAppDataAfterInstallLIF(newPkg);
19198
19199        // writer
19200        synchronized (mPackages) {
19201            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19202
19203            // Propagate the permissions state as we do not want to drop on the floor
19204            // runtime permissions. The update permissions method below will take
19205            // care of removing obsolete permissions and grant install permissions.
19206            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19207            updatePermissionsLPw(newPkg.packageName, newPkg,
19208                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19209
19210            if (applyUserRestrictions) {
19211                boolean installedStateChanged = false;
19212                if (DEBUG_REMOVE) {
19213                    Slog.d(TAG, "Propagating install state across reinstall");
19214                }
19215                for (int userId : allUserHandles) {
19216                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19217                    if (DEBUG_REMOVE) {
19218                        Slog.d(TAG, "    user " + userId + " => " + installed);
19219                    }
19220                    if (installed != ps.getInstalled(userId)) {
19221                        installedStateChanged = true;
19222                    }
19223                    ps.setInstalled(installed, userId);
19224
19225                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19226                }
19227                // Regardless of writeSettings we need to ensure that this restriction
19228                // state propagation is persisted
19229                mSettings.writeAllUsersPackageRestrictionsLPr();
19230                if (installedStateChanged) {
19231                    mSettings.writeKernelMappingLPr(ps);
19232                }
19233            }
19234            // can downgrade to reader here
19235            if (writeSettings) {
19236                mSettings.writeLPr();
19237            }
19238        }
19239        return true;
19240    }
19241
19242    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19243            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19244            PackageRemovedInfo outInfo, boolean writeSettings,
19245            PackageParser.Package replacingPackage) {
19246        synchronized (mPackages) {
19247            if (outInfo != null) {
19248                outInfo.uid = ps.appId;
19249            }
19250
19251            if (outInfo != null && outInfo.removedChildPackages != null) {
19252                final int childCount = (ps.childPackageNames != null)
19253                        ? ps.childPackageNames.size() : 0;
19254                for (int i = 0; i < childCount; i++) {
19255                    String childPackageName = ps.childPackageNames.get(i);
19256                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19257                    if (childPs == null) {
19258                        return false;
19259                    }
19260                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19261                            childPackageName);
19262                    if (childInfo != null) {
19263                        childInfo.uid = childPs.appId;
19264                    }
19265                }
19266            }
19267        }
19268
19269        // Delete package data from internal structures and also remove data if flag is set
19270        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19271
19272        // Delete the child packages data
19273        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19274        for (int i = 0; i < childCount; i++) {
19275            PackageSetting childPs;
19276            synchronized (mPackages) {
19277                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19278            }
19279            if (childPs != null) {
19280                PackageRemovedInfo childOutInfo = (outInfo != null
19281                        && outInfo.removedChildPackages != null)
19282                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19283                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19284                        && (replacingPackage != null
19285                        && !replacingPackage.hasChildPackage(childPs.name))
19286                        ? flags & ~DELETE_KEEP_DATA : flags;
19287                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19288                        deleteFlags, writeSettings);
19289            }
19290        }
19291
19292        // Delete application code and resources only for parent packages
19293        if (ps.parentPackageName == null) {
19294            if (deleteCodeAndResources && (outInfo != null)) {
19295                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19296                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19297                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19298            }
19299        }
19300
19301        return true;
19302    }
19303
19304    @Override
19305    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19306            int userId) {
19307        mContext.enforceCallingOrSelfPermission(
19308                android.Manifest.permission.DELETE_PACKAGES, null);
19309        synchronized (mPackages) {
19310            // Cannot block uninstall of static shared libs as they are
19311            // considered a part of the using app (emulating static linking).
19312            // Also static libs are installed always on internal storage.
19313            PackageParser.Package pkg = mPackages.get(packageName);
19314            if (pkg != null && pkg.staticSharedLibName != null) {
19315                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19316                        + " providing static shared library: " + pkg.staticSharedLibName);
19317                return false;
19318            }
19319            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19320            mSettings.writePackageRestrictionsLPr(userId);
19321        }
19322        return true;
19323    }
19324
19325    @Override
19326    public boolean getBlockUninstallForUser(String packageName, int userId) {
19327        synchronized (mPackages) {
19328            final PackageSetting ps = mSettings.mPackages.get(packageName);
19329            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19330                return false;
19331            }
19332            return mSettings.getBlockUninstallLPr(userId, packageName);
19333        }
19334    }
19335
19336    @Override
19337    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19338        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19339        synchronized (mPackages) {
19340            PackageSetting ps = mSettings.mPackages.get(packageName);
19341            if (ps == null) {
19342                Log.w(TAG, "Package doesn't exist: " + packageName);
19343                return false;
19344            }
19345            if (systemUserApp) {
19346                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19347            } else {
19348                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19349            }
19350            mSettings.writeLPr();
19351        }
19352        return true;
19353    }
19354
19355    /*
19356     * This method handles package deletion in general
19357     */
19358    private boolean deletePackageLIF(String packageName, UserHandle user,
19359            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19360            PackageRemovedInfo outInfo, boolean writeSettings,
19361            PackageParser.Package replacingPackage) {
19362        if (packageName == null) {
19363            Slog.w(TAG, "Attempt to delete null packageName.");
19364            return false;
19365        }
19366
19367        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19368
19369        PackageSetting ps;
19370        synchronized (mPackages) {
19371            ps = mSettings.mPackages.get(packageName);
19372            if (ps == null) {
19373                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19374                return false;
19375            }
19376
19377            if (ps.parentPackageName != null && (!isSystemApp(ps)
19378                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19379                if (DEBUG_REMOVE) {
19380                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19381                            + ((user == null) ? UserHandle.USER_ALL : user));
19382                }
19383                final int removedUserId = (user != null) ? user.getIdentifier()
19384                        : UserHandle.USER_ALL;
19385                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19386                    return false;
19387                }
19388                markPackageUninstalledForUserLPw(ps, user);
19389                scheduleWritePackageRestrictionsLocked(user);
19390                return true;
19391            }
19392        }
19393
19394        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19395                && user.getIdentifier() != UserHandle.USER_ALL)) {
19396            // The caller is asking that the package only be deleted for a single
19397            // user.  To do this, we just mark its uninstalled state and delete
19398            // its data. If this is a system app, we only allow this to happen if
19399            // they have set the special DELETE_SYSTEM_APP which requests different
19400            // semantics than normal for uninstalling system apps.
19401            markPackageUninstalledForUserLPw(ps, user);
19402
19403            if (!isSystemApp(ps)) {
19404                // Do not uninstall the APK if an app should be cached
19405                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19406                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19407                    // Other user still have this package installed, so all
19408                    // we need to do is clear this user's data and save that
19409                    // it is uninstalled.
19410                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19411                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19412                        return false;
19413                    }
19414                    scheduleWritePackageRestrictionsLocked(user);
19415                    return true;
19416                } else {
19417                    // We need to set it back to 'installed' so the uninstall
19418                    // broadcasts will be sent correctly.
19419                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19420                    ps.setInstalled(true, user.getIdentifier());
19421                    mSettings.writeKernelMappingLPr(ps);
19422                }
19423            } else {
19424                // This is a system app, so we assume that the
19425                // other users still have this package installed, so all
19426                // we need to do is clear this user's data and save that
19427                // it is uninstalled.
19428                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19429                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19430                    return false;
19431                }
19432                scheduleWritePackageRestrictionsLocked(user);
19433                return true;
19434            }
19435        }
19436
19437        // If we are deleting a composite package for all users, keep track
19438        // of result for each child.
19439        if (ps.childPackageNames != null && outInfo != null) {
19440            synchronized (mPackages) {
19441                final int childCount = ps.childPackageNames.size();
19442                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19443                for (int i = 0; i < childCount; i++) {
19444                    String childPackageName = ps.childPackageNames.get(i);
19445                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19446                    childInfo.removedPackage = childPackageName;
19447                    childInfo.installerPackageName = ps.installerPackageName;
19448                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19449                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19450                    if (childPs != null) {
19451                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19452                    }
19453                }
19454            }
19455        }
19456
19457        boolean ret = false;
19458        if (isSystemApp(ps)) {
19459            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19460            // When an updated system application is deleted we delete the existing resources
19461            // as well and fall back to existing code in system partition
19462            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19463        } else {
19464            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19465            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19466                    outInfo, writeSettings, replacingPackage);
19467        }
19468
19469        // Take a note whether we deleted the package for all users
19470        if (outInfo != null) {
19471            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19472            if (outInfo.removedChildPackages != null) {
19473                synchronized (mPackages) {
19474                    final int childCount = outInfo.removedChildPackages.size();
19475                    for (int i = 0; i < childCount; i++) {
19476                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19477                        if (childInfo != null) {
19478                            childInfo.removedForAllUsers = mPackages.get(
19479                                    childInfo.removedPackage) == null;
19480                        }
19481                    }
19482                }
19483            }
19484            // If we uninstalled an update to a system app there may be some
19485            // child packages that appeared as they are declared in the system
19486            // app but were not declared in the update.
19487            if (isSystemApp(ps)) {
19488                synchronized (mPackages) {
19489                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19490                    final int childCount = (updatedPs.childPackageNames != null)
19491                            ? updatedPs.childPackageNames.size() : 0;
19492                    for (int i = 0; i < childCount; i++) {
19493                        String childPackageName = updatedPs.childPackageNames.get(i);
19494                        if (outInfo.removedChildPackages == null
19495                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19496                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19497                            if (childPs == null) {
19498                                continue;
19499                            }
19500                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19501                            installRes.name = childPackageName;
19502                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19503                            installRes.pkg = mPackages.get(childPackageName);
19504                            installRes.uid = childPs.pkg.applicationInfo.uid;
19505                            if (outInfo.appearedChildPackages == null) {
19506                                outInfo.appearedChildPackages = new ArrayMap<>();
19507                            }
19508                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19509                        }
19510                    }
19511                }
19512            }
19513        }
19514
19515        return ret;
19516    }
19517
19518    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19519        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19520                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19521        for (int nextUserId : userIds) {
19522            if (DEBUG_REMOVE) {
19523                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19524            }
19525            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19526                    false /*installed*/,
19527                    true /*stopped*/,
19528                    true /*notLaunched*/,
19529                    false /*hidden*/,
19530                    false /*suspended*/,
19531                    false /*instantApp*/,
19532                    null /*lastDisableAppCaller*/,
19533                    null /*enabledComponents*/,
19534                    null /*disabledComponents*/,
19535                    ps.readUserState(nextUserId).domainVerificationStatus,
19536                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19537        }
19538        mSettings.writeKernelMappingLPr(ps);
19539    }
19540
19541    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19542            PackageRemovedInfo outInfo) {
19543        final PackageParser.Package pkg;
19544        synchronized (mPackages) {
19545            pkg = mPackages.get(ps.name);
19546        }
19547
19548        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19549                : new int[] {userId};
19550        for (int nextUserId : userIds) {
19551            if (DEBUG_REMOVE) {
19552                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19553                        + nextUserId);
19554            }
19555
19556            destroyAppDataLIF(pkg, userId,
19557                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19558            destroyAppProfilesLIF(pkg, userId);
19559            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19560            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19561            schedulePackageCleaning(ps.name, nextUserId, false);
19562            synchronized (mPackages) {
19563                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19564                    scheduleWritePackageRestrictionsLocked(nextUserId);
19565                }
19566                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19567            }
19568        }
19569
19570        if (outInfo != null) {
19571            outInfo.removedPackage = ps.name;
19572            outInfo.installerPackageName = ps.installerPackageName;
19573            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19574            outInfo.removedAppId = ps.appId;
19575            outInfo.removedUsers = userIds;
19576            outInfo.broadcastUsers = userIds;
19577        }
19578
19579        return true;
19580    }
19581
19582    private final class ClearStorageConnection implements ServiceConnection {
19583        IMediaContainerService mContainerService;
19584
19585        @Override
19586        public void onServiceConnected(ComponentName name, IBinder service) {
19587            synchronized (this) {
19588                mContainerService = IMediaContainerService.Stub
19589                        .asInterface(Binder.allowBlocking(service));
19590                notifyAll();
19591            }
19592        }
19593
19594        @Override
19595        public void onServiceDisconnected(ComponentName name) {
19596        }
19597    }
19598
19599    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19600        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19601
19602        final boolean mounted;
19603        if (Environment.isExternalStorageEmulated()) {
19604            mounted = true;
19605        } else {
19606            final String status = Environment.getExternalStorageState();
19607
19608            mounted = status.equals(Environment.MEDIA_MOUNTED)
19609                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19610        }
19611
19612        if (!mounted) {
19613            return;
19614        }
19615
19616        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19617        int[] users;
19618        if (userId == UserHandle.USER_ALL) {
19619            users = sUserManager.getUserIds();
19620        } else {
19621            users = new int[] { userId };
19622        }
19623        final ClearStorageConnection conn = new ClearStorageConnection();
19624        if (mContext.bindServiceAsUser(
19625                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19626            try {
19627                for (int curUser : users) {
19628                    long timeout = SystemClock.uptimeMillis() + 5000;
19629                    synchronized (conn) {
19630                        long now;
19631                        while (conn.mContainerService == null &&
19632                                (now = SystemClock.uptimeMillis()) < timeout) {
19633                            try {
19634                                conn.wait(timeout - now);
19635                            } catch (InterruptedException e) {
19636                            }
19637                        }
19638                    }
19639                    if (conn.mContainerService == null) {
19640                        return;
19641                    }
19642
19643                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19644                    clearDirectory(conn.mContainerService,
19645                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19646                    if (allData) {
19647                        clearDirectory(conn.mContainerService,
19648                                userEnv.buildExternalStorageAppDataDirs(packageName));
19649                        clearDirectory(conn.mContainerService,
19650                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19651                    }
19652                }
19653            } finally {
19654                mContext.unbindService(conn);
19655            }
19656        }
19657    }
19658
19659    @Override
19660    public void clearApplicationProfileData(String packageName) {
19661        enforceSystemOrRoot("Only the system can clear all profile data");
19662
19663        final PackageParser.Package pkg;
19664        synchronized (mPackages) {
19665            pkg = mPackages.get(packageName);
19666        }
19667
19668        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19669            synchronized (mInstallLock) {
19670                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19671            }
19672        }
19673    }
19674
19675    @Override
19676    public void clearApplicationUserData(final String packageName,
19677            final IPackageDataObserver observer, final int userId) {
19678        mContext.enforceCallingOrSelfPermission(
19679                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19680
19681        final int callingUid = Binder.getCallingUid();
19682        enforceCrossUserPermission(callingUid, userId,
19683                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19684
19685        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19686        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19687            return;
19688        }
19689        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19690            throw new SecurityException("Cannot clear data for a protected package: "
19691                    + packageName);
19692        }
19693        // Queue up an async operation since the package deletion may take a little while.
19694        mHandler.post(new Runnable() {
19695            public void run() {
19696                mHandler.removeCallbacks(this);
19697                final boolean succeeded;
19698                try (PackageFreezer freezer = freezePackage(packageName,
19699                        "clearApplicationUserData")) {
19700                    synchronized (mInstallLock) {
19701                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19702                    }
19703                    clearExternalStorageDataSync(packageName, userId, true);
19704                    synchronized (mPackages) {
19705                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19706                                packageName, userId);
19707                    }
19708                }
19709                if (succeeded) {
19710                    // invoke DeviceStorageMonitor's update method to clear any notifications
19711                    DeviceStorageMonitorInternal dsm = LocalServices
19712                            .getService(DeviceStorageMonitorInternal.class);
19713                    if (dsm != null) {
19714                        dsm.checkMemory();
19715                    }
19716                }
19717                if(observer != null) {
19718                    try {
19719                        observer.onRemoveCompleted(packageName, succeeded);
19720                    } catch (RemoteException e) {
19721                        Log.i(TAG, "Observer no longer exists.");
19722                    }
19723                } //end if observer
19724            } //end run
19725        });
19726    }
19727
19728    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19729        if (packageName == null) {
19730            Slog.w(TAG, "Attempt to delete null packageName.");
19731            return false;
19732        }
19733
19734        // Try finding details about the requested package
19735        PackageParser.Package pkg;
19736        synchronized (mPackages) {
19737            pkg = mPackages.get(packageName);
19738            if (pkg == null) {
19739                final PackageSetting ps = mSettings.mPackages.get(packageName);
19740                if (ps != null) {
19741                    pkg = ps.pkg;
19742                }
19743            }
19744
19745            if (pkg == null) {
19746                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19747                return false;
19748            }
19749
19750            PackageSetting ps = (PackageSetting) pkg.mExtras;
19751            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19752        }
19753
19754        clearAppDataLIF(pkg, userId,
19755                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19756
19757        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19758        removeKeystoreDataIfNeeded(userId, appId);
19759
19760        UserManagerInternal umInternal = getUserManagerInternal();
19761        final int flags;
19762        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19763            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19764        } else if (umInternal.isUserRunning(userId)) {
19765            flags = StorageManager.FLAG_STORAGE_DE;
19766        } else {
19767            flags = 0;
19768        }
19769        prepareAppDataContentsLIF(pkg, userId, flags);
19770
19771        return true;
19772    }
19773
19774    /**
19775     * Reverts user permission state changes (permissions and flags) in
19776     * all packages for a given user.
19777     *
19778     * @param userId The device user for which to do a reset.
19779     */
19780    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19781        final int packageCount = mPackages.size();
19782        for (int i = 0; i < packageCount; i++) {
19783            PackageParser.Package pkg = mPackages.valueAt(i);
19784            PackageSetting ps = (PackageSetting) pkg.mExtras;
19785            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19786        }
19787    }
19788
19789    private void resetNetworkPolicies(int userId) {
19790        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19791    }
19792
19793    /**
19794     * Reverts user permission state changes (permissions and flags).
19795     *
19796     * @param ps The package for which to reset.
19797     * @param userId The device user for which to do a reset.
19798     */
19799    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19800            final PackageSetting ps, final int userId) {
19801        if (ps.pkg == null) {
19802            return;
19803        }
19804
19805        // These are flags that can change base on user actions.
19806        final int userSettableMask = FLAG_PERMISSION_USER_SET
19807                | FLAG_PERMISSION_USER_FIXED
19808                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19809                | FLAG_PERMISSION_REVIEW_REQUIRED;
19810
19811        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19812                | FLAG_PERMISSION_POLICY_FIXED;
19813
19814        boolean writeInstallPermissions = false;
19815        boolean writeRuntimePermissions = false;
19816
19817        final int permissionCount = ps.pkg.requestedPermissions.size();
19818        for (int i = 0; i < permissionCount; i++) {
19819            String permission = ps.pkg.requestedPermissions.get(i);
19820
19821            BasePermission bp = mSettings.mPermissions.get(permission);
19822            if (bp == null) {
19823                continue;
19824            }
19825
19826            // If shared user we just reset the state to which only this app contributed.
19827            if (ps.sharedUser != null) {
19828                boolean used = false;
19829                final int packageCount = ps.sharedUser.packages.size();
19830                for (int j = 0; j < packageCount; j++) {
19831                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19832                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19833                            && pkg.pkg.requestedPermissions.contains(permission)) {
19834                        used = true;
19835                        break;
19836                    }
19837                }
19838                if (used) {
19839                    continue;
19840                }
19841            }
19842
19843            PermissionsState permissionsState = ps.getPermissionsState();
19844
19845            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19846
19847            // Always clear the user settable flags.
19848            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19849                    bp.name) != null;
19850            // If permission review is enabled and this is a legacy app, mark the
19851            // permission as requiring a review as this is the initial state.
19852            int flags = 0;
19853            if (mPermissionReviewRequired
19854                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19855                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19856            }
19857            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19858                if (hasInstallState) {
19859                    writeInstallPermissions = true;
19860                } else {
19861                    writeRuntimePermissions = true;
19862                }
19863            }
19864
19865            // Below is only runtime permission handling.
19866            if (!bp.isRuntime()) {
19867                continue;
19868            }
19869
19870            // Never clobber system or policy.
19871            if ((oldFlags & policyOrSystemFlags) != 0) {
19872                continue;
19873            }
19874
19875            // If this permission was granted by default, make sure it is.
19876            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19877                if (permissionsState.grantRuntimePermission(bp, userId)
19878                        != PERMISSION_OPERATION_FAILURE) {
19879                    writeRuntimePermissions = true;
19880                }
19881            // If permission review is enabled the permissions for a legacy apps
19882            // are represented as constantly granted runtime ones, so don't revoke.
19883            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19884                // Otherwise, reset the permission.
19885                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19886                switch (revokeResult) {
19887                    case PERMISSION_OPERATION_SUCCESS:
19888                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19889                        writeRuntimePermissions = true;
19890                        final int appId = ps.appId;
19891                        mHandler.post(new Runnable() {
19892                            @Override
19893                            public void run() {
19894                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19895                            }
19896                        });
19897                    } break;
19898                }
19899            }
19900        }
19901
19902        // Synchronously write as we are taking permissions away.
19903        if (writeRuntimePermissions) {
19904            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19905        }
19906
19907        // Synchronously write as we are taking permissions away.
19908        if (writeInstallPermissions) {
19909            mSettings.writeLPr();
19910        }
19911    }
19912
19913    /**
19914     * Remove entries from the keystore daemon. Will only remove it if the
19915     * {@code appId} is valid.
19916     */
19917    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19918        if (appId < 0) {
19919            return;
19920        }
19921
19922        final KeyStore keyStore = KeyStore.getInstance();
19923        if (keyStore != null) {
19924            if (userId == UserHandle.USER_ALL) {
19925                for (final int individual : sUserManager.getUserIds()) {
19926                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19927                }
19928            } else {
19929                keyStore.clearUid(UserHandle.getUid(userId, appId));
19930            }
19931        } else {
19932            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19933        }
19934    }
19935
19936    @Override
19937    public void deleteApplicationCacheFiles(final String packageName,
19938            final IPackageDataObserver observer) {
19939        final int userId = UserHandle.getCallingUserId();
19940        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19941    }
19942
19943    @Override
19944    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19945            final IPackageDataObserver observer) {
19946        final int callingUid = Binder.getCallingUid();
19947        mContext.enforceCallingOrSelfPermission(
19948                android.Manifest.permission.DELETE_CACHE_FILES, null);
19949        enforceCrossUserPermission(callingUid, userId,
19950                /* requireFullPermission= */ true, /* checkShell= */ false,
19951                "delete application cache files");
19952        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19953                android.Manifest.permission.ACCESS_INSTANT_APPS);
19954
19955        final PackageParser.Package pkg;
19956        synchronized (mPackages) {
19957            pkg = mPackages.get(packageName);
19958        }
19959
19960        // Queue up an async operation since the package deletion may take a little while.
19961        mHandler.post(new Runnable() {
19962            public void run() {
19963                final PackageSetting ps = (PackageSetting) pkg.mExtras;
19964                boolean doClearData = true;
19965                if (ps != null) {
19966                    final boolean targetIsInstantApp =
19967                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19968                    doClearData = !targetIsInstantApp
19969                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19970                }
19971                if (doClearData) {
19972                    synchronized (mInstallLock) {
19973                        final int flags = StorageManager.FLAG_STORAGE_DE
19974                                | StorageManager.FLAG_STORAGE_CE;
19975                        // We're only clearing cache files, so we don't care if the
19976                        // app is unfrozen and still able to run
19977                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19978                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19979                    }
19980                    clearExternalStorageDataSync(packageName, userId, false);
19981                }
19982                if (observer != null) {
19983                    try {
19984                        observer.onRemoveCompleted(packageName, true);
19985                    } catch (RemoteException e) {
19986                        Log.i(TAG, "Observer no longer exists.");
19987                    }
19988                }
19989            }
19990        });
19991    }
19992
19993    @Override
19994    public void getPackageSizeInfo(final String packageName, int userHandle,
19995            final IPackageStatsObserver observer) {
19996        throw new UnsupportedOperationException(
19997                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19998    }
19999
20000    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20001        final PackageSetting ps;
20002        synchronized (mPackages) {
20003            ps = mSettings.mPackages.get(packageName);
20004            if (ps == null) {
20005                Slog.w(TAG, "Failed to find settings for " + packageName);
20006                return false;
20007            }
20008        }
20009
20010        final String[] packageNames = { packageName };
20011        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20012        final String[] codePaths = { ps.codePathString };
20013
20014        try {
20015            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20016                    ps.appId, ceDataInodes, codePaths, stats);
20017
20018            // For now, ignore code size of packages on system partition
20019            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20020                stats.codeSize = 0;
20021            }
20022
20023            // External clients expect these to be tracked separately
20024            stats.dataSize -= stats.cacheSize;
20025
20026        } catch (InstallerException e) {
20027            Slog.w(TAG, String.valueOf(e));
20028            return false;
20029        }
20030
20031        return true;
20032    }
20033
20034    private int getUidTargetSdkVersionLockedLPr(int uid) {
20035        Object obj = mSettings.getUserIdLPr(uid);
20036        if (obj instanceof SharedUserSetting) {
20037            final SharedUserSetting sus = (SharedUserSetting) obj;
20038            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20039            final Iterator<PackageSetting> it = sus.packages.iterator();
20040            while (it.hasNext()) {
20041                final PackageSetting ps = it.next();
20042                if (ps.pkg != null) {
20043                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20044                    if (v < vers) vers = v;
20045                }
20046            }
20047            return vers;
20048        } else if (obj instanceof PackageSetting) {
20049            final PackageSetting ps = (PackageSetting) obj;
20050            if (ps.pkg != null) {
20051                return ps.pkg.applicationInfo.targetSdkVersion;
20052            }
20053        }
20054        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20055    }
20056
20057    @Override
20058    public void addPreferredActivity(IntentFilter filter, int match,
20059            ComponentName[] set, ComponentName activity, int userId) {
20060        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20061                "Adding preferred");
20062    }
20063
20064    private void addPreferredActivityInternal(IntentFilter filter, int match,
20065            ComponentName[] set, ComponentName activity, boolean always, int userId,
20066            String opname) {
20067        // writer
20068        int callingUid = Binder.getCallingUid();
20069        enforceCrossUserPermission(callingUid, userId,
20070                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20071        if (filter.countActions() == 0) {
20072            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20073            return;
20074        }
20075        synchronized (mPackages) {
20076            if (mContext.checkCallingOrSelfPermission(
20077                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20078                    != PackageManager.PERMISSION_GRANTED) {
20079                if (getUidTargetSdkVersionLockedLPr(callingUid)
20080                        < Build.VERSION_CODES.FROYO) {
20081                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20082                            + callingUid);
20083                    return;
20084                }
20085                mContext.enforceCallingOrSelfPermission(
20086                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20087            }
20088
20089            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20090            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20091                    + userId + ":");
20092            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20093            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20094            scheduleWritePackageRestrictionsLocked(userId);
20095            postPreferredActivityChangedBroadcast(userId);
20096        }
20097    }
20098
20099    private void postPreferredActivityChangedBroadcast(int userId) {
20100        mHandler.post(() -> {
20101            final IActivityManager am = ActivityManager.getService();
20102            if (am == null) {
20103                return;
20104            }
20105
20106            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20107            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20108            try {
20109                am.broadcastIntent(null, intent, null, null,
20110                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20111                        null, false, false, userId);
20112            } catch (RemoteException e) {
20113            }
20114        });
20115    }
20116
20117    @Override
20118    public void replacePreferredActivity(IntentFilter filter, int match,
20119            ComponentName[] set, ComponentName activity, int userId) {
20120        if (filter.countActions() != 1) {
20121            throw new IllegalArgumentException(
20122                    "replacePreferredActivity expects filter to have only 1 action.");
20123        }
20124        if (filter.countDataAuthorities() != 0
20125                || filter.countDataPaths() != 0
20126                || filter.countDataSchemes() > 1
20127                || filter.countDataTypes() != 0) {
20128            throw new IllegalArgumentException(
20129                    "replacePreferredActivity expects filter to have no data authorities, " +
20130                    "paths, or types; and at most one scheme.");
20131        }
20132
20133        final int callingUid = Binder.getCallingUid();
20134        enforceCrossUserPermission(callingUid, userId,
20135                true /* requireFullPermission */, false /* checkShell */,
20136                "replace preferred activity");
20137        synchronized (mPackages) {
20138            if (mContext.checkCallingOrSelfPermission(
20139                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20140                    != PackageManager.PERMISSION_GRANTED) {
20141                if (getUidTargetSdkVersionLockedLPr(callingUid)
20142                        < Build.VERSION_CODES.FROYO) {
20143                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20144                            + Binder.getCallingUid());
20145                    return;
20146                }
20147                mContext.enforceCallingOrSelfPermission(
20148                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20149            }
20150
20151            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20152            if (pir != null) {
20153                // Get all of the existing entries that exactly match this filter.
20154                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20155                if (existing != null && existing.size() == 1) {
20156                    PreferredActivity cur = existing.get(0);
20157                    if (DEBUG_PREFERRED) {
20158                        Slog.i(TAG, "Checking replace of preferred:");
20159                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20160                        if (!cur.mPref.mAlways) {
20161                            Slog.i(TAG, "  -- CUR; not mAlways!");
20162                        } else {
20163                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20164                            Slog.i(TAG, "  -- CUR: mSet="
20165                                    + Arrays.toString(cur.mPref.mSetComponents));
20166                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20167                            Slog.i(TAG, "  -- NEW: mMatch="
20168                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20169                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20170                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20171                        }
20172                    }
20173                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20174                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20175                            && cur.mPref.sameSet(set)) {
20176                        // Setting the preferred activity to what it happens to be already
20177                        if (DEBUG_PREFERRED) {
20178                            Slog.i(TAG, "Replacing with same preferred activity "
20179                                    + cur.mPref.mShortComponent + " for user "
20180                                    + userId + ":");
20181                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20182                        }
20183                        return;
20184                    }
20185                }
20186
20187                if (existing != null) {
20188                    if (DEBUG_PREFERRED) {
20189                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20190                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20191                    }
20192                    for (int i = 0; i < existing.size(); i++) {
20193                        PreferredActivity pa = existing.get(i);
20194                        if (DEBUG_PREFERRED) {
20195                            Slog.i(TAG, "Removing existing preferred activity "
20196                                    + pa.mPref.mComponent + ":");
20197                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20198                        }
20199                        pir.removeFilter(pa);
20200                    }
20201                }
20202            }
20203            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20204                    "Replacing preferred");
20205        }
20206    }
20207
20208    @Override
20209    public void clearPackagePreferredActivities(String packageName) {
20210        final int callingUid = Binder.getCallingUid();
20211        if (getInstantAppPackageName(callingUid) != null) {
20212            return;
20213        }
20214        // writer
20215        synchronized (mPackages) {
20216            PackageParser.Package pkg = mPackages.get(packageName);
20217            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20218                if (mContext.checkCallingOrSelfPermission(
20219                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20220                        != PackageManager.PERMISSION_GRANTED) {
20221                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20222                            < Build.VERSION_CODES.FROYO) {
20223                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20224                                + callingUid);
20225                        return;
20226                    }
20227                    mContext.enforceCallingOrSelfPermission(
20228                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20229                }
20230            }
20231            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20232            if (ps != null
20233                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20234                return;
20235            }
20236            int user = UserHandle.getCallingUserId();
20237            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20238                scheduleWritePackageRestrictionsLocked(user);
20239            }
20240        }
20241    }
20242
20243    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20244    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20245        ArrayList<PreferredActivity> removed = null;
20246        boolean changed = false;
20247        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20248            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20249            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20250            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20251                continue;
20252            }
20253            Iterator<PreferredActivity> it = pir.filterIterator();
20254            while (it.hasNext()) {
20255                PreferredActivity pa = it.next();
20256                // Mark entry for removal only if it matches the package name
20257                // and the entry is of type "always".
20258                if (packageName == null ||
20259                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20260                                && pa.mPref.mAlways)) {
20261                    if (removed == null) {
20262                        removed = new ArrayList<PreferredActivity>();
20263                    }
20264                    removed.add(pa);
20265                }
20266            }
20267            if (removed != null) {
20268                for (int j=0; j<removed.size(); j++) {
20269                    PreferredActivity pa = removed.get(j);
20270                    pir.removeFilter(pa);
20271                }
20272                changed = true;
20273            }
20274        }
20275        if (changed) {
20276            postPreferredActivityChangedBroadcast(userId);
20277        }
20278        return changed;
20279    }
20280
20281    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20282    private void clearIntentFilterVerificationsLPw(int userId) {
20283        final int packageCount = mPackages.size();
20284        for (int i = 0; i < packageCount; i++) {
20285            PackageParser.Package pkg = mPackages.valueAt(i);
20286            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20287        }
20288    }
20289
20290    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20291    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20292        if (userId == UserHandle.USER_ALL) {
20293            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20294                    sUserManager.getUserIds())) {
20295                for (int oneUserId : sUserManager.getUserIds()) {
20296                    scheduleWritePackageRestrictionsLocked(oneUserId);
20297                }
20298            }
20299        } else {
20300            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20301                scheduleWritePackageRestrictionsLocked(userId);
20302            }
20303        }
20304    }
20305
20306    /** Clears state for all users, and touches intent filter verification policy */
20307    void clearDefaultBrowserIfNeeded(String packageName) {
20308        for (int oneUserId : sUserManager.getUserIds()) {
20309            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20310        }
20311    }
20312
20313    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20314        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20315        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20316            if (packageName.equals(defaultBrowserPackageName)) {
20317                setDefaultBrowserPackageName(null, userId);
20318            }
20319        }
20320    }
20321
20322    @Override
20323    public void resetApplicationPreferences(int userId) {
20324        mContext.enforceCallingOrSelfPermission(
20325                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20326        final long identity = Binder.clearCallingIdentity();
20327        // writer
20328        try {
20329            synchronized (mPackages) {
20330                clearPackagePreferredActivitiesLPw(null, userId);
20331                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20332                // TODO: We have to reset the default SMS and Phone. This requires
20333                // significant refactoring to keep all default apps in the package
20334                // manager (cleaner but more work) or have the services provide
20335                // callbacks to the package manager to request a default app reset.
20336                applyFactoryDefaultBrowserLPw(userId);
20337                clearIntentFilterVerificationsLPw(userId);
20338                primeDomainVerificationsLPw(userId);
20339                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20340                scheduleWritePackageRestrictionsLocked(userId);
20341            }
20342            resetNetworkPolicies(userId);
20343        } finally {
20344            Binder.restoreCallingIdentity(identity);
20345        }
20346    }
20347
20348    @Override
20349    public int getPreferredActivities(List<IntentFilter> outFilters,
20350            List<ComponentName> outActivities, String packageName) {
20351        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20352            return 0;
20353        }
20354        int num = 0;
20355        final int userId = UserHandle.getCallingUserId();
20356        // reader
20357        synchronized (mPackages) {
20358            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20359            if (pir != null) {
20360                final Iterator<PreferredActivity> it = pir.filterIterator();
20361                while (it.hasNext()) {
20362                    final PreferredActivity pa = it.next();
20363                    if (packageName == null
20364                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20365                                    && pa.mPref.mAlways)) {
20366                        if (outFilters != null) {
20367                            outFilters.add(new IntentFilter(pa));
20368                        }
20369                        if (outActivities != null) {
20370                            outActivities.add(pa.mPref.mComponent);
20371                        }
20372                    }
20373                }
20374            }
20375        }
20376
20377        return num;
20378    }
20379
20380    @Override
20381    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20382            int userId) {
20383        int callingUid = Binder.getCallingUid();
20384        if (callingUid != Process.SYSTEM_UID) {
20385            throw new SecurityException(
20386                    "addPersistentPreferredActivity can only be run by the system");
20387        }
20388        if (filter.countActions() == 0) {
20389            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20390            return;
20391        }
20392        synchronized (mPackages) {
20393            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20394                    ":");
20395            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20396            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20397                    new PersistentPreferredActivity(filter, activity));
20398            scheduleWritePackageRestrictionsLocked(userId);
20399            postPreferredActivityChangedBroadcast(userId);
20400        }
20401    }
20402
20403    @Override
20404    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20405        int callingUid = Binder.getCallingUid();
20406        if (callingUid != Process.SYSTEM_UID) {
20407            throw new SecurityException(
20408                    "clearPackagePersistentPreferredActivities can only be run by the system");
20409        }
20410        ArrayList<PersistentPreferredActivity> removed = null;
20411        boolean changed = false;
20412        synchronized (mPackages) {
20413            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20414                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20415                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20416                        .valueAt(i);
20417                if (userId != thisUserId) {
20418                    continue;
20419                }
20420                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20421                while (it.hasNext()) {
20422                    PersistentPreferredActivity ppa = it.next();
20423                    // Mark entry for removal only if it matches the package name.
20424                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20425                        if (removed == null) {
20426                            removed = new ArrayList<PersistentPreferredActivity>();
20427                        }
20428                        removed.add(ppa);
20429                    }
20430                }
20431                if (removed != null) {
20432                    for (int j=0; j<removed.size(); j++) {
20433                        PersistentPreferredActivity ppa = removed.get(j);
20434                        ppir.removeFilter(ppa);
20435                    }
20436                    changed = true;
20437                }
20438            }
20439
20440            if (changed) {
20441                scheduleWritePackageRestrictionsLocked(userId);
20442                postPreferredActivityChangedBroadcast(userId);
20443            }
20444        }
20445    }
20446
20447    /**
20448     * Common machinery for picking apart a restored XML blob and passing
20449     * it to a caller-supplied functor to be applied to the running system.
20450     */
20451    private void restoreFromXml(XmlPullParser parser, int userId,
20452            String expectedStartTag, BlobXmlRestorer functor)
20453            throws IOException, XmlPullParserException {
20454        int type;
20455        while ((type = parser.next()) != XmlPullParser.START_TAG
20456                && type != XmlPullParser.END_DOCUMENT) {
20457        }
20458        if (type != XmlPullParser.START_TAG) {
20459            // oops didn't find a start tag?!
20460            if (DEBUG_BACKUP) {
20461                Slog.e(TAG, "Didn't find start tag during restore");
20462            }
20463            return;
20464        }
20465Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20466        // this is supposed to be TAG_PREFERRED_BACKUP
20467        if (!expectedStartTag.equals(parser.getName())) {
20468            if (DEBUG_BACKUP) {
20469                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20470            }
20471            return;
20472        }
20473
20474        // skip interfering stuff, then we're aligned with the backing implementation
20475        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20476Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20477        functor.apply(parser, userId);
20478    }
20479
20480    private interface BlobXmlRestorer {
20481        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20482    }
20483
20484    /**
20485     * Non-Binder method, support for the backup/restore mechanism: write the
20486     * full set of preferred activities in its canonical XML format.  Returns the
20487     * XML output as a byte array, or null if there is none.
20488     */
20489    @Override
20490    public byte[] getPreferredActivityBackup(int userId) {
20491        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20492            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20493        }
20494
20495        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20496        try {
20497            final XmlSerializer serializer = new FastXmlSerializer();
20498            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20499            serializer.startDocument(null, true);
20500            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20501
20502            synchronized (mPackages) {
20503                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20504            }
20505
20506            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20507            serializer.endDocument();
20508            serializer.flush();
20509        } catch (Exception e) {
20510            if (DEBUG_BACKUP) {
20511                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20512            }
20513            return null;
20514        }
20515
20516        return dataStream.toByteArray();
20517    }
20518
20519    @Override
20520    public void restorePreferredActivities(byte[] backup, int userId) {
20521        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20522            throw new SecurityException("Only the system may call restorePreferredActivities()");
20523        }
20524
20525        try {
20526            final XmlPullParser parser = Xml.newPullParser();
20527            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20528            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20529                    new BlobXmlRestorer() {
20530                        @Override
20531                        public void apply(XmlPullParser parser, int userId)
20532                                throws XmlPullParserException, IOException {
20533                            synchronized (mPackages) {
20534                                mSettings.readPreferredActivitiesLPw(parser, userId);
20535                            }
20536                        }
20537                    } );
20538        } catch (Exception e) {
20539            if (DEBUG_BACKUP) {
20540                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20541            }
20542        }
20543    }
20544
20545    /**
20546     * Non-Binder method, support for the backup/restore mechanism: write the
20547     * default browser (etc) settings in its canonical XML format.  Returns the default
20548     * browser XML representation as a byte array, or null if there is none.
20549     */
20550    @Override
20551    public byte[] getDefaultAppsBackup(int userId) {
20552        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20553            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20554        }
20555
20556        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20557        try {
20558            final XmlSerializer serializer = new FastXmlSerializer();
20559            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20560            serializer.startDocument(null, true);
20561            serializer.startTag(null, TAG_DEFAULT_APPS);
20562
20563            synchronized (mPackages) {
20564                mSettings.writeDefaultAppsLPr(serializer, userId);
20565            }
20566
20567            serializer.endTag(null, TAG_DEFAULT_APPS);
20568            serializer.endDocument();
20569            serializer.flush();
20570        } catch (Exception e) {
20571            if (DEBUG_BACKUP) {
20572                Slog.e(TAG, "Unable to write default apps for backup", e);
20573            }
20574            return null;
20575        }
20576
20577        return dataStream.toByteArray();
20578    }
20579
20580    @Override
20581    public void restoreDefaultApps(byte[] backup, int userId) {
20582        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20583            throw new SecurityException("Only the system may call restoreDefaultApps()");
20584        }
20585
20586        try {
20587            final XmlPullParser parser = Xml.newPullParser();
20588            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20589            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20590                    new BlobXmlRestorer() {
20591                        @Override
20592                        public void apply(XmlPullParser parser, int userId)
20593                                throws XmlPullParserException, IOException {
20594                            synchronized (mPackages) {
20595                                mSettings.readDefaultAppsLPw(parser, userId);
20596                            }
20597                        }
20598                    } );
20599        } catch (Exception e) {
20600            if (DEBUG_BACKUP) {
20601                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20602            }
20603        }
20604    }
20605
20606    @Override
20607    public byte[] getIntentFilterVerificationBackup(int userId) {
20608        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20609            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20610        }
20611
20612        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20613        try {
20614            final XmlSerializer serializer = new FastXmlSerializer();
20615            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20616            serializer.startDocument(null, true);
20617            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20618
20619            synchronized (mPackages) {
20620                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20621            }
20622
20623            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20624            serializer.endDocument();
20625            serializer.flush();
20626        } catch (Exception e) {
20627            if (DEBUG_BACKUP) {
20628                Slog.e(TAG, "Unable to write default apps for backup", e);
20629            }
20630            return null;
20631        }
20632
20633        return dataStream.toByteArray();
20634    }
20635
20636    @Override
20637    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20638        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20639            throw new SecurityException("Only the system may call restorePreferredActivities()");
20640        }
20641
20642        try {
20643            final XmlPullParser parser = Xml.newPullParser();
20644            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20645            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20646                    new BlobXmlRestorer() {
20647                        @Override
20648                        public void apply(XmlPullParser parser, int userId)
20649                                throws XmlPullParserException, IOException {
20650                            synchronized (mPackages) {
20651                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20652                                mSettings.writeLPr();
20653                            }
20654                        }
20655                    } );
20656        } catch (Exception e) {
20657            if (DEBUG_BACKUP) {
20658                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20659            }
20660        }
20661    }
20662
20663    @Override
20664    public byte[] getPermissionGrantBackup(int userId) {
20665        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20666            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20667        }
20668
20669        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20670        try {
20671            final XmlSerializer serializer = new FastXmlSerializer();
20672            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20673            serializer.startDocument(null, true);
20674            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20675
20676            synchronized (mPackages) {
20677                serializeRuntimePermissionGrantsLPr(serializer, userId);
20678            }
20679
20680            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20681            serializer.endDocument();
20682            serializer.flush();
20683        } catch (Exception e) {
20684            if (DEBUG_BACKUP) {
20685                Slog.e(TAG, "Unable to write default apps for backup", e);
20686            }
20687            return null;
20688        }
20689
20690        return dataStream.toByteArray();
20691    }
20692
20693    @Override
20694    public void restorePermissionGrants(byte[] backup, int userId) {
20695        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20696            throw new SecurityException("Only the system may call restorePermissionGrants()");
20697        }
20698
20699        try {
20700            final XmlPullParser parser = Xml.newPullParser();
20701            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20702            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20703                    new BlobXmlRestorer() {
20704                        @Override
20705                        public void apply(XmlPullParser parser, int userId)
20706                                throws XmlPullParserException, IOException {
20707                            synchronized (mPackages) {
20708                                processRestoredPermissionGrantsLPr(parser, userId);
20709                            }
20710                        }
20711                    } );
20712        } catch (Exception e) {
20713            if (DEBUG_BACKUP) {
20714                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20715            }
20716        }
20717    }
20718
20719    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20720            throws IOException {
20721        serializer.startTag(null, TAG_ALL_GRANTS);
20722
20723        final int N = mSettings.mPackages.size();
20724        for (int i = 0; i < N; i++) {
20725            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20726            boolean pkgGrantsKnown = false;
20727
20728            PermissionsState packagePerms = ps.getPermissionsState();
20729
20730            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20731                final int grantFlags = state.getFlags();
20732                // only look at grants that are not system/policy fixed
20733                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20734                    final boolean isGranted = state.isGranted();
20735                    // And only back up the user-twiddled state bits
20736                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20737                        final String packageName = mSettings.mPackages.keyAt(i);
20738                        if (!pkgGrantsKnown) {
20739                            serializer.startTag(null, TAG_GRANT);
20740                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20741                            pkgGrantsKnown = true;
20742                        }
20743
20744                        final boolean userSet =
20745                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20746                        final boolean userFixed =
20747                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20748                        final boolean revoke =
20749                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20750
20751                        serializer.startTag(null, TAG_PERMISSION);
20752                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20753                        if (isGranted) {
20754                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20755                        }
20756                        if (userSet) {
20757                            serializer.attribute(null, ATTR_USER_SET, "true");
20758                        }
20759                        if (userFixed) {
20760                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20761                        }
20762                        if (revoke) {
20763                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20764                        }
20765                        serializer.endTag(null, TAG_PERMISSION);
20766                    }
20767                }
20768            }
20769
20770            if (pkgGrantsKnown) {
20771                serializer.endTag(null, TAG_GRANT);
20772            }
20773        }
20774
20775        serializer.endTag(null, TAG_ALL_GRANTS);
20776    }
20777
20778    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20779            throws XmlPullParserException, IOException {
20780        String pkgName = null;
20781        int outerDepth = parser.getDepth();
20782        int type;
20783        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20784                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20785            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20786                continue;
20787            }
20788
20789            final String tagName = parser.getName();
20790            if (tagName.equals(TAG_GRANT)) {
20791                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20792                if (DEBUG_BACKUP) {
20793                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20794                }
20795            } else if (tagName.equals(TAG_PERMISSION)) {
20796
20797                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20798                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20799
20800                int newFlagSet = 0;
20801                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20802                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20803                }
20804                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20805                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20806                }
20807                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20808                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20809                }
20810                if (DEBUG_BACKUP) {
20811                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20812                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20813                }
20814                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20815                if (ps != null) {
20816                    // Already installed so we apply the grant immediately
20817                    if (DEBUG_BACKUP) {
20818                        Slog.v(TAG, "        + already installed; applying");
20819                    }
20820                    PermissionsState perms = ps.getPermissionsState();
20821                    BasePermission bp = mSettings.mPermissions.get(permName);
20822                    if (bp != null) {
20823                        if (isGranted) {
20824                            perms.grantRuntimePermission(bp, userId);
20825                        }
20826                        if (newFlagSet != 0) {
20827                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20828                        }
20829                    }
20830                } else {
20831                    // Need to wait for post-restore install to apply the grant
20832                    if (DEBUG_BACKUP) {
20833                        Slog.v(TAG, "        - not yet installed; saving for later");
20834                    }
20835                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20836                            isGranted, newFlagSet, userId);
20837                }
20838            } else {
20839                PackageManagerService.reportSettingsProblem(Log.WARN,
20840                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20841                XmlUtils.skipCurrentTag(parser);
20842            }
20843        }
20844
20845        scheduleWriteSettingsLocked();
20846        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20847    }
20848
20849    @Override
20850    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20851            int sourceUserId, int targetUserId, int flags) {
20852        mContext.enforceCallingOrSelfPermission(
20853                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20854        int callingUid = Binder.getCallingUid();
20855        enforceOwnerRights(ownerPackage, callingUid);
20856        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20857        if (intentFilter.countActions() == 0) {
20858            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20859            return;
20860        }
20861        synchronized (mPackages) {
20862            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20863                    ownerPackage, targetUserId, flags);
20864            CrossProfileIntentResolver resolver =
20865                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20866            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20867            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20868            if (existing != null) {
20869                int size = existing.size();
20870                for (int i = 0; i < size; i++) {
20871                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20872                        return;
20873                    }
20874                }
20875            }
20876            resolver.addFilter(newFilter);
20877            scheduleWritePackageRestrictionsLocked(sourceUserId);
20878        }
20879    }
20880
20881    @Override
20882    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20883        mContext.enforceCallingOrSelfPermission(
20884                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20885        final int callingUid = Binder.getCallingUid();
20886        enforceOwnerRights(ownerPackage, callingUid);
20887        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20888        synchronized (mPackages) {
20889            CrossProfileIntentResolver resolver =
20890                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20891            ArraySet<CrossProfileIntentFilter> set =
20892                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20893            for (CrossProfileIntentFilter filter : set) {
20894                if (filter.getOwnerPackage().equals(ownerPackage)) {
20895                    resolver.removeFilter(filter);
20896                }
20897            }
20898            scheduleWritePackageRestrictionsLocked(sourceUserId);
20899        }
20900    }
20901
20902    // Enforcing that callingUid is owning pkg on userId
20903    private void enforceOwnerRights(String pkg, int callingUid) {
20904        // The system owns everything.
20905        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20906            return;
20907        }
20908        final int callingUserId = UserHandle.getUserId(callingUid);
20909        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20910        if (pi == null) {
20911            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20912                    + callingUserId);
20913        }
20914        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20915            throw new SecurityException("Calling uid " + callingUid
20916                    + " does not own package " + pkg);
20917        }
20918    }
20919
20920    @Override
20921    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20922        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20923            return null;
20924        }
20925        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20926    }
20927
20928    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20929        UserManagerService ums = UserManagerService.getInstance();
20930        if (ums != null) {
20931            final UserInfo parent = ums.getProfileParent(userId);
20932            final int launcherUid = (parent != null) ? parent.id : userId;
20933            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20934            if (launcherComponent != null) {
20935                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20936                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20937                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20938                        .setPackage(launcherComponent.getPackageName());
20939                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20940            }
20941        }
20942    }
20943
20944    /**
20945     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20946     * then reports the most likely home activity or null if there are more than one.
20947     */
20948    private ComponentName getDefaultHomeActivity(int userId) {
20949        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20950        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20951        if (cn != null) {
20952            return cn;
20953        }
20954
20955        // Find the launcher with the highest priority and return that component if there are no
20956        // other home activity with the same priority.
20957        int lastPriority = Integer.MIN_VALUE;
20958        ComponentName lastComponent = null;
20959        final int size = allHomeCandidates.size();
20960        for (int i = 0; i < size; i++) {
20961            final ResolveInfo ri = allHomeCandidates.get(i);
20962            if (ri.priority > lastPriority) {
20963                lastComponent = ri.activityInfo.getComponentName();
20964                lastPriority = ri.priority;
20965            } else if (ri.priority == lastPriority) {
20966                // Two components found with same priority.
20967                lastComponent = null;
20968            }
20969        }
20970        return lastComponent;
20971    }
20972
20973    private Intent getHomeIntent() {
20974        Intent intent = new Intent(Intent.ACTION_MAIN);
20975        intent.addCategory(Intent.CATEGORY_HOME);
20976        intent.addCategory(Intent.CATEGORY_DEFAULT);
20977        return intent;
20978    }
20979
20980    private IntentFilter getHomeFilter() {
20981        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20982        filter.addCategory(Intent.CATEGORY_HOME);
20983        filter.addCategory(Intent.CATEGORY_DEFAULT);
20984        return filter;
20985    }
20986
20987    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20988            int userId) {
20989        Intent intent  = getHomeIntent();
20990        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20991                PackageManager.GET_META_DATA, userId);
20992        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20993                true, false, false, userId);
20994
20995        allHomeCandidates.clear();
20996        if (list != null) {
20997            for (ResolveInfo ri : list) {
20998                allHomeCandidates.add(ri);
20999            }
21000        }
21001        return (preferred == null || preferred.activityInfo == null)
21002                ? null
21003                : new ComponentName(preferred.activityInfo.packageName,
21004                        preferred.activityInfo.name);
21005    }
21006
21007    @Override
21008    public void setHomeActivity(ComponentName comp, int userId) {
21009        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21010            return;
21011        }
21012        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21013        getHomeActivitiesAsUser(homeActivities, userId);
21014
21015        boolean found = false;
21016
21017        final int size = homeActivities.size();
21018        final ComponentName[] set = new ComponentName[size];
21019        for (int i = 0; i < size; i++) {
21020            final ResolveInfo candidate = homeActivities.get(i);
21021            final ActivityInfo info = candidate.activityInfo;
21022            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21023            set[i] = activityName;
21024            if (!found && activityName.equals(comp)) {
21025                found = true;
21026            }
21027        }
21028        if (!found) {
21029            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21030                    + userId);
21031        }
21032        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21033                set, comp, userId);
21034    }
21035
21036    private @Nullable String getSetupWizardPackageName() {
21037        final Intent intent = new Intent(Intent.ACTION_MAIN);
21038        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21039
21040        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21041                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21042                        | MATCH_DISABLED_COMPONENTS,
21043                UserHandle.myUserId());
21044        if (matches.size() == 1) {
21045            return matches.get(0).getComponentInfo().packageName;
21046        } else {
21047            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21048                    + ": matches=" + matches);
21049            return null;
21050        }
21051    }
21052
21053    private @Nullable String getStorageManagerPackageName() {
21054        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21055
21056        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21057                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21058                        | MATCH_DISABLED_COMPONENTS,
21059                UserHandle.myUserId());
21060        if (matches.size() == 1) {
21061            return matches.get(0).getComponentInfo().packageName;
21062        } else {
21063            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21064                    + matches.size() + ": matches=" + matches);
21065            return null;
21066        }
21067    }
21068
21069    @Override
21070    public void setApplicationEnabledSetting(String appPackageName,
21071            int newState, int flags, int userId, String callingPackage) {
21072        if (!sUserManager.exists(userId)) return;
21073        if (callingPackage == null) {
21074            callingPackage = Integer.toString(Binder.getCallingUid());
21075        }
21076        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21077    }
21078
21079    @Override
21080    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21081        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21082        synchronized (mPackages) {
21083            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21084            if (pkgSetting != null) {
21085                pkgSetting.setUpdateAvailable(updateAvailable);
21086            }
21087        }
21088    }
21089
21090    @Override
21091    public void setComponentEnabledSetting(ComponentName componentName,
21092            int newState, int flags, int userId) {
21093        if (!sUserManager.exists(userId)) return;
21094        setEnabledSetting(componentName.getPackageName(),
21095                componentName.getClassName(), newState, flags, userId, null);
21096    }
21097
21098    private void setEnabledSetting(final String packageName, String className, int newState,
21099            final int flags, int userId, String callingPackage) {
21100        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21101              || newState == COMPONENT_ENABLED_STATE_ENABLED
21102              || newState == COMPONENT_ENABLED_STATE_DISABLED
21103              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21104              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21105            throw new IllegalArgumentException("Invalid new component state: "
21106                    + newState);
21107        }
21108        PackageSetting pkgSetting;
21109        final int callingUid = Binder.getCallingUid();
21110        final int permission;
21111        if (callingUid == Process.SYSTEM_UID) {
21112            permission = PackageManager.PERMISSION_GRANTED;
21113        } else {
21114            permission = mContext.checkCallingOrSelfPermission(
21115                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21116        }
21117        enforceCrossUserPermission(callingUid, userId,
21118                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21119        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21120        boolean sendNow = false;
21121        boolean isApp = (className == null);
21122        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21123        String componentName = isApp ? packageName : className;
21124        int packageUid = -1;
21125        ArrayList<String> components;
21126
21127        // reader
21128        synchronized (mPackages) {
21129            pkgSetting = mSettings.mPackages.get(packageName);
21130            if (pkgSetting == null) {
21131                if (!isCallerInstantApp) {
21132                    if (className == null) {
21133                        throw new IllegalArgumentException("Unknown package: " + packageName);
21134                    }
21135                    throw new IllegalArgumentException(
21136                            "Unknown component: " + packageName + "/" + className);
21137                } else {
21138                    // throw SecurityException to prevent leaking package information
21139                    throw new SecurityException(
21140                            "Attempt to change component state; "
21141                            + "pid=" + Binder.getCallingPid()
21142                            + ", uid=" + callingUid
21143                            + (className == null
21144                                    ? ", package=" + packageName
21145                                    : ", component=" + packageName + "/" + className));
21146                }
21147            }
21148        }
21149
21150        // Limit who can change which apps
21151        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21152            // Don't allow apps that don't have permission to modify other apps
21153            if (!allowedByPermission
21154                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21155                throw new SecurityException(
21156                        "Attempt to change component state; "
21157                        + "pid=" + Binder.getCallingPid()
21158                        + ", uid=" + callingUid
21159                        + (className == null
21160                                ? ", package=" + packageName
21161                                : ", component=" + packageName + "/" + className));
21162            }
21163            // Don't allow changing protected packages.
21164            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21165                throw new SecurityException("Cannot disable a protected package: " + packageName);
21166            }
21167        }
21168
21169        synchronized (mPackages) {
21170            if (callingUid == Process.SHELL_UID
21171                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21172                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21173                // unless it is a test package.
21174                int oldState = pkgSetting.getEnabled(userId);
21175                if (className == null
21176                    &&
21177                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21178                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21179                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21180                    &&
21181                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21182                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21183                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21184                    // ok
21185                } else {
21186                    throw new SecurityException(
21187                            "Shell cannot change component state for " + packageName + "/"
21188                            + className + " to " + newState);
21189                }
21190            }
21191            if (className == null) {
21192                // We're dealing with an application/package level state change
21193                if (pkgSetting.getEnabled(userId) == newState) {
21194                    // Nothing to do
21195                    return;
21196                }
21197                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21198                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21199                    // Don't care about who enables an app.
21200                    callingPackage = null;
21201                }
21202                pkgSetting.setEnabled(newState, userId, callingPackage);
21203                // pkgSetting.pkg.mSetEnabled = newState;
21204            } else {
21205                // We're dealing with a component level state change
21206                // First, verify that this is a valid class name.
21207                PackageParser.Package pkg = pkgSetting.pkg;
21208                if (pkg == null || !pkg.hasComponentClassName(className)) {
21209                    if (pkg != null &&
21210                            pkg.applicationInfo.targetSdkVersion >=
21211                                    Build.VERSION_CODES.JELLY_BEAN) {
21212                        throw new IllegalArgumentException("Component class " + className
21213                                + " does not exist in " + packageName);
21214                    } else {
21215                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21216                                + className + " does not exist in " + packageName);
21217                    }
21218                }
21219                switch (newState) {
21220                case COMPONENT_ENABLED_STATE_ENABLED:
21221                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21222                        return;
21223                    }
21224                    break;
21225                case COMPONENT_ENABLED_STATE_DISABLED:
21226                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21227                        return;
21228                    }
21229                    break;
21230                case COMPONENT_ENABLED_STATE_DEFAULT:
21231                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21232                        return;
21233                    }
21234                    break;
21235                default:
21236                    Slog.e(TAG, "Invalid new component state: " + newState);
21237                    return;
21238                }
21239            }
21240            scheduleWritePackageRestrictionsLocked(userId);
21241            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21242            final long callingId = Binder.clearCallingIdentity();
21243            try {
21244                updateInstantAppInstallerLocked(packageName);
21245            } finally {
21246                Binder.restoreCallingIdentity(callingId);
21247            }
21248            components = mPendingBroadcasts.get(userId, packageName);
21249            final boolean newPackage = components == null;
21250            if (newPackage) {
21251                components = new ArrayList<String>();
21252            }
21253            if (!components.contains(componentName)) {
21254                components.add(componentName);
21255            }
21256            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21257                sendNow = true;
21258                // Purge entry from pending broadcast list if another one exists already
21259                // since we are sending one right away.
21260                mPendingBroadcasts.remove(userId, packageName);
21261            } else {
21262                if (newPackage) {
21263                    mPendingBroadcasts.put(userId, packageName, components);
21264                }
21265                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21266                    // Schedule a message
21267                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21268                }
21269            }
21270        }
21271
21272        long callingId = Binder.clearCallingIdentity();
21273        try {
21274            if (sendNow) {
21275                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21276                sendPackageChangedBroadcast(packageName,
21277                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21278            }
21279        } finally {
21280            Binder.restoreCallingIdentity(callingId);
21281        }
21282    }
21283
21284    @Override
21285    public void flushPackageRestrictionsAsUser(int userId) {
21286        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21287            return;
21288        }
21289        if (!sUserManager.exists(userId)) {
21290            return;
21291        }
21292        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21293                false /* checkShell */, "flushPackageRestrictions");
21294        synchronized (mPackages) {
21295            mSettings.writePackageRestrictionsLPr(userId);
21296            mDirtyUsers.remove(userId);
21297            if (mDirtyUsers.isEmpty()) {
21298                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21299            }
21300        }
21301    }
21302
21303    private void sendPackageChangedBroadcast(String packageName,
21304            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21305        if (DEBUG_INSTALL)
21306            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21307                    + componentNames);
21308        Bundle extras = new Bundle(4);
21309        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21310        String nameList[] = new String[componentNames.size()];
21311        componentNames.toArray(nameList);
21312        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21313        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21314        extras.putInt(Intent.EXTRA_UID, packageUid);
21315        // If this is not reporting a change of the overall package, then only send it
21316        // to registered receivers.  We don't want to launch a swath of apps for every
21317        // little component state change.
21318        final int flags = !componentNames.contains(packageName)
21319                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21320        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21321                new int[] {UserHandle.getUserId(packageUid)});
21322    }
21323
21324    @Override
21325    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21326        if (!sUserManager.exists(userId)) return;
21327        final int callingUid = Binder.getCallingUid();
21328        if (getInstantAppPackageName(callingUid) != null) {
21329            return;
21330        }
21331        final int permission = mContext.checkCallingOrSelfPermission(
21332                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21333        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21334        enforceCrossUserPermission(callingUid, userId,
21335                true /* requireFullPermission */, true /* checkShell */, "stop package");
21336        // writer
21337        synchronized (mPackages) {
21338            final PackageSetting ps = mSettings.mPackages.get(packageName);
21339            if (!filterAppAccessLPr(ps, callingUid, userId)
21340                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21341                            allowedByPermission, callingUid, userId)) {
21342                scheduleWritePackageRestrictionsLocked(userId);
21343            }
21344        }
21345    }
21346
21347    @Override
21348    public String getInstallerPackageName(String packageName) {
21349        final int callingUid = Binder.getCallingUid();
21350        if (getInstantAppPackageName(callingUid) != null) {
21351            return null;
21352        }
21353        // reader
21354        synchronized (mPackages) {
21355            final PackageSetting ps = mSettings.mPackages.get(packageName);
21356            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21357                return null;
21358            }
21359            return mSettings.getInstallerPackageNameLPr(packageName);
21360        }
21361    }
21362
21363    public boolean isOrphaned(String packageName) {
21364        // reader
21365        synchronized (mPackages) {
21366            return mSettings.isOrphaned(packageName);
21367        }
21368    }
21369
21370    @Override
21371    public int getApplicationEnabledSetting(String packageName, int userId) {
21372        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21373        int callingUid = Binder.getCallingUid();
21374        enforceCrossUserPermission(callingUid, userId,
21375                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21376        // reader
21377        synchronized (mPackages) {
21378            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21379                return COMPONENT_ENABLED_STATE_DISABLED;
21380            }
21381            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21382        }
21383    }
21384
21385    @Override
21386    public int getComponentEnabledSetting(ComponentName component, int userId) {
21387        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21388        int callingUid = Binder.getCallingUid();
21389        enforceCrossUserPermission(callingUid, userId,
21390                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21391        synchronized (mPackages) {
21392            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21393                    component, TYPE_UNKNOWN, userId)) {
21394                return COMPONENT_ENABLED_STATE_DISABLED;
21395            }
21396            return mSettings.getComponentEnabledSettingLPr(component, userId);
21397        }
21398    }
21399
21400    @Override
21401    public void enterSafeMode() {
21402        enforceSystemOrRoot("Only the system can request entering safe mode");
21403
21404        if (!mSystemReady) {
21405            mSafeMode = true;
21406        }
21407    }
21408
21409    @Override
21410    public void systemReady() {
21411        enforceSystemOrRoot("Only the system can claim the system is ready");
21412
21413        mSystemReady = true;
21414        final ContentResolver resolver = mContext.getContentResolver();
21415        ContentObserver co = new ContentObserver(mHandler) {
21416            @Override
21417            public void onChange(boolean selfChange) {
21418                mEphemeralAppsDisabled =
21419                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21420                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21421            }
21422        };
21423        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21424                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21425                false, co, UserHandle.USER_SYSTEM);
21426        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21427                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21428        co.onChange(true);
21429
21430        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21431        // disabled after already being started.
21432        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21433                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21434
21435        // Read the compatibilty setting when the system is ready.
21436        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21437                mContext.getContentResolver(),
21438                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21439        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21440        if (DEBUG_SETTINGS) {
21441            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21442        }
21443
21444        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21445
21446        synchronized (mPackages) {
21447            // Verify that all of the preferred activity components actually
21448            // exist.  It is possible for applications to be updated and at
21449            // that point remove a previously declared activity component that
21450            // had been set as a preferred activity.  We try to clean this up
21451            // the next time we encounter that preferred activity, but it is
21452            // possible for the user flow to never be able to return to that
21453            // situation so here we do a sanity check to make sure we haven't
21454            // left any junk around.
21455            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21456            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21457                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21458                removed.clear();
21459                for (PreferredActivity pa : pir.filterSet()) {
21460                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21461                        removed.add(pa);
21462                    }
21463                }
21464                if (removed.size() > 0) {
21465                    for (int r=0; r<removed.size(); r++) {
21466                        PreferredActivity pa = removed.get(r);
21467                        Slog.w(TAG, "Removing dangling preferred activity: "
21468                                + pa.mPref.mComponent);
21469                        pir.removeFilter(pa);
21470                    }
21471                    mSettings.writePackageRestrictionsLPr(
21472                            mSettings.mPreferredActivities.keyAt(i));
21473                }
21474            }
21475
21476            for (int userId : UserManagerService.getInstance().getUserIds()) {
21477                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21478                    grantPermissionsUserIds = ArrayUtils.appendInt(
21479                            grantPermissionsUserIds, userId);
21480                }
21481            }
21482        }
21483        sUserManager.systemReady();
21484
21485        // If we upgraded grant all default permissions before kicking off.
21486        for (int userId : grantPermissionsUserIds) {
21487            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21488        }
21489
21490        // If we did not grant default permissions, we preload from this the
21491        // default permission exceptions lazily to ensure we don't hit the
21492        // disk on a new user creation.
21493        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21494            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21495        }
21496
21497        // Kick off any messages waiting for system ready
21498        if (mPostSystemReadyMessages != null) {
21499            for (Message msg : mPostSystemReadyMessages) {
21500                msg.sendToTarget();
21501            }
21502            mPostSystemReadyMessages = null;
21503        }
21504
21505        // Watch for external volumes that come and go over time
21506        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21507        storage.registerListener(mStorageListener);
21508
21509        mInstallerService.systemReady();
21510        mPackageDexOptimizer.systemReady();
21511
21512        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21513                StorageManagerInternal.class);
21514        StorageManagerInternal.addExternalStoragePolicy(
21515                new StorageManagerInternal.ExternalStorageMountPolicy() {
21516            @Override
21517            public int getMountMode(int uid, String packageName) {
21518                if (Process.isIsolated(uid)) {
21519                    return Zygote.MOUNT_EXTERNAL_NONE;
21520                }
21521                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21522                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21523                }
21524                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21525                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21526                }
21527                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21528                    return Zygote.MOUNT_EXTERNAL_READ;
21529                }
21530                return Zygote.MOUNT_EXTERNAL_WRITE;
21531            }
21532
21533            @Override
21534            public boolean hasExternalStorage(int uid, String packageName) {
21535                return true;
21536            }
21537        });
21538
21539        // Now that we're mostly running, clean up stale users and apps
21540        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21541        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21542
21543        if (mPrivappPermissionsViolations != null) {
21544            Slog.wtf(TAG,"Signature|privileged permissions not in "
21545                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21546            mPrivappPermissionsViolations = null;
21547        }
21548    }
21549
21550    public void waitForAppDataPrepared() {
21551        if (mPrepareAppDataFuture == null) {
21552            return;
21553        }
21554        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21555        mPrepareAppDataFuture = null;
21556    }
21557
21558    @Override
21559    public boolean isSafeMode() {
21560        // allow instant applications
21561        return mSafeMode;
21562    }
21563
21564    @Override
21565    public boolean hasSystemUidErrors() {
21566        // allow instant applications
21567        return mHasSystemUidErrors;
21568    }
21569
21570    static String arrayToString(int[] array) {
21571        StringBuffer buf = new StringBuffer(128);
21572        buf.append('[');
21573        if (array != null) {
21574            for (int i=0; i<array.length; i++) {
21575                if (i > 0) buf.append(", ");
21576                buf.append(array[i]);
21577            }
21578        }
21579        buf.append(']');
21580        return buf.toString();
21581    }
21582
21583    static class DumpState {
21584        public static final int DUMP_LIBS = 1 << 0;
21585        public static final int DUMP_FEATURES = 1 << 1;
21586        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21587        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21588        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21589        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21590        public static final int DUMP_PERMISSIONS = 1 << 6;
21591        public static final int DUMP_PACKAGES = 1 << 7;
21592        public static final int DUMP_SHARED_USERS = 1 << 8;
21593        public static final int DUMP_MESSAGES = 1 << 9;
21594        public static final int DUMP_PROVIDERS = 1 << 10;
21595        public static final int DUMP_VERIFIERS = 1 << 11;
21596        public static final int DUMP_PREFERRED = 1 << 12;
21597        public static final int DUMP_PREFERRED_XML = 1 << 13;
21598        public static final int DUMP_KEYSETS = 1 << 14;
21599        public static final int DUMP_VERSION = 1 << 15;
21600        public static final int DUMP_INSTALLS = 1 << 16;
21601        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21602        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21603        public static final int DUMP_FROZEN = 1 << 19;
21604        public static final int DUMP_DEXOPT = 1 << 20;
21605        public static final int DUMP_COMPILER_STATS = 1 << 21;
21606        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
21607        public static final int DUMP_CHANGES = 1 << 23;
21608
21609        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21610
21611        private int mTypes;
21612
21613        private int mOptions;
21614
21615        private boolean mTitlePrinted;
21616
21617        private SharedUserSetting mSharedUser;
21618
21619        public boolean isDumping(int type) {
21620            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21621                return true;
21622            }
21623
21624            return (mTypes & type) != 0;
21625        }
21626
21627        public void setDump(int type) {
21628            mTypes |= type;
21629        }
21630
21631        public boolean isOptionEnabled(int option) {
21632            return (mOptions & option) != 0;
21633        }
21634
21635        public void setOptionEnabled(int option) {
21636            mOptions |= option;
21637        }
21638
21639        public boolean onTitlePrinted() {
21640            final boolean printed = mTitlePrinted;
21641            mTitlePrinted = true;
21642            return printed;
21643        }
21644
21645        public boolean getTitlePrinted() {
21646            return mTitlePrinted;
21647        }
21648
21649        public void setTitlePrinted(boolean enabled) {
21650            mTitlePrinted = enabled;
21651        }
21652
21653        public SharedUserSetting getSharedUser() {
21654            return mSharedUser;
21655        }
21656
21657        public void setSharedUser(SharedUserSetting user) {
21658            mSharedUser = user;
21659        }
21660    }
21661
21662    @Override
21663    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21664            FileDescriptor err, String[] args, ShellCallback callback,
21665            ResultReceiver resultReceiver) {
21666        (new PackageManagerShellCommand(this)).exec(
21667                this, in, out, err, args, callback, resultReceiver);
21668    }
21669
21670    @Override
21671    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21672        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21673
21674        DumpState dumpState = new DumpState();
21675        boolean fullPreferred = false;
21676        boolean checkin = false;
21677
21678        String packageName = null;
21679        ArraySet<String> permissionNames = null;
21680
21681        int opti = 0;
21682        while (opti < args.length) {
21683            String opt = args[opti];
21684            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21685                break;
21686            }
21687            opti++;
21688
21689            if ("-a".equals(opt)) {
21690                // Right now we only know how to print all.
21691            } else if ("-h".equals(opt)) {
21692                pw.println("Package manager dump options:");
21693                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21694                pw.println("    --checkin: dump for a checkin");
21695                pw.println("    -f: print details of intent filters");
21696                pw.println("    -h: print this help");
21697                pw.println("  cmd may be one of:");
21698                pw.println("    l[ibraries]: list known shared libraries");
21699                pw.println("    f[eatures]: list device features");
21700                pw.println("    k[eysets]: print known keysets");
21701                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21702                pw.println("    perm[issions]: dump permissions");
21703                pw.println("    permission [name ...]: dump declaration and use of given permission");
21704                pw.println("    pref[erred]: print preferred package settings");
21705                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21706                pw.println("    prov[iders]: dump content providers");
21707                pw.println("    p[ackages]: dump installed packages");
21708                pw.println("    s[hared-users]: dump shared user IDs");
21709                pw.println("    m[essages]: print collected runtime messages");
21710                pw.println("    v[erifiers]: print package verifier info");
21711                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21712                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21713                pw.println("    version: print database version info");
21714                pw.println("    write: write current settings now");
21715                pw.println("    installs: details about install sessions");
21716                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21717                pw.println("    dexopt: dump dexopt state");
21718                pw.println("    compiler-stats: dump compiler statistics");
21719                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21720                pw.println("    <package.name>: info about given package");
21721                return;
21722            } else if ("--checkin".equals(opt)) {
21723                checkin = true;
21724            } else if ("-f".equals(opt)) {
21725                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21726            } else if ("--proto".equals(opt)) {
21727                dumpProto(fd);
21728                return;
21729            } else {
21730                pw.println("Unknown argument: " + opt + "; use -h for help");
21731            }
21732        }
21733
21734        // Is the caller requesting to dump a particular piece of data?
21735        if (opti < args.length) {
21736            String cmd = args[opti];
21737            opti++;
21738            // Is this a package name?
21739            if ("android".equals(cmd) || cmd.contains(".")) {
21740                packageName = cmd;
21741                // When dumping a single package, we always dump all of its
21742                // filter information since the amount of data will be reasonable.
21743                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21744            } else if ("check-permission".equals(cmd)) {
21745                if (opti >= args.length) {
21746                    pw.println("Error: check-permission missing permission argument");
21747                    return;
21748                }
21749                String perm = args[opti];
21750                opti++;
21751                if (opti >= args.length) {
21752                    pw.println("Error: check-permission missing package argument");
21753                    return;
21754                }
21755
21756                String pkg = args[opti];
21757                opti++;
21758                int user = UserHandle.getUserId(Binder.getCallingUid());
21759                if (opti < args.length) {
21760                    try {
21761                        user = Integer.parseInt(args[opti]);
21762                    } catch (NumberFormatException e) {
21763                        pw.println("Error: check-permission user argument is not a number: "
21764                                + args[opti]);
21765                        return;
21766                    }
21767                }
21768
21769                // Normalize package name to handle renamed packages and static libs
21770                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21771
21772                pw.println(checkPermission(perm, pkg, user));
21773                return;
21774            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21775                dumpState.setDump(DumpState.DUMP_LIBS);
21776            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21777                dumpState.setDump(DumpState.DUMP_FEATURES);
21778            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21779                if (opti >= args.length) {
21780                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21781                            | DumpState.DUMP_SERVICE_RESOLVERS
21782                            | DumpState.DUMP_RECEIVER_RESOLVERS
21783                            | DumpState.DUMP_CONTENT_RESOLVERS);
21784                } else {
21785                    while (opti < args.length) {
21786                        String name = args[opti];
21787                        if ("a".equals(name) || "activity".equals(name)) {
21788                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21789                        } else if ("s".equals(name) || "service".equals(name)) {
21790                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21791                        } else if ("r".equals(name) || "receiver".equals(name)) {
21792                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21793                        } else if ("c".equals(name) || "content".equals(name)) {
21794                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21795                        } else {
21796                            pw.println("Error: unknown resolver table type: " + name);
21797                            return;
21798                        }
21799                        opti++;
21800                    }
21801                }
21802            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21803                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21804            } else if ("permission".equals(cmd)) {
21805                if (opti >= args.length) {
21806                    pw.println("Error: permission requires permission name");
21807                    return;
21808                }
21809                permissionNames = new ArraySet<>();
21810                while (opti < args.length) {
21811                    permissionNames.add(args[opti]);
21812                    opti++;
21813                }
21814                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21815                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21816            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21817                dumpState.setDump(DumpState.DUMP_PREFERRED);
21818            } else if ("preferred-xml".equals(cmd)) {
21819                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21820                if (opti < args.length && "--full".equals(args[opti])) {
21821                    fullPreferred = true;
21822                    opti++;
21823                }
21824            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21825                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21826            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21827                dumpState.setDump(DumpState.DUMP_PACKAGES);
21828            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21829                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21830            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21831                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21832            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21833                dumpState.setDump(DumpState.DUMP_MESSAGES);
21834            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21835                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21836            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21837                    || "intent-filter-verifiers".equals(cmd)) {
21838                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21839            } else if ("version".equals(cmd)) {
21840                dumpState.setDump(DumpState.DUMP_VERSION);
21841            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21842                dumpState.setDump(DumpState.DUMP_KEYSETS);
21843            } else if ("installs".equals(cmd)) {
21844                dumpState.setDump(DumpState.DUMP_INSTALLS);
21845            } else if ("frozen".equals(cmd)) {
21846                dumpState.setDump(DumpState.DUMP_FROZEN);
21847            } else if ("dexopt".equals(cmd)) {
21848                dumpState.setDump(DumpState.DUMP_DEXOPT);
21849            } else if ("compiler-stats".equals(cmd)) {
21850                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21851            } else if ("enabled-overlays".equals(cmd)) {
21852                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
21853            } else if ("changes".equals(cmd)) {
21854                dumpState.setDump(DumpState.DUMP_CHANGES);
21855            } else if ("write".equals(cmd)) {
21856                synchronized (mPackages) {
21857                    mSettings.writeLPr();
21858                    pw.println("Settings written.");
21859                    return;
21860                }
21861            }
21862        }
21863
21864        if (checkin) {
21865            pw.println("vers,1");
21866        }
21867
21868        // reader
21869        synchronized (mPackages) {
21870            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21871                if (!checkin) {
21872                    if (dumpState.onTitlePrinted())
21873                        pw.println();
21874                    pw.println("Database versions:");
21875                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21876                }
21877            }
21878
21879            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21880                if (!checkin) {
21881                    if (dumpState.onTitlePrinted())
21882                        pw.println();
21883                    pw.println("Verifiers:");
21884                    pw.print("  Required: ");
21885                    pw.print(mRequiredVerifierPackage);
21886                    pw.print(" (uid=");
21887                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21888                            UserHandle.USER_SYSTEM));
21889                    pw.println(")");
21890                } else if (mRequiredVerifierPackage != null) {
21891                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21892                    pw.print(",");
21893                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21894                            UserHandle.USER_SYSTEM));
21895                }
21896            }
21897
21898            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21899                    packageName == null) {
21900                if (mIntentFilterVerifierComponent != null) {
21901                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21902                    if (!checkin) {
21903                        if (dumpState.onTitlePrinted())
21904                            pw.println();
21905                        pw.println("Intent Filter Verifier:");
21906                        pw.print("  Using: ");
21907                        pw.print(verifierPackageName);
21908                        pw.print(" (uid=");
21909                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21910                                UserHandle.USER_SYSTEM));
21911                        pw.println(")");
21912                    } else if (verifierPackageName != null) {
21913                        pw.print("ifv,"); pw.print(verifierPackageName);
21914                        pw.print(",");
21915                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21916                                UserHandle.USER_SYSTEM));
21917                    }
21918                } else {
21919                    pw.println();
21920                    pw.println("No Intent Filter Verifier available!");
21921                }
21922            }
21923
21924            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21925                boolean printedHeader = false;
21926                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21927                while (it.hasNext()) {
21928                    String libName = it.next();
21929                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21930                    if (versionedLib == null) {
21931                        continue;
21932                    }
21933                    final int versionCount = versionedLib.size();
21934                    for (int i = 0; i < versionCount; i++) {
21935                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21936                        if (!checkin) {
21937                            if (!printedHeader) {
21938                                if (dumpState.onTitlePrinted())
21939                                    pw.println();
21940                                pw.println("Libraries:");
21941                                printedHeader = true;
21942                            }
21943                            pw.print("  ");
21944                        } else {
21945                            pw.print("lib,");
21946                        }
21947                        pw.print(libEntry.info.getName());
21948                        if (libEntry.info.isStatic()) {
21949                            pw.print(" version=" + libEntry.info.getVersion());
21950                        }
21951                        if (!checkin) {
21952                            pw.print(" -> ");
21953                        }
21954                        if (libEntry.path != null) {
21955                            pw.print(" (jar) ");
21956                            pw.print(libEntry.path);
21957                        } else {
21958                            pw.print(" (apk) ");
21959                            pw.print(libEntry.apk);
21960                        }
21961                        pw.println();
21962                    }
21963                }
21964            }
21965
21966            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21967                if (dumpState.onTitlePrinted())
21968                    pw.println();
21969                if (!checkin) {
21970                    pw.println("Features:");
21971                }
21972
21973                synchronized (mAvailableFeatures) {
21974                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21975                        if (checkin) {
21976                            pw.print("feat,");
21977                            pw.print(feat.name);
21978                            pw.print(",");
21979                            pw.println(feat.version);
21980                        } else {
21981                            pw.print("  ");
21982                            pw.print(feat.name);
21983                            if (feat.version > 0) {
21984                                pw.print(" version=");
21985                                pw.print(feat.version);
21986                            }
21987                            pw.println();
21988                        }
21989                    }
21990                }
21991            }
21992
21993            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21994                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21995                        : "Activity Resolver Table:", "  ", packageName,
21996                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21997                    dumpState.setTitlePrinted(true);
21998                }
21999            }
22000            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22001                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22002                        : "Receiver Resolver Table:", "  ", packageName,
22003                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22004                    dumpState.setTitlePrinted(true);
22005                }
22006            }
22007            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22008                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22009                        : "Service Resolver Table:", "  ", packageName,
22010                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22011                    dumpState.setTitlePrinted(true);
22012                }
22013            }
22014            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22015                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22016                        : "Provider Resolver Table:", "  ", packageName,
22017                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22018                    dumpState.setTitlePrinted(true);
22019                }
22020            }
22021
22022            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22023                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22024                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22025                    int user = mSettings.mPreferredActivities.keyAt(i);
22026                    if (pir.dump(pw,
22027                            dumpState.getTitlePrinted()
22028                                ? "\nPreferred Activities User " + user + ":"
22029                                : "Preferred Activities User " + user + ":", "  ",
22030                            packageName, true, false)) {
22031                        dumpState.setTitlePrinted(true);
22032                    }
22033                }
22034            }
22035
22036            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22037                pw.flush();
22038                FileOutputStream fout = new FileOutputStream(fd);
22039                BufferedOutputStream str = new BufferedOutputStream(fout);
22040                XmlSerializer serializer = new FastXmlSerializer();
22041                try {
22042                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22043                    serializer.startDocument(null, true);
22044                    serializer.setFeature(
22045                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22046                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22047                    serializer.endDocument();
22048                    serializer.flush();
22049                } catch (IllegalArgumentException e) {
22050                    pw.println("Failed writing: " + e);
22051                } catch (IllegalStateException e) {
22052                    pw.println("Failed writing: " + e);
22053                } catch (IOException e) {
22054                    pw.println("Failed writing: " + e);
22055                }
22056            }
22057
22058            if (!checkin
22059                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22060                    && packageName == null) {
22061                pw.println();
22062                int count = mSettings.mPackages.size();
22063                if (count == 0) {
22064                    pw.println("No applications!");
22065                    pw.println();
22066                } else {
22067                    final String prefix = "  ";
22068                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22069                    if (allPackageSettings.size() == 0) {
22070                        pw.println("No domain preferred apps!");
22071                        pw.println();
22072                    } else {
22073                        pw.println("App verification status:");
22074                        pw.println();
22075                        count = 0;
22076                        for (PackageSetting ps : allPackageSettings) {
22077                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22078                            if (ivi == null || ivi.getPackageName() == null) continue;
22079                            pw.println(prefix + "Package: " + ivi.getPackageName());
22080                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22081                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22082                            pw.println();
22083                            count++;
22084                        }
22085                        if (count == 0) {
22086                            pw.println(prefix + "No app verification established.");
22087                            pw.println();
22088                        }
22089                        for (int userId : sUserManager.getUserIds()) {
22090                            pw.println("App linkages for user " + userId + ":");
22091                            pw.println();
22092                            count = 0;
22093                            for (PackageSetting ps : allPackageSettings) {
22094                                final long status = ps.getDomainVerificationStatusForUser(userId);
22095                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22096                                        && !DEBUG_DOMAIN_VERIFICATION) {
22097                                    continue;
22098                                }
22099                                pw.println(prefix + "Package: " + ps.name);
22100                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22101                                String statusStr = IntentFilterVerificationInfo.
22102                                        getStatusStringFromValue(status);
22103                                pw.println(prefix + "Status:  " + statusStr);
22104                                pw.println();
22105                                count++;
22106                            }
22107                            if (count == 0) {
22108                                pw.println(prefix + "No configured app linkages.");
22109                                pw.println();
22110                            }
22111                        }
22112                    }
22113                }
22114            }
22115
22116            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22117                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22118                if (packageName == null && permissionNames == null) {
22119                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22120                        if (iperm == 0) {
22121                            if (dumpState.onTitlePrinted())
22122                                pw.println();
22123                            pw.println("AppOp Permissions:");
22124                        }
22125                        pw.print("  AppOp Permission ");
22126                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22127                        pw.println(":");
22128                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22129                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22130                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22131                        }
22132                    }
22133                }
22134            }
22135
22136            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22137                boolean printedSomething = false;
22138                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22139                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22140                        continue;
22141                    }
22142                    if (!printedSomething) {
22143                        if (dumpState.onTitlePrinted())
22144                            pw.println();
22145                        pw.println("Registered ContentProviders:");
22146                        printedSomething = true;
22147                    }
22148                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22149                    pw.print("    "); pw.println(p.toString());
22150                }
22151                printedSomething = false;
22152                for (Map.Entry<String, PackageParser.Provider> entry :
22153                        mProvidersByAuthority.entrySet()) {
22154                    PackageParser.Provider p = entry.getValue();
22155                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22156                        continue;
22157                    }
22158                    if (!printedSomething) {
22159                        if (dumpState.onTitlePrinted())
22160                            pw.println();
22161                        pw.println("ContentProvider Authorities:");
22162                        printedSomething = true;
22163                    }
22164                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22165                    pw.print("    "); pw.println(p.toString());
22166                    if (p.info != null && p.info.applicationInfo != null) {
22167                        final String appInfo = p.info.applicationInfo.toString();
22168                        pw.print("      applicationInfo="); pw.println(appInfo);
22169                    }
22170                }
22171            }
22172
22173            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22174                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22175            }
22176
22177            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22178                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22179            }
22180
22181            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22182                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22183            }
22184
22185            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22186                if (dumpState.onTitlePrinted()) pw.println();
22187                pw.println("Package Changes:");
22188                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22189                final int K = mChangedPackages.size();
22190                for (int i = 0; i < K; i++) {
22191                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22192                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22193                    final int N = changes.size();
22194                    if (N == 0) {
22195                        pw.print("    "); pw.println("No packages changed");
22196                    } else {
22197                        for (int j = 0; j < N; j++) {
22198                            final String pkgName = changes.valueAt(j);
22199                            final int sequenceNumber = changes.keyAt(j);
22200                            pw.print("    ");
22201                            pw.print("seq=");
22202                            pw.print(sequenceNumber);
22203                            pw.print(", package=");
22204                            pw.println(pkgName);
22205                        }
22206                    }
22207                }
22208            }
22209
22210            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22211                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22212            }
22213
22214            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22215                // XXX should handle packageName != null by dumping only install data that
22216                // the given package is involved with.
22217                if (dumpState.onTitlePrinted()) pw.println();
22218
22219                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22220                ipw.println();
22221                ipw.println("Frozen packages:");
22222                ipw.increaseIndent();
22223                if (mFrozenPackages.size() == 0) {
22224                    ipw.println("(none)");
22225                } else {
22226                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22227                        ipw.println(mFrozenPackages.valueAt(i));
22228                    }
22229                }
22230                ipw.decreaseIndent();
22231            }
22232
22233            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22234                if (dumpState.onTitlePrinted()) pw.println();
22235                dumpDexoptStateLPr(pw, packageName);
22236            }
22237
22238            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22239                if (dumpState.onTitlePrinted()) pw.println();
22240                dumpCompilerStatsLPr(pw, packageName);
22241            }
22242
22243            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22244                if (dumpState.onTitlePrinted()) pw.println();
22245                mSettings.dumpReadMessagesLPr(pw, dumpState);
22246
22247                pw.println();
22248                pw.println("Package warning messages:");
22249                BufferedReader in = null;
22250                String line = null;
22251                try {
22252                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22253                    while ((line = in.readLine()) != null) {
22254                        if (line.contains("ignored: updated version")) continue;
22255                        pw.println(line);
22256                    }
22257                } catch (IOException ignored) {
22258                } finally {
22259                    IoUtils.closeQuietly(in);
22260                }
22261            }
22262
22263            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22264                BufferedReader in = null;
22265                String line = null;
22266                try {
22267                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22268                    while ((line = in.readLine()) != null) {
22269                        if (line.contains("ignored: updated version")) continue;
22270                        pw.print("msg,");
22271                        pw.println(line);
22272                    }
22273                } catch (IOException ignored) {
22274                } finally {
22275                    IoUtils.closeQuietly(in);
22276                }
22277            }
22278        }
22279
22280        // PackageInstaller should be called outside of mPackages lock
22281        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22282            // XXX should handle packageName != null by dumping only install data that
22283            // the given package is involved with.
22284            if (dumpState.onTitlePrinted()) pw.println();
22285            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22286        }
22287    }
22288
22289    private void dumpProto(FileDescriptor fd) {
22290        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22291
22292        synchronized (mPackages) {
22293            final long requiredVerifierPackageToken =
22294                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22295            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22296            proto.write(
22297                    PackageServiceDumpProto.PackageShortProto.UID,
22298                    getPackageUid(
22299                            mRequiredVerifierPackage,
22300                            MATCH_DEBUG_TRIAGED_MISSING,
22301                            UserHandle.USER_SYSTEM));
22302            proto.end(requiredVerifierPackageToken);
22303
22304            if (mIntentFilterVerifierComponent != null) {
22305                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22306                final long verifierPackageToken =
22307                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22308                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22309                proto.write(
22310                        PackageServiceDumpProto.PackageShortProto.UID,
22311                        getPackageUid(
22312                                verifierPackageName,
22313                                MATCH_DEBUG_TRIAGED_MISSING,
22314                                UserHandle.USER_SYSTEM));
22315                proto.end(verifierPackageToken);
22316            }
22317
22318            dumpSharedLibrariesProto(proto);
22319            dumpFeaturesProto(proto);
22320            mSettings.dumpPackagesProto(proto);
22321            mSettings.dumpSharedUsersProto(proto);
22322            dumpMessagesProto(proto);
22323        }
22324        proto.flush();
22325    }
22326
22327    private void dumpMessagesProto(ProtoOutputStream proto) {
22328        BufferedReader in = null;
22329        String line = null;
22330        try {
22331            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22332            while ((line = in.readLine()) != null) {
22333                if (line.contains("ignored: updated version")) continue;
22334                proto.write(PackageServiceDumpProto.MESSAGES, line);
22335            }
22336        } catch (IOException ignored) {
22337        } finally {
22338            IoUtils.closeQuietly(in);
22339        }
22340    }
22341
22342    private void dumpFeaturesProto(ProtoOutputStream proto) {
22343        synchronized (mAvailableFeatures) {
22344            final int count = mAvailableFeatures.size();
22345            for (int i = 0; i < count; i++) {
22346                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22347                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22348                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22349                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22350                proto.end(featureToken);
22351            }
22352        }
22353    }
22354
22355    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22356        final int count = mSharedLibraries.size();
22357        for (int i = 0; i < count; i++) {
22358            final String libName = mSharedLibraries.keyAt(i);
22359            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22360            if (versionedLib == null) {
22361                continue;
22362            }
22363            final int versionCount = versionedLib.size();
22364            for (int j = 0; j < versionCount; j++) {
22365                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22366                final long sharedLibraryToken =
22367                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22368                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22369                final boolean isJar = (libEntry.path != null);
22370                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22371                if (isJar) {
22372                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22373                } else {
22374                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22375                }
22376                proto.end(sharedLibraryToken);
22377            }
22378        }
22379    }
22380
22381    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22382        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22383        ipw.println();
22384        ipw.println("Dexopt state:");
22385        ipw.increaseIndent();
22386        Collection<PackageParser.Package> packages = null;
22387        if (packageName != null) {
22388            PackageParser.Package targetPackage = mPackages.get(packageName);
22389            if (targetPackage != null) {
22390                packages = Collections.singletonList(targetPackage);
22391            } else {
22392                ipw.println("Unable to find package: " + packageName);
22393                return;
22394            }
22395        } else {
22396            packages = mPackages.values();
22397        }
22398
22399        for (PackageParser.Package pkg : packages) {
22400            ipw.println("[" + pkg.packageName + "]");
22401            ipw.increaseIndent();
22402            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22403            ipw.decreaseIndent();
22404        }
22405    }
22406
22407    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22408        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22409        ipw.println();
22410        ipw.println("Compiler stats:");
22411        ipw.increaseIndent();
22412        Collection<PackageParser.Package> packages = null;
22413        if (packageName != null) {
22414            PackageParser.Package targetPackage = mPackages.get(packageName);
22415            if (targetPackage != null) {
22416                packages = Collections.singletonList(targetPackage);
22417            } else {
22418                ipw.println("Unable to find package: " + packageName);
22419                return;
22420            }
22421        } else {
22422            packages = mPackages.values();
22423        }
22424
22425        for (PackageParser.Package pkg : packages) {
22426            ipw.println("[" + pkg.packageName + "]");
22427            ipw.increaseIndent();
22428
22429            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22430            if (stats == null) {
22431                ipw.println("(No recorded stats)");
22432            } else {
22433                stats.dump(ipw);
22434            }
22435            ipw.decreaseIndent();
22436        }
22437    }
22438
22439    private String dumpDomainString(String packageName) {
22440        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22441                .getList();
22442        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22443
22444        ArraySet<String> result = new ArraySet<>();
22445        if (iviList.size() > 0) {
22446            for (IntentFilterVerificationInfo ivi : iviList) {
22447                for (String host : ivi.getDomains()) {
22448                    result.add(host);
22449                }
22450            }
22451        }
22452        if (filters != null && filters.size() > 0) {
22453            for (IntentFilter filter : filters) {
22454                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22455                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22456                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22457                    result.addAll(filter.getHostsList());
22458                }
22459            }
22460        }
22461
22462        StringBuilder sb = new StringBuilder(result.size() * 16);
22463        for (String domain : result) {
22464            if (sb.length() > 0) sb.append(" ");
22465            sb.append(domain);
22466        }
22467        return sb.toString();
22468    }
22469
22470    // ------- apps on sdcard specific code -------
22471    static final boolean DEBUG_SD_INSTALL = false;
22472
22473    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22474
22475    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22476
22477    private boolean mMediaMounted = false;
22478
22479    static String getEncryptKey() {
22480        try {
22481            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22482                    SD_ENCRYPTION_KEYSTORE_NAME);
22483            if (sdEncKey == null) {
22484                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22485                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22486                if (sdEncKey == null) {
22487                    Slog.e(TAG, "Failed to create encryption keys");
22488                    return null;
22489                }
22490            }
22491            return sdEncKey;
22492        } catch (NoSuchAlgorithmException nsae) {
22493            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22494            return null;
22495        } catch (IOException ioe) {
22496            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22497            return null;
22498        }
22499    }
22500
22501    /*
22502     * Update media status on PackageManager.
22503     */
22504    @Override
22505    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22506        enforceSystemOrRoot("Media status can only be updated by the system");
22507        // reader; this apparently protects mMediaMounted, but should probably
22508        // be a different lock in that case.
22509        synchronized (mPackages) {
22510            Log.i(TAG, "Updating external media status from "
22511                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22512                    + (mediaStatus ? "mounted" : "unmounted"));
22513            if (DEBUG_SD_INSTALL)
22514                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22515                        + ", mMediaMounted=" + mMediaMounted);
22516            if (mediaStatus == mMediaMounted) {
22517                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22518                        : 0, -1);
22519                mHandler.sendMessage(msg);
22520                return;
22521            }
22522            mMediaMounted = mediaStatus;
22523        }
22524        // Queue up an async operation since the package installation may take a
22525        // little while.
22526        mHandler.post(new Runnable() {
22527            public void run() {
22528                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22529            }
22530        });
22531    }
22532
22533    /**
22534     * Called by StorageManagerService when the initial ASECs to scan are available.
22535     * Should block until all the ASEC containers are finished being scanned.
22536     */
22537    public void scanAvailableAsecs() {
22538        updateExternalMediaStatusInner(true, false, false);
22539    }
22540
22541    /*
22542     * Collect information of applications on external media, map them against
22543     * existing containers and update information based on current mount status.
22544     * Please note that we always have to report status if reportStatus has been
22545     * set to true especially when unloading packages.
22546     */
22547    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22548            boolean externalStorage) {
22549        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22550        int[] uidArr = EmptyArray.INT;
22551
22552        final String[] list = PackageHelper.getSecureContainerList();
22553        if (ArrayUtils.isEmpty(list)) {
22554            Log.i(TAG, "No secure containers found");
22555        } else {
22556            // Process list of secure containers and categorize them
22557            // as active or stale based on their package internal state.
22558
22559            // reader
22560            synchronized (mPackages) {
22561                for (String cid : list) {
22562                    // Leave stages untouched for now; installer service owns them
22563                    if (PackageInstallerService.isStageName(cid)) continue;
22564
22565                    if (DEBUG_SD_INSTALL)
22566                        Log.i(TAG, "Processing container " + cid);
22567                    String pkgName = getAsecPackageName(cid);
22568                    if (pkgName == null) {
22569                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22570                        continue;
22571                    }
22572                    if (DEBUG_SD_INSTALL)
22573                        Log.i(TAG, "Looking for pkg : " + pkgName);
22574
22575                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22576                    if (ps == null) {
22577                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22578                        continue;
22579                    }
22580
22581                    /*
22582                     * Skip packages that are not external if we're unmounting
22583                     * external storage.
22584                     */
22585                    if (externalStorage && !isMounted && !isExternal(ps)) {
22586                        continue;
22587                    }
22588
22589                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22590                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22591                    // The package status is changed only if the code path
22592                    // matches between settings and the container id.
22593                    if (ps.codePathString != null
22594                            && ps.codePathString.startsWith(args.getCodePath())) {
22595                        if (DEBUG_SD_INSTALL) {
22596                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22597                                    + " at code path: " + ps.codePathString);
22598                        }
22599
22600                        // We do have a valid package installed on sdcard
22601                        processCids.put(args, ps.codePathString);
22602                        final int uid = ps.appId;
22603                        if (uid != -1) {
22604                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22605                        }
22606                    } else {
22607                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22608                                + ps.codePathString);
22609                    }
22610                }
22611            }
22612
22613            Arrays.sort(uidArr);
22614        }
22615
22616        // Process packages with valid entries.
22617        if (isMounted) {
22618            if (DEBUG_SD_INSTALL)
22619                Log.i(TAG, "Loading packages");
22620            loadMediaPackages(processCids, uidArr, externalStorage);
22621            startCleaningPackages();
22622            mInstallerService.onSecureContainersAvailable();
22623        } else {
22624            if (DEBUG_SD_INSTALL)
22625                Log.i(TAG, "Unloading packages");
22626            unloadMediaPackages(processCids, uidArr, reportStatus);
22627        }
22628    }
22629
22630    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22631            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22632        final int size = infos.size();
22633        final String[] packageNames = new String[size];
22634        final int[] packageUids = new int[size];
22635        for (int i = 0; i < size; i++) {
22636            final ApplicationInfo info = infos.get(i);
22637            packageNames[i] = info.packageName;
22638            packageUids[i] = info.uid;
22639        }
22640        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22641                finishedReceiver);
22642    }
22643
22644    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22645            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22646        sendResourcesChangedBroadcast(mediaStatus, replacing,
22647                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22648    }
22649
22650    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22651            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22652        int size = pkgList.length;
22653        if (size > 0) {
22654            // Send broadcasts here
22655            Bundle extras = new Bundle();
22656            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22657            if (uidArr != null) {
22658                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22659            }
22660            if (replacing) {
22661                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22662            }
22663            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22664                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22665            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22666        }
22667    }
22668
22669   /*
22670     * Look at potentially valid container ids from processCids If package
22671     * information doesn't match the one on record or package scanning fails,
22672     * the cid is added to list of removeCids. We currently don't delete stale
22673     * containers.
22674     */
22675    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22676            boolean externalStorage) {
22677        ArrayList<String> pkgList = new ArrayList<String>();
22678        Set<AsecInstallArgs> keys = processCids.keySet();
22679
22680        for (AsecInstallArgs args : keys) {
22681            String codePath = processCids.get(args);
22682            if (DEBUG_SD_INSTALL)
22683                Log.i(TAG, "Loading container : " + args.cid);
22684            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22685            try {
22686                // Make sure there are no container errors first.
22687                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22688                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22689                            + " when installing from sdcard");
22690                    continue;
22691                }
22692                // Check code path here.
22693                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22694                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22695                            + " does not match one in settings " + codePath);
22696                    continue;
22697                }
22698                // Parse package
22699                int parseFlags = mDefParseFlags;
22700                if (args.isExternalAsec()) {
22701                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22702                }
22703                if (args.isFwdLocked()) {
22704                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22705                }
22706
22707                synchronized (mInstallLock) {
22708                    PackageParser.Package pkg = null;
22709                    try {
22710                        // Sadly we don't know the package name yet to freeze it
22711                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22712                                SCAN_IGNORE_FROZEN, 0, null);
22713                    } catch (PackageManagerException e) {
22714                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22715                    }
22716                    // Scan the package
22717                    if (pkg != null) {
22718                        /*
22719                         * TODO why is the lock being held? doPostInstall is
22720                         * called in other places without the lock. This needs
22721                         * to be straightened out.
22722                         */
22723                        // writer
22724                        synchronized (mPackages) {
22725                            retCode = PackageManager.INSTALL_SUCCEEDED;
22726                            pkgList.add(pkg.packageName);
22727                            // Post process args
22728                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22729                                    pkg.applicationInfo.uid);
22730                        }
22731                    } else {
22732                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22733                    }
22734                }
22735
22736            } finally {
22737                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22738                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22739                }
22740            }
22741        }
22742        // writer
22743        synchronized (mPackages) {
22744            // If the platform SDK has changed since the last time we booted,
22745            // we need to re-grant app permission to catch any new ones that
22746            // appear. This is really a hack, and means that apps can in some
22747            // cases get permissions that the user didn't initially explicitly
22748            // allow... it would be nice to have some better way to handle
22749            // this situation.
22750            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22751                    : mSettings.getInternalVersion();
22752            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22753                    : StorageManager.UUID_PRIVATE_INTERNAL;
22754
22755            int updateFlags = UPDATE_PERMISSIONS_ALL;
22756            if (ver.sdkVersion != mSdkVersion) {
22757                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22758                        + mSdkVersion + "; regranting permissions for external");
22759                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22760            }
22761            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22762
22763            // Yay, everything is now upgraded
22764            ver.forceCurrent();
22765
22766            // can downgrade to reader
22767            // Persist settings
22768            mSettings.writeLPr();
22769        }
22770        // Send a broadcast to let everyone know we are done processing
22771        if (pkgList.size() > 0) {
22772            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22773        }
22774    }
22775
22776   /*
22777     * Utility method to unload a list of specified containers
22778     */
22779    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22780        // Just unmount all valid containers.
22781        for (AsecInstallArgs arg : cidArgs) {
22782            synchronized (mInstallLock) {
22783                arg.doPostDeleteLI(false);
22784           }
22785       }
22786   }
22787
22788    /*
22789     * Unload packages mounted on external media. This involves deleting package
22790     * data from internal structures, sending broadcasts about disabled packages,
22791     * gc'ing to free up references, unmounting all secure containers
22792     * corresponding to packages on external media, and posting a
22793     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22794     * that we always have to post this message if status has been requested no
22795     * matter what.
22796     */
22797    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22798            final boolean reportStatus) {
22799        if (DEBUG_SD_INSTALL)
22800            Log.i(TAG, "unloading media packages");
22801        ArrayList<String> pkgList = new ArrayList<String>();
22802        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22803        final Set<AsecInstallArgs> keys = processCids.keySet();
22804        for (AsecInstallArgs args : keys) {
22805            String pkgName = args.getPackageName();
22806            if (DEBUG_SD_INSTALL)
22807                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22808            // Delete package internally
22809            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22810            synchronized (mInstallLock) {
22811                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22812                final boolean res;
22813                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22814                        "unloadMediaPackages")) {
22815                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22816                            null);
22817                }
22818                if (res) {
22819                    pkgList.add(pkgName);
22820                } else {
22821                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22822                    failedList.add(args);
22823                }
22824            }
22825        }
22826
22827        // reader
22828        synchronized (mPackages) {
22829            // We didn't update the settings after removing each package;
22830            // write them now for all packages.
22831            mSettings.writeLPr();
22832        }
22833
22834        // We have to absolutely send UPDATED_MEDIA_STATUS only
22835        // after confirming that all the receivers processed the ordered
22836        // broadcast when packages get disabled, force a gc to clean things up.
22837        // and unload all the containers.
22838        if (pkgList.size() > 0) {
22839            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22840                    new IIntentReceiver.Stub() {
22841                public void performReceive(Intent intent, int resultCode, String data,
22842                        Bundle extras, boolean ordered, boolean sticky,
22843                        int sendingUser) throws RemoteException {
22844                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22845                            reportStatus ? 1 : 0, 1, keys);
22846                    mHandler.sendMessage(msg);
22847                }
22848            });
22849        } else {
22850            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22851                    keys);
22852            mHandler.sendMessage(msg);
22853        }
22854    }
22855
22856    private void loadPrivatePackages(final VolumeInfo vol) {
22857        mHandler.post(new Runnable() {
22858            @Override
22859            public void run() {
22860                loadPrivatePackagesInner(vol);
22861            }
22862        });
22863    }
22864
22865    private void loadPrivatePackagesInner(VolumeInfo vol) {
22866        final String volumeUuid = vol.fsUuid;
22867        if (TextUtils.isEmpty(volumeUuid)) {
22868            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22869            return;
22870        }
22871
22872        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22873        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22874        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22875
22876        final VersionInfo ver;
22877        final List<PackageSetting> packages;
22878        synchronized (mPackages) {
22879            ver = mSettings.findOrCreateVersion(volumeUuid);
22880            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22881        }
22882
22883        for (PackageSetting ps : packages) {
22884            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22885            synchronized (mInstallLock) {
22886                final PackageParser.Package pkg;
22887                try {
22888                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22889                    loaded.add(pkg.applicationInfo);
22890
22891                } catch (PackageManagerException e) {
22892                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22893                }
22894
22895                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22896                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22897                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22898                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22899                }
22900            }
22901        }
22902
22903        // Reconcile app data for all started/unlocked users
22904        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22905        final UserManager um = mContext.getSystemService(UserManager.class);
22906        UserManagerInternal umInternal = getUserManagerInternal();
22907        for (UserInfo user : um.getUsers()) {
22908            final int flags;
22909            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22910                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22911            } else if (umInternal.isUserRunning(user.id)) {
22912                flags = StorageManager.FLAG_STORAGE_DE;
22913            } else {
22914                continue;
22915            }
22916
22917            try {
22918                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22919                synchronized (mInstallLock) {
22920                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22921                }
22922            } catch (IllegalStateException e) {
22923                // Device was probably ejected, and we'll process that event momentarily
22924                Slog.w(TAG, "Failed to prepare storage: " + e);
22925            }
22926        }
22927
22928        synchronized (mPackages) {
22929            int updateFlags = UPDATE_PERMISSIONS_ALL;
22930            if (ver.sdkVersion != mSdkVersion) {
22931                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22932                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22933                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22934            }
22935            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22936
22937            // Yay, everything is now upgraded
22938            ver.forceCurrent();
22939
22940            mSettings.writeLPr();
22941        }
22942
22943        for (PackageFreezer freezer : freezers) {
22944            freezer.close();
22945        }
22946
22947        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22948        sendResourcesChangedBroadcast(true, false, loaded, null);
22949    }
22950
22951    private void unloadPrivatePackages(final VolumeInfo vol) {
22952        mHandler.post(new Runnable() {
22953            @Override
22954            public void run() {
22955                unloadPrivatePackagesInner(vol);
22956            }
22957        });
22958    }
22959
22960    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22961        final String volumeUuid = vol.fsUuid;
22962        if (TextUtils.isEmpty(volumeUuid)) {
22963            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22964            return;
22965        }
22966
22967        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22968        synchronized (mInstallLock) {
22969        synchronized (mPackages) {
22970            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22971            for (PackageSetting ps : packages) {
22972                if (ps.pkg == null) continue;
22973
22974                final ApplicationInfo info = ps.pkg.applicationInfo;
22975                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22976                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22977
22978                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22979                        "unloadPrivatePackagesInner")) {
22980                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22981                            false, null)) {
22982                        unloaded.add(info);
22983                    } else {
22984                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22985                    }
22986                }
22987
22988                // Try very hard to release any references to this package
22989                // so we don't risk the system server being killed due to
22990                // open FDs
22991                AttributeCache.instance().removePackage(ps.name);
22992            }
22993
22994            mSettings.writeLPr();
22995        }
22996        }
22997
22998        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22999        sendResourcesChangedBroadcast(false, false, unloaded, null);
23000
23001        // Try very hard to release any references to this path so we don't risk
23002        // the system server being killed due to open FDs
23003        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23004
23005        for (int i = 0; i < 3; i++) {
23006            System.gc();
23007            System.runFinalization();
23008        }
23009    }
23010
23011    private void assertPackageKnown(String volumeUuid, String packageName)
23012            throws PackageManagerException {
23013        synchronized (mPackages) {
23014            // Normalize package name to handle renamed packages
23015            packageName = normalizePackageNameLPr(packageName);
23016
23017            final PackageSetting ps = mSettings.mPackages.get(packageName);
23018            if (ps == null) {
23019                throw new PackageManagerException("Package " + packageName + " is unknown");
23020            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23021                throw new PackageManagerException(
23022                        "Package " + packageName + " found on unknown volume " + volumeUuid
23023                                + "; expected volume " + ps.volumeUuid);
23024            }
23025        }
23026    }
23027
23028    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23029            throws PackageManagerException {
23030        synchronized (mPackages) {
23031            // Normalize package name to handle renamed packages
23032            packageName = normalizePackageNameLPr(packageName);
23033
23034            final PackageSetting ps = mSettings.mPackages.get(packageName);
23035            if (ps == null) {
23036                throw new PackageManagerException("Package " + packageName + " is unknown");
23037            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23038                throw new PackageManagerException(
23039                        "Package " + packageName + " found on unknown volume " + volumeUuid
23040                                + "; expected volume " + ps.volumeUuid);
23041            } else if (!ps.getInstalled(userId)) {
23042                throw new PackageManagerException(
23043                        "Package " + packageName + " not installed for user " + userId);
23044            }
23045        }
23046    }
23047
23048    private List<String> collectAbsoluteCodePaths() {
23049        synchronized (mPackages) {
23050            List<String> codePaths = new ArrayList<>();
23051            final int packageCount = mSettings.mPackages.size();
23052            for (int i = 0; i < packageCount; i++) {
23053                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23054                codePaths.add(ps.codePath.getAbsolutePath());
23055            }
23056            return codePaths;
23057        }
23058    }
23059
23060    /**
23061     * Examine all apps present on given mounted volume, and destroy apps that
23062     * aren't expected, either due to uninstallation or reinstallation on
23063     * another volume.
23064     */
23065    private void reconcileApps(String volumeUuid) {
23066        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23067        List<File> filesToDelete = null;
23068
23069        final File[] files = FileUtils.listFilesOrEmpty(
23070                Environment.getDataAppDirectory(volumeUuid));
23071        for (File file : files) {
23072            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23073                    && !PackageInstallerService.isStageName(file.getName());
23074            if (!isPackage) {
23075                // Ignore entries which are not packages
23076                continue;
23077            }
23078
23079            String absolutePath = file.getAbsolutePath();
23080
23081            boolean pathValid = false;
23082            final int absoluteCodePathCount = absoluteCodePaths.size();
23083            for (int i = 0; i < absoluteCodePathCount; i++) {
23084                String absoluteCodePath = absoluteCodePaths.get(i);
23085                if (absolutePath.startsWith(absoluteCodePath)) {
23086                    pathValid = true;
23087                    break;
23088                }
23089            }
23090
23091            if (!pathValid) {
23092                if (filesToDelete == null) {
23093                    filesToDelete = new ArrayList<>();
23094                }
23095                filesToDelete.add(file);
23096            }
23097        }
23098
23099        if (filesToDelete != null) {
23100            final int fileToDeleteCount = filesToDelete.size();
23101            for (int i = 0; i < fileToDeleteCount; i++) {
23102                File fileToDelete = filesToDelete.get(i);
23103                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23104                synchronized (mInstallLock) {
23105                    removeCodePathLI(fileToDelete);
23106                }
23107            }
23108        }
23109    }
23110
23111    /**
23112     * Reconcile all app data for the given user.
23113     * <p>
23114     * Verifies that directories exist and that ownership and labeling is
23115     * correct for all installed apps on all mounted volumes.
23116     */
23117    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23118        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23119        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23120            final String volumeUuid = vol.getFsUuid();
23121            synchronized (mInstallLock) {
23122                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23123            }
23124        }
23125    }
23126
23127    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23128            boolean migrateAppData) {
23129        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23130    }
23131
23132    /**
23133     * Reconcile all app data on given mounted volume.
23134     * <p>
23135     * Destroys app data that isn't expected, either due to uninstallation or
23136     * reinstallation on another volume.
23137     * <p>
23138     * Verifies that directories exist and that ownership and labeling is
23139     * correct for all installed apps.
23140     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23141     */
23142    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23143            boolean migrateAppData, boolean onlyCoreApps) {
23144        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23145                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23146        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23147
23148        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23149        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23150
23151        // First look for stale data that doesn't belong, and check if things
23152        // have changed since we did our last restorecon
23153        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23154            if (StorageManager.isFileEncryptedNativeOrEmulated()
23155                    && !StorageManager.isUserKeyUnlocked(userId)) {
23156                throw new RuntimeException(
23157                        "Yikes, someone asked us to reconcile CE storage while " + userId
23158                                + " was still locked; this would have caused massive data loss!");
23159            }
23160
23161            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23162            for (File file : files) {
23163                final String packageName = file.getName();
23164                try {
23165                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23166                } catch (PackageManagerException e) {
23167                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23168                    try {
23169                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23170                                StorageManager.FLAG_STORAGE_CE, 0);
23171                    } catch (InstallerException e2) {
23172                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23173                    }
23174                }
23175            }
23176        }
23177        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23178            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23179            for (File file : files) {
23180                final String packageName = file.getName();
23181                try {
23182                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23183                } catch (PackageManagerException e) {
23184                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23185                    try {
23186                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23187                                StorageManager.FLAG_STORAGE_DE, 0);
23188                    } catch (InstallerException e2) {
23189                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23190                    }
23191                }
23192            }
23193        }
23194
23195        // Ensure that data directories are ready to roll for all packages
23196        // installed for this volume and user
23197        final List<PackageSetting> packages;
23198        synchronized (mPackages) {
23199            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23200        }
23201        int preparedCount = 0;
23202        for (PackageSetting ps : packages) {
23203            final String packageName = ps.name;
23204            if (ps.pkg == null) {
23205                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23206                // TODO: might be due to legacy ASEC apps; we should circle back
23207                // and reconcile again once they're scanned
23208                continue;
23209            }
23210            // Skip non-core apps if requested
23211            if (onlyCoreApps && !ps.pkg.coreApp) {
23212                result.add(packageName);
23213                continue;
23214            }
23215
23216            if (ps.getInstalled(userId)) {
23217                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23218                preparedCount++;
23219            }
23220        }
23221
23222        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23223        return result;
23224    }
23225
23226    /**
23227     * Prepare app data for the given app just after it was installed or
23228     * upgraded. This method carefully only touches users that it's installed
23229     * for, and it forces a restorecon to handle any seinfo changes.
23230     * <p>
23231     * Verifies that directories exist and that ownership and labeling is
23232     * correct for all installed apps. If there is an ownership mismatch, it
23233     * will try recovering system apps by wiping data; third-party app data is
23234     * left intact.
23235     * <p>
23236     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23237     */
23238    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23239        final PackageSetting ps;
23240        synchronized (mPackages) {
23241            ps = mSettings.mPackages.get(pkg.packageName);
23242            mSettings.writeKernelMappingLPr(ps);
23243        }
23244
23245        final UserManager um = mContext.getSystemService(UserManager.class);
23246        UserManagerInternal umInternal = getUserManagerInternal();
23247        for (UserInfo user : um.getUsers()) {
23248            final int flags;
23249            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23250                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23251            } else if (umInternal.isUserRunning(user.id)) {
23252                flags = StorageManager.FLAG_STORAGE_DE;
23253            } else {
23254                continue;
23255            }
23256
23257            if (ps.getInstalled(user.id)) {
23258                // TODO: when user data is locked, mark that we're still dirty
23259                prepareAppDataLIF(pkg, user.id, flags);
23260            }
23261        }
23262    }
23263
23264    /**
23265     * Prepare app data for the given app.
23266     * <p>
23267     * Verifies that directories exist and that ownership and labeling is
23268     * correct for all installed apps. If there is an ownership mismatch, this
23269     * will try recovering system apps by wiping data; third-party app data is
23270     * left intact.
23271     */
23272    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23273        if (pkg == null) {
23274            Slog.wtf(TAG, "Package was null!", new Throwable());
23275            return;
23276        }
23277        prepareAppDataLeafLIF(pkg, userId, flags);
23278        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23279        for (int i = 0; i < childCount; i++) {
23280            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23281        }
23282    }
23283
23284    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23285            boolean maybeMigrateAppData) {
23286        prepareAppDataLIF(pkg, userId, flags);
23287
23288        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23289            // We may have just shuffled around app data directories, so
23290            // prepare them one more time
23291            prepareAppDataLIF(pkg, userId, flags);
23292        }
23293    }
23294
23295    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23296        if (DEBUG_APP_DATA) {
23297            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23298                    + Integer.toHexString(flags));
23299        }
23300
23301        final String volumeUuid = pkg.volumeUuid;
23302        final String packageName = pkg.packageName;
23303        final ApplicationInfo app = pkg.applicationInfo;
23304        final int appId = UserHandle.getAppId(app.uid);
23305
23306        Preconditions.checkNotNull(app.seInfo);
23307
23308        long ceDataInode = -1;
23309        try {
23310            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23311                    appId, app.seInfo, app.targetSdkVersion);
23312        } catch (InstallerException e) {
23313            if (app.isSystemApp()) {
23314                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23315                        + ", but trying to recover: " + e);
23316                destroyAppDataLeafLIF(pkg, userId, flags);
23317                try {
23318                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23319                            appId, app.seInfo, app.targetSdkVersion);
23320                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23321                } catch (InstallerException e2) {
23322                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23323                }
23324            } else {
23325                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23326            }
23327        }
23328
23329        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23330            // TODO: mark this structure as dirty so we persist it!
23331            synchronized (mPackages) {
23332                final PackageSetting ps = mSettings.mPackages.get(packageName);
23333                if (ps != null) {
23334                    ps.setCeDataInode(ceDataInode, userId);
23335                }
23336            }
23337        }
23338
23339        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23340    }
23341
23342    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23343        if (pkg == null) {
23344            Slog.wtf(TAG, "Package was null!", new Throwable());
23345            return;
23346        }
23347        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23348        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23349        for (int i = 0; i < childCount; i++) {
23350            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23351        }
23352    }
23353
23354    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23355        final String volumeUuid = pkg.volumeUuid;
23356        final String packageName = pkg.packageName;
23357        final ApplicationInfo app = pkg.applicationInfo;
23358
23359        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23360            // Create a native library symlink only if we have native libraries
23361            // and if the native libraries are 32 bit libraries. We do not provide
23362            // this symlink for 64 bit libraries.
23363            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23364                final String nativeLibPath = app.nativeLibraryDir;
23365                try {
23366                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23367                            nativeLibPath, userId);
23368                } catch (InstallerException e) {
23369                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23370                }
23371            }
23372        }
23373    }
23374
23375    /**
23376     * For system apps on non-FBE devices, this method migrates any existing
23377     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23378     * requested by the app.
23379     */
23380    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23381        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23382                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23383            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23384                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23385            try {
23386                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23387                        storageTarget);
23388            } catch (InstallerException e) {
23389                logCriticalInfo(Log.WARN,
23390                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23391            }
23392            return true;
23393        } else {
23394            return false;
23395        }
23396    }
23397
23398    public PackageFreezer freezePackage(String packageName, String killReason) {
23399        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23400    }
23401
23402    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23403        return new PackageFreezer(packageName, userId, killReason);
23404    }
23405
23406    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23407            String killReason) {
23408        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23409    }
23410
23411    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23412            String killReason) {
23413        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23414            return new PackageFreezer();
23415        } else {
23416            return freezePackage(packageName, userId, killReason);
23417        }
23418    }
23419
23420    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23421            String killReason) {
23422        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23423    }
23424
23425    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23426            String killReason) {
23427        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23428            return new PackageFreezer();
23429        } else {
23430            return freezePackage(packageName, userId, killReason);
23431        }
23432    }
23433
23434    /**
23435     * Class that freezes and kills the given package upon creation, and
23436     * unfreezes it upon closing. This is typically used when doing surgery on
23437     * app code/data to prevent the app from running while you're working.
23438     */
23439    private class PackageFreezer implements AutoCloseable {
23440        private final String mPackageName;
23441        private final PackageFreezer[] mChildren;
23442
23443        private final boolean mWeFroze;
23444
23445        private final AtomicBoolean mClosed = new AtomicBoolean();
23446        private final CloseGuard mCloseGuard = CloseGuard.get();
23447
23448        /**
23449         * Create and return a stub freezer that doesn't actually do anything,
23450         * typically used when someone requested
23451         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23452         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23453         */
23454        public PackageFreezer() {
23455            mPackageName = null;
23456            mChildren = null;
23457            mWeFroze = false;
23458            mCloseGuard.open("close");
23459        }
23460
23461        public PackageFreezer(String packageName, int userId, String killReason) {
23462            synchronized (mPackages) {
23463                mPackageName = packageName;
23464                mWeFroze = mFrozenPackages.add(mPackageName);
23465
23466                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23467                if (ps != null) {
23468                    killApplication(ps.name, ps.appId, userId, killReason);
23469                }
23470
23471                final PackageParser.Package p = mPackages.get(packageName);
23472                if (p != null && p.childPackages != null) {
23473                    final int N = p.childPackages.size();
23474                    mChildren = new PackageFreezer[N];
23475                    for (int i = 0; i < N; i++) {
23476                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23477                                userId, killReason);
23478                    }
23479                } else {
23480                    mChildren = null;
23481                }
23482            }
23483            mCloseGuard.open("close");
23484        }
23485
23486        @Override
23487        protected void finalize() throws Throwable {
23488            try {
23489                mCloseGuard.warnIfOpen();
23490                close();
23491            } finally {
23492                super.finalize();
23493            }
23494        }
23495
23496        @Override
23497        public void close() {
23498            mCloseGuard.close();
23499            if (mClosed.compareAndSet(false, true)) {
23500                synchronized (mPackages) {
23501                    if (mWeFroze) {
23502                        mFrozenPackages.remove(mPackageName);
23503                    }
23504
23505                    if (mChildren != null) {
23506                        for (PackageFreezer freezer : mChildren) {
23507                            freezer.close();
23508                        }
23509                    }
23510                }
23511            }
23512        }
23513    }
23514
23515    /**
23516     * Verify that given package is currently frozen.
23517     */
23518    private void checkPackageFrozen(String packageName) {
23519        synchronized (mPackages) {
23520            if (!mFrozenPackages.contains(packageName)) {
23521                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23522            }
23523        }
23524    }
23525
23526    @Override
23527    public int movePackage(final String packageName, final String volumeUuid) {
23528        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23529
23530        final int callingUid = Binder.getCallingUid();
23531        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23532        final int moveId = mNextMoveId.getAndIncrement();
23533        mHandler.post(new Runnable() {
23534            @Override
23535            public void run() {
23536                try {
23537                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23538                } catch (PackageManagerException e) {
23539                    Slog.w(TAG, "Failed to move " + packageName, e);
23540                    mMoveCallbacks.notifyStatusChanged(moveId,
23541                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23542                }
23543            }
23544        });
23545        return moveId;
23546    }
23547
23548    private void movePackageInternal(final String packageName, final String volumeUuid,
23549            final int moveId, final int callingUid, UserHandle user)
23550                    throws PackageManagerException {
23551        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23552        final PackageManager pm = mContext.getPackageManager();
23553
23554        final boolean currentAsec;
23555        final String currentVolumeUuid;
23556        final File codeFile;
23557        final String installerPackageName;
23558        final String packageAbiOverride;
23559        final int appId;
23560        final String seinfo;
23561        final String label;
23562        final int targetSdkVersion;
23563        final PackageFreezer freezer;
23564        final int[] installedUserIds;
23565
23566        // reader
23567        synchronized (mPackages) {
23568            final PackageParser.Package pkg = mPackages.get(packageName);
23569            final PackageSetting ps = mSettings.mPackages.get(packageName);
23570            if (pkg == null
23571                    || ps == null
23572                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23573                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23574            }
23575            if (pkg.applicationInfo.isSystemApp()) {
23576                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23577                        "Cannot move system application");
23578            }
23579
23580            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23581            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23582                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23583            if (isInternalStorage && !allow3rdPartyOnInternal) {
23584                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23585                        "3rd party apps are not allowed on internal storage");
23586            }
23587
23588            if (pkg.applicationInfo.isExternalAsec()) {
23589                currentAsec = true;
23590                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23591            } else if (pkg.applicationInfo.isForwardLocked()) {
23592                currentAsec = true;
23593                currentVolumeUuid = "forward_locked";
23594            } else {
23595                currentAsec = false;
23596                currentVolumeUuid = ps.volumeUuid;
23597
23598                final File probe = new File(pkg.codePath);
23599                final File probeOat = new File(probe, "oat");
23600                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23601                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23602                            "Move only supported for modern cluster style installs");
23603                }
23604            }
23605
23606            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23607                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23608                        "Package already moved to " + volumeUuid);
23609            }
23610            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23611                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23612                        "Device admin cannot be moved");
23613            }
23614
23615            if (mFrozenPackages.contains(packageName)) {
23616                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23617                        "Failed to move already frozen package");
23618            }
23619
23620            codeFile = new File(pkg.codePath);
23621            installerPackageName = ps.installerPackageName;
23622            packageAbiOverride = ps.cpuAbiOverrideString;
23623            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23624            seinfo = pkg.applicationInfo.seInfo;
23625            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23626            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23627            freezer = freezePackage(packageName, "movePackageInternal");
23628            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23629        }
23630
23631        final Bundle extras = new Bundle();
23632        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23633        extras.putString(Intent.EXTRA_TITLE, label);
23634        mMoveCallbacks.notifyCreated(moveId, extras);
23635
23636        int installFlags;
23637        final boolean moveCompleteApp;
23638        final File measurePath;
23639
23640        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23641            installFlags = INSTALL_INTERNAL;
23642            moveCompleteApp = !currentAsec;
23643            measurePath = Environment.getDataAppDirectory(volumeUuid);
23644        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23645            installFlags = INSTALL_EXTERNAL;
23646            moveCompleteApp = false;
23647            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23648        } else {
23649            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23650            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23651                    || !volume.isMountedWritable()) {
23652                freezer.close();
23653                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23654                        "Move location not mounted private volume");
23655            }
23656
23657            Preconditions.checkState(!currentAsec);
23658
23659            installFlags = INSTALL_INTERNAL;
23660            moveCompleteApp = true;
23661            measurePath = Environment.getDataAppDirectory(volumeUuid);
23662        }
23663
23664        final PackageStats stats = new PackageStats(null, -1);
23665        synchronized (mInstaller) {
23666            for (int userId : installedUserIds) {
23667                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23668                    freezer.close();
23669                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23670                            "Failed to measure package size");
23671                }
23672            }
23673        }
23674
23675        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23676                + stats.dataSize);
23677
23678        final long startFreeBytes = measurePath.getUsableSpace();
23679        final long sizeBytes;
23680        if (moveCompleteApp) {
23681            sizeBytes = stats.codeSize + stats.dataSize;
23682        } else {
23683            sizeBytes = stats.codeSize;
23684        }
23685
23686        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23687            freezer.close();
23688            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23689                    "Not enough free space to move");
23690        }
23691
23692        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23693
23694        final CountDownLatch installedLatch = new CountDownLatch(1);
23695        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23696            @Override
23697            public void onUserActionRequired(Intent intent) throws RemoteException {
23698                throw new IllegalStateException();
23699            }
23700
23701            @Override
23702            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23703                    Bundle extras) throws RemoteException {
23704                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23705                        + PackageManager.installStatusToString(returnCode, msg));
23706
23707                installedLatch.countDown();
23708                freezer.close();
23709
23710                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23711                switch (status) {
23712                    case PackageInstaller.STATUS_SUCCESS:
23713                        mMoveCallbacks.notifyStatusChanged(moveId,
23714                                PackageManager.MOVE_SUCCEEDED);
23715                        break;
23716                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23717                        mMoveCallbacks.notifyStatusChanged(moveId,
23718                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23719                        break;
23720                    default:
23721                        mMoveCallbacks.notifyStatusChanged(moveId,
23722                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23723                        break;
23724                }
23725            }
23726        };
23727
23728        final MoveInfo move;
23729        if (moveCompleteApp) {
23730            // Kick off a thread to report progress estimates
23731            new Thread() {
23732                @Override
23733                public void run() {
23734                    while (true) {
23735                        try {
23736                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23737                                break;
23738                            }
23739                        } catch (InterruptedException ignored) {
23740                        }
23741
23742                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23743                        final int progress = 10 + (int) MathUtils.constrain(
23744                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23745                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23746                    }
23747                }
23748            }.start();
23749
23750            final String dataAppName = codeFile.getName();
23751            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23752                    dataAppName, appId, seinfo, targetSdkVersion);
23753        } else {
23754            move = null;
23755        }
23756
23757        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23758
23759        final Message msg = mHandler.obtainMessage(INIT_COPY);
23760        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23761        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23762                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23763                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23764                PackageManager.INSTALL_REASON_UNKNOWN);
23765        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23766        msg.obj = params;
23767
23768        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23769                System.identityHashCode(msg.obj));
23770        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23771                System.identityHashCode(msg.obj));
23772
23773        mHandler.sendMessage(msg);
23774    }
23775
23776    @Override
23777    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23778        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23779
23780        final int realMoveId = mNextMoveId.getAndIncrement();
23781        final Bundle extras = new Bundle();
23782        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23783        mMoveCallbacks.notifyCreated(realMoveId, extras);
23784
23785        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23786            @Override
23787            public void onCreated(int moveId, Bundle extras) {
23788                // Ignored
23789            }
23790
23791            @Override
23792            public void onStatusChanged(int moveId, int status, long estMillis) {
23793                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23794            }
23795        };
23796
23797        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23798        storage.setPrimaryStorageUuid(volumeUuid, callback);
23799        return realMoveId;
23800    }
23801
23802    @Override
23803    public int getMoveStatus(int moveId) {
23804        mContext.enforceCallingOrSelfPermission(
23805                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23806        return mMoveCallbacks.mLastStatus.get(moveId);
23807    }
23808
23809    @Override
23810    public void registerMoveCallback(IPackageMoveObserver callback) {
23811        mContext.enforceCallingOrSelfPermission(
23812                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23813        mMoveCallbacks.register(callback);
23814    }
23815
23816    @Override
23817    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23818        mContext.enforceCallingOrSelfPermission(
23819                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23820        mMoveCallbacks.unregister(callback);
23821    }
23822
23823    @Override
23824    public boolean setInstallLocation(int loc) {
23825        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23826                null);
23827        if (getInstallLocation() == loc) {
23828            return true;
23829        }
23830        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23831                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23832            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23833                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23834            return true;
23835        }
23836        return false;
23837   }
23838
23839    @Override
23840    public int getInstallLocation() {
23841        // allow instant app access
23842        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23843                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23844                PackageHelper.APP_INSTALL_AUTO);
23845    }
23846
23847    /** Called by UserManagerService */
23848    void cleanUpUser(UserManagerService userManager, int userHandle) {
23849        synchronized (mPackages) {
23850            mDirtyUsers.remove(userHandle);
23851            mUserNeedsBadging.delete(userHandle);
23852            mSettings.removeUserLPw(userHandle);
23853            mPendingBroadcasts.remove(userHandle);
23854            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23855            removeUnusedPackagesLPw(userManager, userHandle);
23856        }
23857    }
23858
23859    /**
23860     * We're removing userHandle and would like to remove any downloaded packages
23861     * that are no longer in use by any other user.
23862     * @param userHandle the user being removed
23863     */
23864    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23865        final boolean DEBUG_CLEAN_APKS = false;
23866        int [] users = userManager.getUserIds();
23867        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23868        while (psit.hasNext()) {
23869            PackageSetting ps = psit.next();
23870            if (ps.pkg == null) {
23871                continue;
23872            }
23873            final String packageName = ps.pkg.packageName;
23874            // Skip over if system app
23875            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23876                continue;
23877            }
23878            if (DEBUG_CLEAN_APKS) {
23879                Slog.i(TAG, "Checking package " + packageName);
23880            }
23881            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23882            if (keep) {
23883                if (DEBUG_CLEAN_APKS) {
23884                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23885                }
23886            } else {
23887                for (int i = 0; i < users.length; i++) {
23888                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23889                        keep = true;
23890                        if (DEBUG_CLEAN_APKS) {
23891                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23892                                    + users[i]);
23893                        }
23894                        break;
23895                    }
23896                }
23897            }
23898            if (!keep) {
23899                if (DEBUG_CLEAN_APKS) {
23900                    Slog.i(TAG, "  Removing package " + packageName);
23901                }
23902                mHandler.post(new Runnable() {
23903                    public void run() {
23904                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23905                                userHandle, 0);
23906                    } //end run
23907                });
23908            }
23909        }
23910    }
23911
23912    /** Called by UserManagerService */
23913    void createNewUser(int userId, String[] disallowedPackages) {
23914        synchronized (mInstallLock) {
23915            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23916        }
23917        synchronized (mPackages) {
23918            scheduleWritePackageRestrictionsLocked(userId);
23919            scheduleWritePackageListLocked(userId);
23920            applyFactoryDefaultBrowserLPw(userId);
23921            primeDomainVerificationsLPw(userId);
23922        }
23923    }
23924
23925    void onNewUserCreated(final int userId) {
23926        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23927        // If permission review for legacy apps is required, we represent
23928        // dagerous permissions for such apps as always granted runtime
23929        // permissions to keep per user flag state whether review is needed.
23930        // Hence, if a new user is added we have to propagate dangerous
23931        // permission grants for these legacy apps.
23932        if (mPermissionReviewRequired) {
23933            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23934                    | UPDATE_PERMISSIONS_REPLACE_ALL);
23935        }
23936    }
23937
23938    @Override
23939    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23940        mContext.enforceCallingOrSelfPermission(
23941                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23942                "Only package verification agents can read the verifier device identity");
23943
23944        synchronized (mPackages) {
23945            return mSettings.getVerifierDeviceIdentityLPw();
23946        }
23947    }
23948
23949    @Override
23950    public void setPermissionEnforced(String permission, boolean enforced) {
23951        // TODO: Now that we no longer change GID for storage, this should to away.
23952        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23953                "setPermissionEnforced");
23954        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23955            synchronized (mPackages) {
23956                if (mSettings.mReadExternalStorageEnforced == null
23957                        || mSettings.mReadExternalStorageEnforced != enforced) {
23958                    mSettings.mReadExternalStorageEnforced = enforced;
23959                    mSettings.writeLPr();
23960                }
23961            }
23962            // kill any non-foreground processes so we restart them and
23963            // grant/revoke the GID.
23964            final IActivityManager am = ActivityManager.getService();
23965            if (am != null) {
23966                final long token = Binder.clearCallingIdentity();
23967                try {
23968                    am.killProcessesBelowForeground("setPermissionEnforcement");
23969                } catch (RemoteException e) {
23970                } finally {
23971                    Binder.restoreCallingIdentity(token);
23972                }
23973            }
23974        } else {
23975            throw new IllegalArgumentException("No selective enforcement for " + permission);
23976        }
23977    }
23978
23979    @Override
23980    @Deprecated
23981    public boolean isPermissionEnforced(String permission) {
23982        // allow instant applications
23983        return true;
23984    }
23985
23986    @Override
23987    public boolean isStorageLow() {
23988        // allow instant applications
23989        final long token = Binder.clearCallingIdentity();
23990        try {
23991            final DeviceStorageMonitorInternal
23992                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23993            if (dsm != null) {
23994                return dsm.isMemoryLow();
23995            } else {
23996                return false;
23997            }
23998        } finally {
23999            Binder.restoreCallingIdentity(token);
24000        }
24001    }
24002
24003    @Override
24004    public IPackageInstaller getPackageInstaller() {
24005        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24006            return null;
24007        }
24008        return mInstallerService;
24009    }
24010
24011    private boolean userNeedsBadging(int userId) {
24012        int index = mUserNeedsBadging.indexOfKey(userId);
24013        if (index < 0) {
24014            final UserInfo userInfo;
24015            final long token = Binder.clearCallingIdentity();
24016            try {
24017                userInfo = sUserManager.getUserInfo(userId);
24018            } finally {
24019                Binder.restoreCallingIdentity(token);
24020            }
24021            final boolean b;
24022            if (userInfo != null && userInfo.isManagedProfile()) {
24023                b = true;
24024            } else {
24025                b = false;
24026            }
24027            mUserNeedsBadging.put(userId, b);
24028            return b;
24029        }
24030        return mUserNeedsBadging.valueAt(index);
24031    }
24032
24033    @Override
24034    public KeySet getKeySetByAlias(String packageName, String alias) {
24035        if (packageName == null || alias == null) {
24036            return null;
24037        }
24038        synchronized(mPackages) {
24039            final PackageParser.Package pkg = mPackages.get(packageName);
24040            if (pkg == null) {
24041                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24042                throw new IllegalArgumentException("Unknown package: " + packageName);
24043            }
24044            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24045            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24046                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24047                throw new IllegalArgumentException("Unknown package: " + packageName);
24048            }
24049            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24050            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24051        }
24052    }
24053
24054    @Override
24055    public KeySet getSigningKeySet(String packageName) {
24056        if (packageName == null) {
24057            return null;
24058        }
24059        synchronized(mPackages) {
24060            final int callingUid = Binder.getCallingUid();
24061            final int callingUserId = UserHandle.getUserId(callingUid);
24062            final PackageParser.Package pkg = mPackages.get(packageName);
24063            if (pkg == null) {
24064                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24065                throw new IllegalArgumentException("Unknown package: " + packageName);
24066            }
24067            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24068            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24069                // filter and pretend the package doesn't exist
24070                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24071                        + ", uid:" + callingUid);
24072                throw new IllegalArgumentException("Unknown package: " + packageName);
24073            }
24074            if (pkg.applicationInfo.uid != callingUid
24075                    && Process.SYSTEM_UID != callingUid) {
24076                throw new SecurityException("May not access signing KeySet of other apps.");
24077            }
24078            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24079            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24080        }
24081    }
24082
24083    @Override
24084    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24085        final int callingUid = Binder.getCallingUid();
24086        if (getInstantAppPackageName(callingUid) != null) {
24087            return false;
24088        }
24089        if (packageName == null || ks == null) {
24090            return false;
24091        }
24092        synchronized(mPackages) {
24093            final PackageParser.Package pkg = mPackages.get(packageName);
24094            if (pkg == null
24095                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24096                            UserHandle.getUserId(callingUid))) {
24097                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24098                throw new IllegalArgumentException("Unknown package: " + packageName);
24099            }
24100            IBinder ksh = ks.getToken();
24101            if (ksh instanceof KeySetHandle) {
24102                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24103                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24104            }
24105            return false;
24106        }
24107    }
24108
24109    @Override
24110    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24111        final int callingUid = Binder.getCallingUid();
24112        if (getInstantAppPackageName(callingUid) != null) {
24113            return false;
24114        }
24115        if (packageName == null || ks == null) {
24116            return false;
24117        }
24118        synchronized(mPackages) {
24119            final PackageParser.Package pkg = mPackages.get(packageName);
24120            if (pkg == null
24121                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24122                            UserHandle.getUserId(callingUid))) {
24123                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24124                throw new IllegalArgumentException("Unknown package: " + packageName);
24125            }
24126            IBinder ksh = ks.getToken();
24127            if (ksh instanceof KeySetHandle) {
24128                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24129                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24130            }
24131            return false;
24132        }
24133    }
24134
24135    private void deletePackageIfUnusedLPr(final String packageName) {
24136        PackageSetting ps = mSettings.mPackages.get(packageName);
24137        if (ps == null) {
24138            return;
24139        }
24140        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24141            // TODO Implement atomic delete if package is unused
24142            // It is currently possible that the package will be deleted even if it is installed
24143            // after this method returns.
24144            mHandler.post(new Runnable() {
24145                public void run() {
24146                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24147                            0, PackageManager.DELETE_ALL_USERS);
24148                }
24149            });
24150        }
24151    }
24152
24153    /**
24154     * Check and throw if the given before/after packages would be considered a
24155     * downgrade.
24156     */
24157    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24158            throws PackageManagerException {
24159        if (after.versionCode < before.mVersionCode) {
24160            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24161                    "Update version code " + after.versionCode + " is older than current "
24162                    + before.mVersionCode);
24163        } else if (after.versionCode == before.mVersionCode) {
24164            if (after.baseRevisionCode < before.baseRevisionCode) {
24165                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24166                        "Update base revision code " + after.baseRevisionCode
24167                        + " is older than current " + before.baseRevisionCode);
24168            }
24169
24170            if (!ArrayUtils.isEmpty(after.splitNames)) {
24171                for (int i = 0; i < after.splitNames.length; i++) {
24172                    final String splitName = after.splitNames[i];
24173                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24174                    if (j != -1) {
24175                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24176                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24177                                    "Update split " + splitName + " revision code "
24178                                    + after.splitRevisionCodes[i] + " is older than current "
24179                                    + before.splitRevisionCodes[j]);
24180                        }
24181                    }
24182                }
24183            }
24184        }
24185    }
24186
24187    private static class MoveCallbacks extends Handler {
24188        private static final int MSG_CREATED = 1;
24189        private static final int MSG_STATUS_CHANGED = 2;
24190
24191        private final RemoteCallbackList<IPackageMoveObserver>
24192                mCallbacks = new RemoteCallbackList<>();
24193
24194        private final SparseIntArray mLastStatus = new SparseIntArray();
24195
24196        public MoveCallbacks(Looper looper) {
24197            super(looper);
24198        }
24199
24200        public void register(IPackageMoveObserver callback) {
24201            mCallbacks.register(callback);
24202        }
24203
24204        public void unregister(IPackageMoveObserver callback) {
24205            mCallbacks.unregister(callback);
24206        }
24207
24208        @Override
24209        public void handleMessage(Message msg) {
24210            final SomeArgs args = (SomeArgs) msg.obj;
24211            final int n = mCallbacks.beginBroadcast();
24212            for (int i = 0; i < n; i++) {
24213                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24214                try {
24215                    invokeCallback(callback, msg.what, args);
24216                } catch (RemoteException ignored) {
24217                }
24218            }
24219            mCallbacks.finishBroadcast();
24220            args.recycle();
24221        }
24222
24223        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24224                throws RemoteException {
24225            switch (what) {
24226                case MSG_CREATED: {
24227                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24228                    break;
24229                }
24230                case MSG_STATUS_CHANGED: {
24231                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24232                    break;
24233                }
24234            }
24235        }
24236
24237        private void notifyCreated(int moveId, Bundle extras) {
24238            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24239
24240            final SomeArgs args = SomeArgs.obtain();
24241            args.argi1 = moveId;
24242            args.arg2 = extras;
24243            obtainMessage(MSG_CREATED, args).sendToTarget();
24244        }
24245
24246        private void notifyStatusChanged(int moveId, int status) {
24247            notifyStatusChanged(moveId, status, -1);
24248        }
24249
24250        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24251            Slog.v(TAG, "Move " + moveId + " status " + status);
24252
24253            final SomeArgs args = SomeArgs.obtain();
24254            args.argi1 = moveId;
24255            args.argi2 = status;
24256            args.arg3 = estMillis;
24257            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24258
24259            synchronized (mLastStatus) {
24260                mLastStatus.put(moveId, status);
24261            }
24262        }
24263    }
24264
24265    private final static class OnPermissionChangeListeners extends Handler {
24266        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24267
24268        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24269                new RemoteCallbackList<>();
24270
24271        public OnPermissionChangeListeners(Looper looper) {
24272            super(looper);
24273        }
24274
24275        @Override
24276        public void handleMessage(Message msg) {
24277            switch (msg.what) {
24278                case MSG_ON_PERMISSIONS_CHANGED: {
24279                    final int uid = msg.arg1;
24280                    handleOnPermissionsChanged(uid);
24281                } break;
24282            }
24283        }
24284
24285        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24286            mPermissionListeners.register(listener);
24287
24288        }
24289
24290        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24291            mPermissionListeners.unregister(listener);
24292        }
24293
24294        public void onPermissionsChanged(int uid) {
24295            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24296                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24297            }
24298        }
24299
24300        private void handleOnPermissionsChanged(int uid) {
24301            final int count = mPermissionListeners.beginBroadcast();
24302            try {
24303                for (int i = 0; i < count; i++) {
24304                    IOnPermissionsChangeListener callback = mPermissionListeners
24305                            .getBroadcastItem(i);
24306                    try {
24307                        callback.onPermissionsChanged(uid);
24308                    } catch (RemoteException e) {
24309                        Log.e(TAG, "Permission listener is dead", e);
24310                    }
24311                }
24312            } finally {
24313                mPermissionListeners.finishBroadcast();
24314            }
24315        }
24316    }
24317
24318    private class PackageManagerInternalImpl extends PackageManagerInternal {
24319        @Override
24320        public void setLocationPackagesProvider(PackagesProvider provider) {
24321            synchronized (mPackages) {
24322                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24323            }
24324        }
24325
24326        @Override
24327        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24328            synchronized (mPackages) {
24329                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24330            }
24331        }
24332
24333        @Override
24334        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24335            synchronized (mPackages) {
24336                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24337            }
24338        }
24339
24340        @Override
24341        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24342            synchronized (mPackages) {
24343                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24344            }
24345        }
24346
24347        @Override
24348        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24349            synchronized (mPackages) {
24350                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24351            }
24352        }
24353
24354        @Override
24355        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24356            synchronized (mPackages) {
24357                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24358            }
24359        }
24360
24361        @Override
24362        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24363            synchronized (mPackages) {
24364                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24365                        packageName, userId);
24366            }
24367        }
24368
24369        @Override
24370        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24371            synchronized (mPackages) {
24372                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24373                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24374                        packageName, userId);
24375            }
24376        }
24377
24378        @Override
24379        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24380            synchronized (mPackages) {
24381                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24382                        packageName, userId);
24383            }
24384        }
24385
24386        @Override
24387        public void setKeepUninstalledPackages(final List<String> packageList) {
24388            Preconditions.checkNotNull(packageList);
24389            List<String> removedFromList = null;
24390            synchronized (mPackages) {
24391                if (mKeepUninstalledPackages != null) {
24392                    final int packagesCount = mKeepUninstalledPackages.size();
24393                    for (int i = 0; i < packagesCount; i++) {
24394                        String oldPackage = mKeepUninstalledPackages.get(i);
24395                        if (packageList != null && packageList.contains(oldPackage)) {
24396                            continue;
24397                        }
24398                        if (removedFromList == null) {
24399                            removedFromList = new ArrayList<>();
24400                        }
24401                        removedFromList.add(oldPackage);
24402                    }
24403                }
24404                mKeepUninstalledPackages = new ArrayList<>(packageList);
24405                if (removedFromList != null) {
24406                    final int removedCount = removedFromList.size();
24407                    for (int i = 0; i < removedCount; i++) {
24408                        deletePackageIfUnusedLPr(removedFromList.get(i));
24409                    }
24410                }
24411            }
24412        }
24413
24414        @Override
24415        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24416            synchronized (mPackages) {
24417                // If we do not support permission review, done.
24418                if (!mPermissionReviewRequired) {
24419                    return false;
24420                }
24421
24422                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24423                if (packageSetting == null) {
24424                    return false;
24425                }
24426
24427                // Permission review applies only to apps not supporting the new permission model.
24428                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24429                    return false;
24430                }
24431
24432                // Legacy apps have the permission and get user consent on launch.
24433                PermissionsState permissionsState = packageSetting.getPermissionsState();
24434                return permissionsState.isPermissionReviewRequired(userId);
24435            }
24436        }
24437
24438        @Override
24439        public PackageInfo getPackageInfo(
24440                String packageName, int flags, int filterCallingUid, int userId) {
24441            return PackageManagerService.this
24442                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24443                            flags, filterCallingUid, userId);
24444        }
24445
24446        @Override
24447        public ApplicationInfo getApplicationInfo(
24448                String packageName, int flags, int filterCallingUid, int userId) {
24449            return PackageManagerService.this
24450                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24451        }
24452
24453        @Override
24454        public ActivityInfo getActivityInfo(
24455                ComponentName component, int flags, int filterCallingUid, int userId) {
24456            return PackageManagerService.this
24457                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24458        }
24459
24460        @Override
24461        public List<ResolveInfo> queryIntentActivities(
24462                Intent intent, int flags, int filterCallingUid, int userId) {
24463            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24464            return PackageManagerService.this
24465                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24466                            userId, false /*resolveForStart*/);
24467        }
24468
24469        @Override
24470        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24471                int userId) {
24472            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24473        }
24474
24475        @Override
24476        public void setDeviceAndProfileOwnerPackages(
24477                int deviceOwnerUserId, String deviceOwnerPackage,
24478                SparseArray<String> profileOwnerPackages) {
24479            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24480                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24481        }
24482
24483        @Override
24484        public boolean isPackageDataProtected(int userId, String packageName) {
24485            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24486        }
24487
24488        @Override
24489        public boolean isPackageEphemeral(int userId, String packageName) {
24490            synchronized (mPackages) {
24491                final PackageSetting ps = mSettings.mPackages.get(packageName);
24492                return ps != null ? ps.getInstantApp(userId) : false;
24493            }
24494        }
24495
24496        @Override
24497        public boolean wasPackageEverLaunched(String packageName, int userId) {
24498            synchronized (mPackages) {
24499                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24500            }
24501        }
24502
24503        @Override
24504        public void grantRuntimePermission(String packageName, String name, int userId,
24505                boolean overridePolicy) {
24506            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24507                    overridePolicy);
24508        }
24509
24510        @Override
24511        public void revokeRuntimePermission(String packageName, String name, int userId,
24512                boolean overridePolicy) {
24513            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24514                    overridePolicy);
24515        }
24516
24517        @Override
24518        public String getNameForUid(int uid) {
24519            return PackageManagerService.this.getNameForUid(uid);
24520        }
24521
24522        @Override
24523        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24524                Intent origIntent, String resolvedType, String callingPackage,
24525                Bundle verificationBundle, int userId) {
24526            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24527                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24528                    userId);
24529        }
24530
24531        @Override
24532        public void grantEphemeralAccess(int userId, Intent intent,
24533                int targetAppId, int ephemeralAppId) {
24534            synchronized (mPackages) {
24535                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24536                        targetAppId, ephemeralAppId);
24537            }
24538        }
24539
24540        @Override
24541        public boolean isInstantAppInstallerComponent(ComponentName component) {
24542            synchronized (mPackages) {
24543                return mInstantAppInstallerActivity != null
24544                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24545            }
24546        }
24547
24548        @Override
24549        public void pruneInstantApps() {
24550            mInstantAppRegistry.pruneInstantApps();
24551        }
24552
24553        @Override
24554        public String getSetupWizardPackageName() {
24555            return mSetupWizardPackage;
24556        }
24557
24558        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24559            if (policy != null) {
24560                mExternalSourcesPolicy = policy;
24561            }
24562        }
24563
24564        @Override
24565        public boolean isPackagePersistent(String packageName) {
24566            synchronized (mPackages) {
24567                PackageParser.Package pkg = mPackages.get(packageName);
24568                return pkg != null
24569                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24570                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24571                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24572                        : false;
24573            }
24574        }
24575
24576        @Override
24577        public List<PackageInfo> getOverlayPackages(int userId) {
24578            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24579            synchronized (mPackages) {
24580                for (PackageParser.Package p : mPackages.values()) {
24581                    if (p.mOverlayTarget != null) {
24582                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24583                        if (pkg != null) {
24584                            overlayPackages.add(pkg);
24585                        }
24586                    }
24587                }
24588            }
24589            return overlayPackages;
24590        }
24591
24592        @Override
24593        public List<String> getTargetPackageNames(int userId) {
24594            List<String> targetPackages = new ArrayList<>();
24595            synchronized (mPackages) {
24596                for (PackageParser.Package p : mPackages.values()) {
24597                    if (p.mOverlayTarget == null) {
24598                        targetPackages.add(p.packageName);
24599                    }
24600                }
24601            }
24602            return targetPackages;
24603        }
24604
24605        @Override
24606        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24607                @Nullable List<String> overlayPackageNames) {
24608            synchronized (mPackages) {
24609                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24610                    Slog.e(TAG, "failed to find package " + targetPackageName);
24611                    return false;
24612                }
24613                ArrayList<String> overlayPaths = null;
24614                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24615                    final int N = overlayPackageNames.size();
24616                    overlayPaths = new ArrayList<>(N);
24617                    for (int i = 0; i < N; i++) {
24618                        final String packageName = overlayPackageNames.get(i);
24619                        final PackageParser.Package pkg = mPackages.get(packageName);
24620                        if (pkg == null) {
24621                            Slog.e(TAG, "failed to find package " + packageName);
24622                            return false;
24623                        }
24624                        overlayPaths.add(pkg.baseCodePath);
24625                    }
24626                }
24627
24628                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24629                String[] frameworkOverlayPaths = null;
24630                if (!"android".equals(targetPackageName)) {
24631                    frameworkOverlayPaths =
24632                            mSettings.mPackages.get("android").getOverlayPaths(userId);
24633                }
24634                ps.setOverlayPaths(overlayPaths, frameworkOverlayPaths, userId);
24635                return true;
24636            }
24637        }
24638
24639        @Override
24640        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24641                int flags, int userId) {
24642            return resolveIntentInternal(
24643                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24644        }
24645
24646        @Override
24647        public ResolveInfo resolveService(Intent intent, String resolvedType,
24648                int flags, int userId, int callingUid) {
24649            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24650        }
24651
24652        @Override
24653        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24654            synchronized (mPackages) {
24655                mIsolatedOwners.put(isolatedUid, ownerUid);
24656            }
24657        }
24658
24659        @Override
24660        public void removeIsolatedUid(int isolatedUid) {
24661            synchronized (mPackages) {
24662                mIsolatedOwners.delete(isolatedUid);
24663            }
24664        }
24665
24666        @Override
24667        public int getUidTargetSdkVersion(int uid) {
24668            synchronized (mPackages) {
24669                return getUidTargetSdkVersionLockedLPr(uid);
24670            }
24671        }
24672
24673        @Override
24674        public boolean canAccessInstantApps(int callingUid, int userId) {
24675            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24676        }
24677    }
24678
24679    @Override
24680    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24681        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24682        synchronized (mPackages) {
24683            final long identity = Binder.clearCallingIdentity();
24684            try {
24685                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24686                        packageNames, userId);
24687            } finally {
24688                Binder.restoreCallingIdentity(identity);
24689            }
24690        }
24691    }
24692
24693    @Override
24694    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24695        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24696        synchronized (mPackages) {
24697            final long identity = Binder.clearCallingIdentity();
24698            try {
24699                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24700                        packageNames, userId);
24701            } finally {
24702                Binder.restoreCallingIdentity(identity);
24703            }
24704        }
24705    }
24706
24707    private static void enforceSystemOrPhoneCaller(String tag) {
24708        int callingUid = Binder.getCallingUid();
24709        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24710            throw new SecurityException(
24711                    "Cannot call " + tag + " from UID " + callingUid);
24712        }
24713    }
24714
24715    boolean isHistoricalPackageUsageAvailable() {
24716        return mPackageUsage.isHistoricalPackageUsageAvailable();
24717    }
24718
24719    /**
24720     * Return a <b>copy</b> of the collection of packages known to the package manager.
24721     * @return A copy of the values of mPackages.
24722     */
24723    Collection<PackageParser.Package> getPackages() {
24724        synchronized (mPackages) {
24725            return new ArrayList<>(mPackages.values());
24726        }
24727    }
24728
24729    /**
24730     * Logs process start information (including base APK hash) to the security log.
24731     * @hide
24732     */
24733    @Override
24734    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24735            String apkFile, int pid) {
24736        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24737            return;
24738        }
24739        if (!SecurityLog.isLoggingEnabled()) {
24740            return;
24741        }
24742        Bundle data = new Bundle();
24743        data.putLong("startTimestamp", System.currentTimeMillis());
24744        data.putString("processName", processName);
24745        data.putInt("uid", uid);
24746        data.putString("seinfo", seinfo);
24747        data.putString("apkFile", apkFile);
24748        data.putInt("pid", pid);
24749        Message msg = mProcessLoggingHandler.obtainMessage(
24750                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24751        msg.setData(data);
24752        mProcessLoggingHandler.sendMessage(msg);
24753    }
24754
24755    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24756        return mCompilerStats.getPackageStats(pkgName);
24757    }
24758
24759    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24760        return getOrCreateCompilerPackageStats(pkg.packageName);
24761    }
24762
24763    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24764        return mCompilerStats.getOrCreatePackageStats(pkgName);
24765    }
24766
24767    public void deleteCompilerPackageStats(String pkgName) {
24768        mCompilerStats.deletePackageStats(pkgName);
24769    }
24770
24771    @Override
24772    public int getInstallReason(String packageName, int userId) {
24773        final int callingUid = Binder.getCallingUid();
24774        enforceCrossUserPermission(callingUid, userId,
24775                true /* requireFullPermission */, false /* checkShell */,
24776                "get install reason");
24777        synchronized (mPackages) {
24778            final PackageSetting ps = mSettings.mPackages.get(packageName);
24779            if (filterAppAccessLPr(ps, callingUid, userId)) {
24780                return PackageManager.INSTALL_REASON_UNKNOWN;
24781            }
24782            if (ps != null) {
24783                return ps.getInstallReason(userId);
24784            }
24785        }
24786        return PackageManager.INSTALL_REASON_UNKNOWN;
24787    }
24788
24789    @Override
24790    public boolean canRequestPackageInstalls(String packageName, int userId) {
24791        return canRequestPackageInstallsInternal(packageName, 0, userId,
24792                true /* throwIfPermNotDeclared*/);
24793    }
24794
24795    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24796            boolean throwIfPermNotDeclared) {
24797        int callingUid = Binder.getCallingUid();
24798        int uid = getPackageUid(packageName, 0, userId);
24799        if (callingUid != uid && callingUid != Process.ROOT_UID
24800                && callingUid != Process.SYSTEM_UID) {
24801            throw new SecurityException(
24802                    "Caller uid " + callingUid + " does not own package " + packageName);
24803        }
24804        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24805        if (info == null) {
24806            return false;
24807        }
24808        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24809            return false;
24810        }
24811        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24812        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24813        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24814            if (throwIfPermNotDeclared) {
24815                throw new SecurityException("Need to declare " + appOpPermission
24816                        + " to call this api");
24817            } else {
24818                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24819                return false;
24820            }
24821        }
24822        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24823            return false;
24824        }
24825        if (mExternalSourcesPolicy != null) {
24826            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24827            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24828                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24829            }
24830        }
24831        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24832    }
24833
24834    @Override
24835    public ComponentName getInstantAppResolverSettingsComponent() {
24836        return mInstantAppResolverSettingsComponent;
24837    }
24838
24839    @Override
24840    public ComponentName getInstantAppInstallerComponent() {
24841        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24842            return null;
24843        }
24844        return mInstantAppInstallerActivity == null
24845                ? null : mInstantAppInstallerActivity.getComponentName();
24846    }
24847
24848    @Override
24849    public String getInstantAppAndroidId(String packageName, int userId) {
24850        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24851                "getInstantAppAndroidId");
24852        enforceCrossUserPermission(Binder.getCallingUid(), userId,
24853                true /* requireFullPermission */, false /* checkShell */,
24854                "getInstantAppAndroidId");
24855        // Make sure the target is an Instant App.
24856        if (!isInstantApp(packageName, userId)) {
24857            return null;
24858        }
24859        synchronized (mPackages) {
24860            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24861        }
24862    }
24863}
24864
24865interface PackageSender {
24866    void sendPackageBroadcast(final String action, final String pkg,
24867        final Bundle extras, final int flags, final String targetPkg,
24868        final IIntentReceiver finishedReceiver, final int[] userIds);
24869    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
24870        int appId, int... userIds);
24871}
24872