PackageManagerService.java revision 4501c61d65f0590bdc4e6a8a6f3a1b0cf2165b9f
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
106
107import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
108
109import android.Manifest;
110import android.annotation.IntDef;
111import android.annotation.NonNull;
112import android.annotation.Nullable;
113import android.app.ActivityManager;
114import android.app.AppOpsManager;
115import android.app.IActivityManager;
116import android.app.ResourcesManager;
117import android.app.admin.IDevicePolicyManager;
118import android.app.admin.SecurityLog;
119import android.app.backup.IBackupManager;
120import android.content.BroadcastReceiver;
121import android.content.ComponentName;
122import android.content.ContentResolver;
123import android.content.Context;
124import android.content.IIntentReceiver;
125import android.content.Intent;
126import android.content.IntentFilter;
127import android.content.IntentSender;
128import android.content.IntentSender.SendIntentException;
129import android.content.ServiceConnection;
130import android.content.pm.ActivityInfo;
131import android.content.pm.ApplicationInfo;
132import android.content.pm.AppsQueryHelper;
133import android.content.pm.AuxiliaryResolveInfo;
134import android.content.pm.ChangedPackages;
135import android.content.pm.ComponentInfo;
136import android.content.pm.FallbackCategoryProvider;
137import android.content.pm.FeatureInfo;
138import android.content.pm.IDexModuleRegisterCallback;
139import android.content.pm.IOnPermissionsChangeListener;
140import android.content.pm.IPackageDataObserver;
141import android.content.pm.IPackageDeleteObserver;
142import android.content.pm.IPackageDeleteObserver2;
143import android.content.pm.IPackageInstallObserver2;
144import android.content.pm.IPackageInstaller;
145import android.content.pm.IPackageManager;
146import android.content.pm.IPackageMoveObserver;
147import android.content.pm.IPackageStatsObserver;
148import android.content.pm.InstantAppInfo;
149import android.content.pm.InstantAppRequest;
150import android.content.pm.InstantAppResolveInfo;
151import android.content.pm.InstrumentationInfo;
152import android.content.pm.IntentFilterVerificationInfo;
153import android.content.pm.KeySet;
154import android.content.pm.PackageCleanItem;
155import android.content.pm.PackageInfo;
156import android.content.pm.PackageInfoLite;
157import android.content.pm.PackageInstaller;
158import android.content.pm.PackageManager;
159import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
160import android.content.pm.PackageManagerInternal;
161import android.content.pm.PackageParser;
162import android.content.pm.PackageParser.ActivityIntentInfo;
163import android.content.pm.PackageParser.PackageLite;
164import android.content.pm.PackageParser.PackageParserException;
165import android.content.pm.PackageStats;
166import android.content.pm.PackageUserState;
167import android.content.pm.ParceledListSlice;
168import android.content.pm.PermissionGroupInfo;
169import android.content.pm.PermissionInfo;
170import android.content.pm.ProviderInfo;
171import android.content.pm.ResolveInfo;
172import android.content.pm.ServiceInfo;
173import android.content.pm.SharedLibraryInfo;
174import android.content.pm.Signature;
175import android.content.pm.UserInfo;
176import android.content.pm.VerifierDeviceIdentity;
177import android.content.pm.VerifierInfo;
178import android.content.pm.VersionedPackage;
179import android.content.res.Resources;
180import android.database.ContentObserver;
181import android.graphics.Bitmap;
182import android.hardware.display.DisplayManager;
183import android.net.Uri;
184import android.os.Binder;
185import android.os.Build;
186import android.os.Bundle;
187import android.os.Debug;
188import android.os.Environment;
189import android.os.Environment.UserEnvironment;
190import android.os.FileUtils;
191import android.os.Handler;
192import android.os.IBinder;
193import android.os.Looper;
194import android.os.Message;
195import android.os.Parcel;
196import android.os.ParcelFileDescriptor;
197import android.os.PatternMatcher;
198import android.os.Process;
199import android.os.RemoteCallbackList;
200import android.os.RemoteException;
201import android.os.ResultReceiver;
202import android.os.SELinux;
203import android.os.ServiceManager;
204import android.os.ShellCallback;
205import android.os.SystemClock;
206import android.os.SystemProperties;
207import android.os.Trace;
208import android.os.UserHandle;
209import android.os.UserManager;
210import android.os.UserManagerInternal;
211import android.os.storage.IStorageManager;
212import android.os.storage.StorageEventListener;
213import android.os.storage.StorageManager;
214import android.os.storage.StorageManagerInternal;
215import android.os.storage.VolumeInfo;
216import android.os.storage.VolumeRecord;
217import android.provider.Settings.Global;
218import android.provider.Settings.Secure;
219import android.security.KeyStore;
220import android.security.SystemKeyStore;
221import android.service.pm.PackageServiceDumpProto;
222import android.system.ErrnoException;
223import android.system.Os;
224import android.text.TextUtils;
225import android.text.format.DateUtils;
226import android.util.ArrayMap;
227import android.util.ArraySet;
228import android.util.Base64;
229import android.util.BootTimingsTraceLog;
230import android.util.DisplayMetrics;
231import android.util.EventLog;
232import android.util.ExceptionUtils;
233import android.util.Log;
234import android.util.LogPrinter;
235import android.util.MathUtils;
236import android.util.PackageUtils;
237import android.util.Pair;
238import android.util.PrintStreamPrinter;
239import android.util.Slog;
240import android.util.SparseArray;
241import android.util.SparseBooleanArray;
242import android.util.SparseIntArray;
243import android.util.Xml;
244import android.util.jar.StrictJarFile;
245import android.util.proto.ProtoOutputStream;
246import android.view.Display;
247
248import com.android.internal.R;
249import com.android.internal.annotations.GuardedBy;
250import com.android.internal.app.IMediaContainerService;
251import com.android.internal.app.ResolverActivity;
252import com.android.internal.content.NativeLibraryHelper;
253import com.android.internal.content.PackageHelper;
254import com.android.internal.logging.MetricsLogger;
255import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
256import com.android.internal.os.IParcelFileDescriptorFactory;
257import com.android.internal.os.RoSystemProperties;
258import com.android.internal.os.SomeArgs;
259import com.android.internal.os.Zygote;
260import com.android.internal.telephony.CarrierAppUtils;
261import com.android.internal.util.ArrayUtils;
262import com.android.internal.util.ConcurrentUtils;
263import com.android.internal.util.DumpUtils;
264import com.android.internal.util.FastPrintWriter;
265import com.android.internal.util.FastXmlSerializer;
266import com.android.internal.util.IndentingPrintWriter;
267import com.android.internal.util.Preconditions;
268import com.android.internal.util.XmlUtils;
269import com.android.server.AttributeCache;
270import com.android.server.DeviceIdleController;
271import com.android.server.EventLogTags;
272import com.android.server.FgThread;
273import com.android.server.IntentResolver;
274import com.android.server.LocalServices;
275import com.android.server.LockGuard;
276import com.android.server.ServiceThread;
277import com.android.server.SystemConfig;
278import com.android.server.SystemServerInitThreadPool;
279import com.android.server.Watchdog;
280import com.android.server.net.NetworkPolicyManagerInternal;
281import com.android.server.pm.Installer.InstallerException;
282import com.android.server.pm.PermissionsState.PermissionState;
283import com.android.server.pm.Settings.DatabaseVersion;
284import com.android.server.pm.Settings.VersionInfo;
285import com.android.server.pm.dex.DexManager;
286import com.android.server.pm.dex.DexoptOptions;
287import com.android.server.pm.dex.PackageDexUsage;
288import com.android.server.storage.DeviceStorageMonitorInternal;
289
290import dalvik.system.CloseGuard;
291import dalvik.system.DexFile;
292import dalvik.system.VMRuntime;
293
294import libcore.io.IoUtils;
295import libcore.io.Streams;
296import libcore.util.EmptyArray;
297
298import org.xmlpull.v1.XmlPullParser;
299import org.xmlpull.v1.XmlPullParserException;
300import org.xmlpull.v1.XmlSerializer;
301
302import java.io.BufferedOutputStream;
303import java.io.BufferedReader;
304import java.io.ByteArrayInputStream;
305import java.io.ByteArrayOutputStream;
306import java.io.File;
307import java.io.FileDescriptor;
308import java.io.FileInputStream;
309import java.io.FileOutputStream;
310import java.io.FileReader;
311import java.io.FilenameFilter;
312import java.io.IOException;
313import java.io.InputStream;
314import java.io.OutputStream;
315import java.io.PrintWriter;
316import java.lang.annotation.Retention;
317import java.lang.annotation.RetentionPolicy;
318import java.nio.charset.StandardCharsets;
319import java.security.DigestInputStream;
320import java.security.MessageDigest;
321import java.security.NoSuchAlgorithmException;
322import java.security.PublicKey;
323import java.security.SecureRandom;
324import java.security.cert.Certificate;
325import java.security.cert.CertificateEncodingException;
326import java.security.cert.CertificateException;
327import java.text.SimpleDateFormat;
328import java.util.ArrayList;
329import java.util.Arrays;
330import java.util.Collection;
331import java.util.Collections;
332import java.util.Comparator;
333import java.util.Date;
334import java.util.HashMap;
335import java.util.HashSet;
336import java.util.Iterator;
337import java.util.List;
338import java.util.Map;
339import java.util.Objects;
340import java.util.Set;
341import java.util.concurrent.CountDownLatch;
342import java.util.concurrent.Future;
343import java.util.concurrent.TimeUnit;
344import java.util.concurrent.atomic.AtomicBoolean;
345import java.util.concurrent.atomic.AtomicInteger;
346import java.util.zip.GZIPInputStream;
347
348/**
349 * Keep track of all those APKs everywhere.
350 * <p>
351 * Internally there are two important locks:
352 * <ul>
353 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
354 * and other related state. It is a fine-grained lock that should only be held
355 * momentarily, as it's one of the most contended locks in the system.
356 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
357 * operations typically involve heavy lifting of application data on disk. Since
358 * {@code installd} is single-threaded, and it's operations can often be slow,
359 * this lock should never be acquired while already holding {@link #mPackages}.
360 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
361 * holding {@link #mInstallLock}.
362 * </ul>
363 * Many internal methods rely on the caller to hold the appropriate locks, and
364 * this contract is expressed through method name suffixes:
365 * <ul>
366 * <li>fooLI(): the caller must hold {@link #mInstallLock}
367 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
368 * being modified must be frozen
369 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
370 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
371 * </ul>
372 * <p>
373 * Because this class is very central to the platform's security; please run all
374 * CTS and unit tests whenever making modifications:
375 *
376 * <pre>
377 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
378 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
379 * </pre>
380 */
381public class PackageManagerService extends IPackageManager.Stub
382        implements PackageSender {
383    static final String TAG = "PackageManager";
384    static final boolean DEBUG_SETTINGS = false;
385    static final boolean DEBUG_PREFERRED = false;
386    static final boolean DEBUG_UPGRADE = false;
387    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
388    private static final boolean DEBUG_BACKUP = false;
389    private static final boolean DEBUG_INSTALL = false;
390    private static final boolean DEBUG_REMOVE = false;
391    private static final boolean DEBUG_BROADCASTS = false;
392    private static final boolean DEBUG_SHOW_INFO = false;
393    private static final boolean DEBUG_PACKAGE_INFO = false;
394    private static final boolean DEBUG_INTENT_MATCHING = false;
395    private static final boolean DEBUG_PACKAGE_SCANNING = false;
396    private static final boolean DEBUG_VERIFY = false;
397    private static final boolean DEBUG_FILTERS = false;
398    private static final boolean DEBUG_PERMISSIONS = false;
399    private static final boolean DEBUG_SHARED_LIBRARIES = false;
400    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
401
402    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
403    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
404    // user, but by default initialize to this.
405    public static final boolean DEBUG_DEXOPT = false;
406
407    private static final boolean DEBUG_ABI_SELECTION = false;
408    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
409    private static final boolean DEBUG_TRIAGED_MISSING = false;
410    private static final boolean DEBUG_APP_DATA = false;
411
412    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
413    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
414
415    private static final boolean HIDE_EPHEMERAL_APIS = false;
416
417    private static final boolean ENABLE_FREE_CACHE_V2 =
418            SystemProperties.getBoolean("fw.free_cache_v2", true);
419
420    private static final int RADIO_UID = Process.PHONE_UID;
421    private static final int LOG_UID = Process.LOG_UID;
422    private static final int NFC_UID = Process.NFC_UID;
423    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
424    private static final int SHELL_UID = Process.SHELL_UID;
425
426    // Cap the size of permission trees that 3rd party apps can define
427    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
428
429    // Suffix used during package installation when copying/moving
430    // package apks to install directory.
431    private static final String INSTALL_PACKAGE_SUFFIX = "-";
432
433    static final int SCAN_NO_DEX = 1<<1;
434    static final int SCAN_FORCE_DEX = 1<<2;
435    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
436    static final int SCAN_NEW_INSTALL = 1<<4;
437    static final int SCAN_UPDATE_TIME = 1<<5;
438    static final int SCAN_BOOTING = 1<<6;
439    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
440    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
441    static final int SCAN_REPLACING = 1<<9;
442    static final int SCAN_REQUIRE_KNOWN = 1<<10;
443    static final int SCAN_MOVE = 1<<11;
444    static final int SCAN_INITIAL = 1<<12;
445    static final int SCAN_CHECK_ONLY = 1<<13;
446    static final int SCAN_DONT_KILL_APP = 1<<14;
447    static final int SCAN_IGNORE_FROZEN = 1<<15;
448    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
449    static final int SCAN_AS_INSTANT_APP = 1<<17;
450    static final int SCAN_AS_FULL_APP = 1<<18;
451    /** Should not be with the scan flags */
452    static final int FLAGS_REMOVE_CHATTY = 1<<31;
453
454    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
455    /** Extension of the compressed packages */
456    private final static String COMPRESSED_EXTENSION = ".gz";
457
458    private static final int[] EMPTY_INT_ARRAY = new int[0];
459
460    private static final int TYPE_UNKNOWN = 0;
461    private static final int TYPE_ACTIVITY = 1;
462    private static final int TYPE_RECEIVER = 2;
463    private static final int TYPE_SERVICE = 3;
464    private static final int TYPE_PROVIDER = 4;
465    @IntDef(prefix = { "TYPE_" }, value = {
466            TYPE_UNKNOWN,
467            TYPE_ACTIVITY,
468            TYPE_RECEIVER,
469            TYPE_SERVICE,
470            TYPE_PROVIDER,
471    })
472    @Retention(RetentionPolicy.SOURCE)
473    public @interface ComponentType {}
474
475    /**
476     * Timeout (in milliseconds) after which the watchdog should declare that
477     * our handler thread is wedged.  The usual default for such things is one
478     * minute but we sometimes do very lengthy I/O operations on this thread,
479     * such as installing multi-gigabyte applications, so ours needs to be longer.
480     */
481    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
482
483    /**
484     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
485     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
486     * settings entry if available, otherwise we use the hardcoded default.  If it's been
487     * more than this long since the last fstrim, we force one during the boot sequence.
488     *
489     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
490     * one gets run at the next available charging+idle time.  This final mandatory
491     * no-fstrim check kicks in only of the other scheduling criteria is never met.
492     */
493    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
494
495    /**
496     * Whether verification is enabled by default.
497     */
498    private static final boolean DEFAULT_VERIFY_ENABLE = true;
499
500    /**
501     * The default maximum time to wait for the verification agent to return in
502     * milliseconds.
503     */
504    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
505
506    /**
507     * The default response for package verification timeout.
508     *
509     * This can be either PackageManager.VERIFICATION_ALLOW or
510     * PackageManager.VERIFICATION_REJECT.
511     */
512    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
513
514    static final String PLATFORM_PACKAGE_NAME = "android";
515
516    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
517
518    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
519            DEFAULT_CONTAINER_PACKAGE,
520            "com.android.defcontainer.DefaultContainerService");
521
522    private static final String KILL_APP_REASON_GIDS_CHANGED =
523            "permission grant or revoke changed gids";
524
525    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
526            "permissions revoked";
527
528    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
529
530    private static final String PACKAGE_SCHEME = "package";
531
532    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
533
534    /** Permission grant: not grant the permission. */
535    private static final int GRANT_DENIED = 1;
536
537    /** Permission grant: grant the permission as an install permission. */
538    private static final int GRANT_INSTALL = 2;
539
540    /** Permission grant: grant the permission as a runtime one. */
541    private static final int GRANT_RUNTIME = 3;
542
543    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
544    private static final int GRANT_UPGRADE = 4;
545
546    /** Canonical intent used to identify what counts as a "web browser" app */
547    private static final Intent sBrowserIntent;
548    static {
549        sBrowserIntent = new Intent();
550        sBrowserIntent.setAction(Intent.ACTION_VIEW);
551        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
552        sBrowserIntent.setData(Uri.parse("http:"));
553    }
554
555    /**
556     * The set of all protected actions [i.e. those actions for which a high priority
557     * intent filter is disallowed].
558     */
559    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
560    static {
561        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
562        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
563        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
564        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
565    }
566
567    // Compilation reasons.
568    public static final int REASON_FIRST_BOOT = 0;
569    public static final int REASON_BOOT = 1;
570    public static final int REASON_INSTALL = 2;
571    public static final int REASON_BACKGROUND_DEXOPT = 3;
572    public static final int REASON_AB_OTA = 4;
573    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
574
575    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
576
577    /** All dangerous permission names in the same order as the events in MetricsEvent */
578    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
579            Manifest.permission.READ_CALENDAR,
580            Manifest.permission.WRITE_CALENDAR,
581            Manifest.permission.CAMERA,
582            Manifest.permission.READ_CONTACTS,
583            Manifest.permission.WRITE_CONTACTS,
584            Manifest.permission.GET_ACCOUNTS,
585            Manifest.permission.ACCESS_FINE_LOCATION,
586            Manifest.permission.ACCESS_COARSE_LOCATION,
587            Manifest.permission.RECORD_AUDIO,
588            Manifest.permission.READ_PHONE_STATE,
589            Manifest.permission.CALL_PHONE,
590            Manifest.permission.READ_CALL_LOG,
591            Manifest.permission.WRITE_CALL_LOG,
592            Manifest.permission.ADD_VOICEMAIL,
593            Manifest.permission.USE_SIP,
594            Manifest.permission.PROCESS_OUTGOING_CALLS,
595            Manifest.permission.READ_CELL_BROADCASTS,
596            Manifest.permission.BODY_SENSORS,
597            Manifest.permission.SEND_SMS,
598            Manifest.permission.RECEIVE_SMS,
599            Manifest.permission.READ_SMS,
600            Manifest.permission.RECEIVE_WAP_PUSH,
601            Manifest.permission.RECEIVE_MMS,
602            Manifest.permission.READ_EXTERNAL_STORAGE,
603            Manifest.permission.WRITE_EXTERNAL_STORAGE,
604            Manifest.permission.READ_PHONE_NUMBERS,
605            Manifest.permission.ANSWER_PHONE_CALLS);
606
607
608    /**
609     * Version number for the package parser cache. Increment this whenever the format or
610     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
611     */
612    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
613
614    /**
615     * Whether the package parser cache is enabled.
616     */
617    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
618
619    final ServiceThread mHandlerThread;
620
621    final PackageHandler mHandler;
622
623    private final ProcessLoggingHandler mProcessLoggingHandler;
624
625    /**
626     * Messages for {@link #mHandler} that need to wait for system ready before
627     * being dispatched.
628     */
629    private ArrayList<Message> mPostSystemReadyMessages;
630
631    final int mSdkVersion = Build.VERSION.SDK_INT;
632
633    final Context mContext;
634    final boolean mFactoryTest;
635    final boolean mOnlyCore;
636    final DisplayMetrics mMetrics;
637    final int mDefParseFlags;
638    final String[] mSeparateProcesses;
639    final boolean mIsUpgrade;
640    final boolean mIsPreNUpgrade;
641    final boolean mIsPreNMR1Upgrade;
642
643    // Have we told the Activity Manager to whitelist the default container service by uid yet?
644    @GuardedBy("mPackages")
645    boolean mDefaultContainerWhitelisted = false;
646
647    @GuardedBy("mPackages")
648    private boolean mDexOptDialogShown;
649
650    /** The location for ASEC container files on internal storage. */
651    final String mAsecInternalPath;
652
653    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
654    // LOCK HELD.  Can be called with mInstallLock held.
655    @GuardedBy("mInstallLock")
656    final Installer mInstaller;
657
658    /** Directory where installed third-party apps stored */
659    final File mAppInstallDir;
660
661    /**
662     * Directory to which applications installed internally have their
663     * 32 bit native libraries copied.
664     */
665    private File mAppLib32InstallDir;
666
667    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
668    // apps.
669    final File mDrmAppPrivateInstallDir;
670
671    // ----------------------------------------------------------------
672
673    // Lock for state used when installing and doing other long running
674    // operations.  Methods that must be called with this lock held have
675    // the suffix "LI".
676    final Object mInstallLock = new Object();
677
678    // ----------------------------------------------------------------
679
680    // Keys are String (package name), values are Package.  This also serves
681    // as the lock for the global state.  Methods that must be called with
682    // this lock held have the prefix "LP".
683    @GuardedBy("mPackages")
684    final ArrayMap<String, PackageParser.Package> mPackages =
685            new ArrayMap<String, PackageParser.Package>();
686
687    final ArrayMap<String, Set<String>> mKnownCodebase =
688            new ArrayMap<String, Set<String>>();
689
690    // Keys are isolated uids and values are the uid of the application
691    // that created the isolated proccess.
692    @GuardedBy("mPackages")
693    final SparseIntArray mIsolatedOwners = new SparseIntArray();
694
695    /**
696     * Tracks new system packages [received in an OTA] that we expect to
697     * find updated user-installed versions. Keys are package name, values
698     * are package location.
699     */
700    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
701    /**
702     * Tracks high priority intent filters for protected actions. During boot, certain
703     * filter actions are protected and should never be allowed to have a high priority
704     * intent filter for them. However, there is one, and only one exception -- the
705     * setup wizard. It must be able to define a high priority intent filter for these
706     * actions to ensure there are no escapes from the wizard. We need to delay processing
707     * of these during boot as we need to look at all of the system packages in order
708     * to know which component is the setup wizard.
709     */
710    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
711    /**
712     * Whether or not processing protected filters should be deferred.
713     */
714    private boolean mDeferProtectedFilters = true;
715
716    /**
717     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
718     */
719    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
720    /**
721     * Whether or not system app permissions should be promoted from install to runtime.
722     */
723    boolean mPromoteSystemApps;
724
725    @GuardedBy("mPackages")
726    final Settings mSettings;
727
728    /**
729     * Set of package names that are currently "frozen", which means active
730     * surgery is being done on the code/data for that package. The platform
731     * will refuse to launch frozen packages to avoid race conditions.
732     *
733     * @see PackageFreezer
734     */
735    @GuardedBy("mPackages")
736    final ArraySet<String> mFrozenPackages = new ArraySet<>();
737
738    final ProtectedPackages mProtectedPackages;
739
740    @GuardedBy("mLoadedVolumes")
741    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
742
743    boolean mFirstBoot;
744
745    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
746
747    // System configuration read by SystemConfig.
748    final int[] mGlobalGids;
749    final SparseArray<ArraySet<String>> mSystemPermissions;
750    @GuardedBy("mAvailableFeatures")
751    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
752
753    // If mac_permissions.xml was found for seinfo labeling.
754    boolean mFoundPolicyFile;
755
756    private final InstantAppRegistry mInstantAppRegistry;
757
758    @GuardedBy("mPackages")
759    int mChangedPackagesSequenceNumber;
760    /**
761     * List of changed [installed, removed or updated] packages.
762     * mapping from user id -> sequence number -> package name
763     */
764    @GuardedBy("mPackages")
765    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
766    /**
767     * The sequence number of the last change to a package.
768     * mapping from user id -> package name -> sequence number
769     */
770    @GuardedBy("mPackages")
771    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
772
773    class PackageParserCallback implements PackageParser.Callback {
774        @Override public final boolean hasFeature(String feature) {
775            return PackageManagerService.this.hasSystemFeature(feature, 0);
776        }
777
778        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
779                Collection<PackageParser.Package> allPackages, String targetPackageName) {
780            List<PackageParser.Package> overlayPackages = null;
781            for (PackageParser.Package p : allPackages) {
782                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
783                    if (overlayPackages == null) {
784                        overlayPackages = new ArrayList<PackageParser.Package>();
785                    }
786                    overlayPackages.add(p);
787                }
788            }
789            if (overlayPackages != null) {
790                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
791                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
792                        return p1.mOverlayPriority - p2.mOverlayPriority;
793                    }
794                };
795                Collections.sort(overlayPackages, cmp);
796            }
797            return overlayPackages;
798        }
799
800        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
801                String targetPackageName, String targetPath) {
802            if ("android".equals(targetPackageName)) {
803                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
804                // native AssetManager.
805                return null;
806            }
807            List<PackageParser.Package> overlayPackages =
808                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
809            if (overlayPackages == null || overlayPackages.isEmpty()) {
810                return null;
811            }
812            List<String> overlayPathList = null;
813            for (PackageParser.Package overlayPackage : overlayPackages) {
814                if (targetPath == null) {
815                    if (overlayPathList == null) {
816                        overlayPathList = new ArrayList<String>();
817                    }
818                    overlayPathList.add(overlayPackage.baseCodePath);
819                    continue;
820                }
821
822                try {
823                    // Creates idmaps for system to parse correctly the Android manifest of the
824                    // target package.
825                    //
826                    // OverlayManagerService will update each of them with a correct gid from its
827                    // target package app id.
828                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
829                            UserHandle.getSharedAppGid(
830                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
831                    if (overlayPathList == null) {
832                        overlayPathList = new ArrayList<String>();
833                    }
834                    overlayPathList.add(overlayPackage.baseCodePath);
835                } catch (InstallerException e) {
836                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
837                            overlayPackage.baseCodePath);
838                }
839            }
840            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
841        }
842
843        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
844            synchronized (mPackages) {
845                return getStaticOverlayPathsLocked(
846                        mPackages.values(), targetPackageName, targetPath);
847            }
848        }
849
850        @Override public final String[] getOverlayApks(String targetPackageName) {
851            return getStaticOverlayPaths(targetPackageName, null);
852        }
853
854        @Override public final String[] getOverlayPaths(String targetPackageName,
855                String targetPath) {
856            return getStaticOverlayPaths(targetPackageName, targetPath);
857        }
858    };
859
860    class ParallelPackageParserCallback extends PackageParserCallback {
861        List<PackageParser.Package> mOverlayPackages = null;
862
863        void findStaticOverlayPackages() {
864            synchronized (mPackages) {
865                for (PackageParser.Package p : mPackages.values()) {
866                    if (p.mIsStaticOverlay) {
867                        if (mOverlayPackages == null) {
868                            mOverlayPackages = new ArrayList<PackageParser.Package>();
869                        }
870                        mOverlayPackages.add(p);
871                    }
872                }
873            }
874        }
875
876        @Override
877        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
878            // We can trust mOverlayPackages without holding mPackages because package uninstall
879            // can't happen while running parallel parsing.
880            // Moreover holding mPackages on each parsing thread causes dead-lock.
881            return mOverlayPackages == null ? null :
882                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
883        }
884    }
885
886    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
887    final ParallelPackageParserCallback mParallelPackageParserCallback =
888            new ParallelPackageParserCallback();
889
890    public static final class SharedLibraryEntry {
891        public final @Nullable String path;
892        public final @Nullable String apk;
893        public final @NonNull SharedLibraryInfo info;
894
895        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
896                String declaringPackageName, int declaringPackageVersionCode) {
897            path = _path;
898            apk = _apk;
899            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
900                    declaringPackageName, declaringPackageVersionCode), null);
901        }
902    }
903
904    // Currently known shared libraries.
905    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
906    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
907            new ArrayMap<>();
908
909    // All available activities, for your resolving pleasure.
910    final ActivityIntentResolver mActivities =
911            new ActivityIntentResolver();
912
913    // All available receivers, for your resolving pleasure.
914    final ActivityIntentResolver mReceivers =
915            new ActivityIntentResolver();
916
917    // All available services, for your resolving pleasure.
918    final ServiceIntentResolver mServices = new ServiceIntentResolver();
919
920    // All available providers, for your resolving pleasure.
921    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
922
923    // Mapping from provider base names (first directory in content URI codePath)
924    // to the provider information.
925    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
926            new ArrayMap<String, PackageParser.Provider>();
927
928    // Mapping from instrumentation class names to info about them.
929    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
930            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
931
932    // Mapping from permission names to info about them.
933    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
934            new ArrayMap<String, PackageParser.PermissionGroup>();
935
936    // Packages whose data we have transfered into another package, thus
937    // should no longer exist.
938    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
939
940    // Broadcast actions that are only available to the system.
941    @GuardedBy("mProtectedBroadcasts")
942    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
943
944    /** List of packages waiting for verification. */
945    final SparseArray<PackageVerificationState> mPendingVerification
946            = new SparseArray<PackageVerificationState>();
947
948    /** Set of packages associated with each app op permission. */
949    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
950
951    final PackageInstallerService mInstallerService;
952
953    private final PackageDexOptimizer mPackageDexOptimizer;
954    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
955    // is used by other apps).
956    private final DexManager mDexManager;
957
958    private AtomicInteger mNextMoveId = new AtomicInteger();
959    private final MoveCallbacks mMoveCallbacks;
960
961    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
962
963    // Cache of users who need badging.
964    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
965
966    /** Token for keys in mPendingVerification. */
967    private int mPendingVerificationToken = 0;
968
969    volatile boolean mSystemReady;
970    volatile boolean mSafeMode;
971    volatile boolean mHasSystemUidErrors;
972    private volatile boolean mEphemeralAppsDisabled;
973
974    ApplicationInfo mAndroidApplication;
975    final ActivityInfo mResolveActivity = new ActivityInfo();
976    final ResolveInfo mResolveInfo = new ResolveInfo();
977    ComponentName mResolveComponentName;
978    PackageParser.Package mPlatformPackage;
979    ComponentName mCustomResolverComponentName;
980
981    boolean mResolverReplaced = false;
982
983    private final @Nullable ComponentName mIntentFilterVerifierComponent;
984    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
985
986    private int mIntentFilterVerificationToken = 0;
987
988    /** The service connection to the ephemeral resolver */
989    final EphemeralResolverConnection mInstantAppResolverConnection;
990    /** Component used to show resolver settings for Instant Apps */
991    final ComponentName mInstantAppResolverSettingsComponent;
992
993    /** Activity used to install instant applications */
994    ActivityInfo mInstantAppInstallerActivity;
995    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
996
997    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
998            = new SparseArray<IntentFilterVerificationState>();
999
1000    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1001
1002    // List of packages names to keep cached, even if they are uninstalled for all users
1003    private List<String> mKeepUninstalledPackages;
1004
1005    private UserManagerInternal mUserManagerInternal;
1006
1007    private DeviceIdleController.LocalService mDeviceIdleController;
1008
1009    private File mCacheDir;
1010
1011    private ArraySet<String> mPrivappPermissionsViolations;
1012
1013    private Future<?> mPrepareAppDataFuture;
1014
1015    private static class IFVerificationParams {
1016        PackageParser.Package pkg;
1017        boolean replacing;
1018        int userId;
1019        int verifierUid;
1020
1021        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1022                int _userId, int _verifierUid) {
1023            pkg = _pkg;
1024            replacing = _replacing;
1025            userId = _userId;
1026            replacing = _replacing;
1027            verifierUid = _verifierUid;
1028        }
1029    }
1030
1031    private interface IntentFilterVerifier<T extends IntentFilter> {
1032        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1033                                               T filter, String packageName);
1034        void startVerifications(int userId);
1035        void receiveVerificationResponse(int verificationId);
1036    }
1037
1038    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1039        private Context mContext;
1040        private ComponentName mIntentFilterVerifierComponent;
1041        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1042
1043        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1044            mContext = context;
1045            mIntentFilterVerifierComponent = verifierComponent;
1046        }
1047
1048        private String getDefaultScheme() {
1049            return IntentFilter.SCHEME_HTTPS;
1050        }
1051
1052        @Override
1053        public void startVerifications(int userId) {
1054            // Launch verifications requests
1055            int count = mCurrentIntentFilterVerifications.size();
1056            for (int n=0; n<count; n++) {
1057                int verificationId = mCurrentIntentFilterVerifications.get(n);
1058                final IntentFilterVerificationState ivs =
1059                        mIntentFilterVerificationStates.get(verificationId);
1060
1061                String packageName = ivs.getPackageName();
1062
1063                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1064                final int filterCount = filters.size();
1065                ArraySet<String> domainsSet = new ArraySet<>();
1066                for (int m=0; m<filterCount; m++) {
1067                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1068                    domainsSet.addAll(filter.getHostsList());
1069                }
1070                synchronized (mPackages) {
1071                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1072                            packageName, domainsSet) != null) {
1073                        scheduleWriteSettingsLocked();
1074                    }
1075                }
1076                sendVerificationRequest(verificationId, ivs);
1077            }
1078            mCurrentIntentFilterVerifications.clear();
1079        }
1080
1081        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1082            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1083            verificationIntent.putExtra(
1084                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1085                    verificationId);
1086            verificationIntent.putExtra(
1087                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1088                    getDefaultScheme());
1089            verificationIntent.putExtra(
1090                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1091                    ivs.getHostsString());
1092            verificationIntent.putExtra(
1093                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1094                    ivs.getPackageName());
1095            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1096            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1097
1098            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1099            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1100                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1101                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1102
1103            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1104            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1105                    "Sending IntentFilter verification broadcast");
1106        }
1107
1108        public void receiveVerificationResponse(int verificationId) {
1109            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1110
1111            final boolean verified = ivs.isVerified();
1112
1113            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1114            final int count = filters.size();
1115            if (DEBUG_DOMAIN_VERIFICATION) {
1116                Slog.i(TAG, "Received verification response " + verificationId
1117                        + " for " + count + " filters, verified=" + verified);
1118            }
1119            for (int n=0; n<count; n++) {
1120                PackageParser.ActivityIntentInfo filter = filters.get(n);
1121                filter.setVerified(verified);
1122
1123                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1124                        + " verified with result:" + verified + " and hosts:"
1125                        + ivs.getHostsString());
1126            }
1127
1128            mIntentFilterVerificationStates.remove(verificationId);
1129
1130            final String packageName = ivs.getPackageName();
1131            IntentFilterVerificationInfo ivi = null;
1132
1133            synchronized (mPackages) {
1134                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1135            }
1136            if (ivi == null) {
1137                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1138                        + verificationId + " packageName:" + packageName);
1139                return;
1140            }
1141            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1142                    "Updating IntentFilterVerificationInfo for package " + packageName
1143                            +" verificationId:" + verificationId);
1144
1145            synchronized (mPackages) {
1146                if (verified) {
1147                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1148                } else {
1149                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1150                }
1151                scheduleWriteSettingsLocked();
1152
1153                final int userId = ivs.getUserId();
1154                if (userId != UserHandle.USER_ALL) {
1155                    final int userStatus =
1156                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1157
1158                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1159                    boolean needUpdate = false;
1160
1161                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1162                    // already been set by the User thru the Disambiguation dialog
1163                    switch (userStatus) {
1164                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1165                            if (verified) {
1166                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1167                            } else {
1168                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1169                            }
1170                            needUpdate = true;
1171                            break;
1172
1173                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1174                            if (verified) {
1175                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1176                                needUpdate = true;
1177                            }
1178                            break;
1179
1180                        default:
1181                            // Nothing to do
1182                    }
1183
1184                    if (needUpdate) {
1185                        mSettings.updateIntentFilterVerificationStatusLPw(
1186                                packageName, updatedStatus, userId);
1187                        scheduleWritePackageRestrictionsLocked(userId);
1188                    }
1189                }
1190            }
1191        }
1192
1193        @Override
1194        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1195                    ActivityIntentInfo filter, String packageName) {
1196            if (!hasValidDomains(filter)) {
1197                return false;
1198            }
1199            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1200            if (ivs == null) {
1201                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1202                        packageName);
1203            }
1204            if (DEBUG_DOMAIN_VERIFICATION) {
1205                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1206            }
1207            ivs.addFilter(filter);
1208            return true;
1209        }
1210
1211        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1212                int userId, int verificationId, String packageName) {
1213            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1214                    verifierUid, userId, packageName);
1215            ivs.setPendingState();
1216            synchronized (mPackages) {
1217                mIntentFilterVerificationStates.append(verificationId, ivs);
1218                mCurrentIntentFilterVerifications.add(verificationId);
1219            }
1220            return ivs;
1221        }
1222    }
1223
1224    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1225        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1226                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1227                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1228    }
1229
1230    // Set of pending broadcasts for aggregating enable/disable of components.
1231    static class PendingPackageBroadcasts {
1232        // for each user id, a map of <package name -> components within that package>
1233        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1234
1235        public PendingPackageBroadcasts() {
1236            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1237        }
1238
1239        public ArrayList<String> get(int userId, String packageName) {
1240            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1241            return packages.get(packageName);
1242        }
1243
1244        public void put(int userId, String packageName, ArrayList<String> components) {
1245            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1246            packages.put(packageName, components);
1247        }
1248
1249        public void remove(int userId, String packageName) {
1250            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1251            if (packages != null) {
1252                packages.remove(packageName);
1253            }
1254        }
1255
1256        public void remove(int userId) {
1257            mUidMap.remove(userId);
1258        }
1259
1260        public int userIdCount() {
1261            return mUidMap.size();
1262        }
1263
1264        public int userIdAt(int n) {
1265            return mUidMap.keyAt(n);
1266        }
1267
1268        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1269            return mUidMap.get(userId);
1270        }
1271
1272        public int size() {
1273            // total number of pending broadcast entries across all userIds
1274            int num = 0;
1275            for (int i = 0; i< mUidMap.size(); i++) {
1276                num += mUidMap.valueAt(i).size();
1277            }
1278            return num;
1279        }
1280
1281        public void clear() {
1282            mUidMap.clear();
1283        }
1284
1285        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1286            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1287            if (map == null) {
1288                map = new ArrayMap<String, ArrayList<String>>();
1289                mUidMap.put(userId, map);
1290            }
1291            return map;
1292        }
1293    }
1294    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1295
1296    // Service Connection to remote media container service to copy
1297    // package uri's from external media onto secure containers
1298    // or internal storage.
1299    private IMediaContainerService mContainerService = null;
1300
1301    static final int SEND_PENDING_BROADCAST = 1;
1302    static final int MCS_BOUND = 3;
1303    static final int END_COPY = 4;
1304    static final int INIT_COPY = 5;
1305    static final int MCS_UNBIND = 6;
1306    static final int START_CLEANING_PACKAGE = 7;
1307    static final int FIND_INSTALL_LOC = 8;
1308    static final int POST_INSTALL = 9;
1309    static final int MCS_RECONNECT = 10;
1310    static final int MCS_GIVE_UP = 11;
1311    static final int UPDATED_MEDIA_STATUS = 12;
1312    static final int WRITE_SETTINGS = 13;
1313    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1314    static final int PACKAGE_VERIFIED = 15;
1315    static final int CHECK_PENDING_VERIFICATION = 16;
1316    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1317    static final int INTENT_FILTER_VERIFIED = 18;
1318    static final int WRITE_PACKAGE_LIST = 19;
1319    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1320
1321    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1322
1323    // Delay time in millisecs
1324    static final int BROADCAST_DELAY = 10 * 1000;
1325
1326    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1327            2 * 60 * 60 * 1000L; /* two hours */
1328
1329    static UserManagerService sUserManager;
1330
1331    // Stores a list of users whose package restrictions file needs to be updated
1332    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1333
1334    final private DefaultContainerConnection mDefContainerConn =
1335            new DefaultContainerConnection();
1336    class DefaultContainerConnection implements ServiceConnection {
1337        public void onServiceConnected(ComponentName name, IBinder service) {
1338            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1339            final IMediaContainerService imcs = IMediaContainerService.Stub
1340                    .asInterface(Binder.allowBlocking(service));
1341            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1342        }
1343
1344        public void onServiceDisconnected(ComponentName name) {
1345            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1346        }
1347    }
1348
1349    // Recordkeeping of restore-after-install operations that are currently in flight
1350    // between the Package Manager and the Backup Manager
1351    static class PostInstallData {
1352        public InstallArgs args;
1353        public PackageInstalledInfo res;
1354
1355        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1356            args = _a;
1357            res = _r;
1358        }
1359    }
1360
1361    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1362    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1363
1364    // XML tags for backup/restore of various bits of state
1365    private static final String TAG_PREFERRED_BACKUP = "pa";
1366    private static final String TAG_DEFAULT_APPS = "da";
1367    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1368
1369    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1370    private static final String TAG_ALL_GRANTS = "rt-grants";
1371    private static final String TAG_GRANT = "grant";
1372    private static final String ATTR_PACKAGE_NAME = "pkg";
1373
1374    private static final String TAG_PERMISSION = "perm";
1375    private static final String ATTR_PERMISSION_NAME = "name";
1376    private static final String ATTR_IS_GRANTED = "g";
1377    private static final String ATTR_USER_SET = "set";
1378    private static final String ATTR_USER_FIXED = "fixed";
1379    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1380
1381    // System/policy permission grants are not backed up
1382    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1383            FLAG_PERMISSION_POLICY_FIXED
1384            | FLAG_PERMISSION_SYSTEM_FIXED
1385            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1386
1387    // And we back up these user-adjusted states
1388    private static final int USER_RUNTIME_GRANT_MASK =
1389            FLAG_PERMISSION_USER_SET
1390            | FLAG_PERMISSION_USER_FIXED
1391            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1392
1393    final @Nullable String mRequiredVerifierPackage;
1394    final @NonNull String mRequiredInstallerPackage;
1395    final @NonNull String mRequiredUninstallerPackage;
1396    final @Nullable String mSetupWizardPackage;
1397    final @Nullable String mStorageManagerPackage;
1398    final @NonNull String mServicesSystemSharedLibraryPackageName;
1399    final @NonNull String mSharedSystemSharedLibraryPackageName;
1400
1401    final boolean mPermissionReviewRequired;
1402
1403    private final PackageUsage mPackageUsage = new PackageUsage();
1404    private final CompilerStats mCompilerStats = new CompilerStats();
1405
1406    class PackageHandler extends Handler {
1407        private boolean mBound = false;
1408        final ArrayList<HandlerParams> mPendingInstalls =
1409            new ArrayList<HandlerParams>();
1410
1411        private boolean connectToService() {
1412            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1413                    " DefaultContainerService");
1414            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1415            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1416            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1417                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1418                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1419                mBound = true;
1420                return true;
1421            }
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1423            return false;
1424        }
1425
1426        private void disconnectService() {
1427            mContainerService = null;
1428            mBound = false;
1429            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1430            mContext.unbindService(mDefContainerConn);
1431            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1432        }
1433
1434        PackageHandler(Looper looper) {
1435            super(looper);
1436        }
1437
1438        public void handleMessage(Message msg) {
1439            try {
1440                doHandleMessage(msg);
1441            } finally {
1442                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1443            }
1444        }
1445
1446        void doHandleMessage(Message msg) {
1447            switch (msg.what) {
1448                case INIT_COPY: {
1449                    HandlerParams params = (HandlerParams) msg.obj;
1450                    int idx = mPendingInstalls.size();
1451                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1452                    // If a bind was already initiated we dont really
1453                    // need to do anything. The pending install
1454                    // will be processed later on.
1455                    if (!mBound) {
1456                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1457                                System.identityHashCode(mHandler));
1458                        // If this is the only one pending we might
1459                        // have to bind to the service again.
1460                        if (!connectToService()) {
1461                            Slog.e(TAG, "Failed to bind to media container service");
1462                            params.serviceError();
1463                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1464                                    System.identityHashCode(mHandler));
1465                            if (params.traceMethod != null) {
1466                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1467                                        params.traceCookie);
1468                            }
1469                            return;
1470                        } else {
1471                            // Once we bind to the service, the first
1472                            // pending request will be processed.
1473                            mPendingInstalls.add(idx, params);
1474                        }
1475                    } else {
1476                        mPendingInstalls.add(idx, params);
1477                        // Already bound to the service. Just make
1478                        // sure we trigger off processing the first request.
1479                        if (idx == 0) {
1480                            mHandler.sendEmptyMessage(MCS_BOUND);
1481                        }
1482                    }
1483                    break;
1484                }
1485                case MCS_BOUND: {
1486                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1487                    if (msg.obj != null) {
1488                        mContainerService = (IMediaContainerService) msg.obj;
1489                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1490                                System.identityHashCode(mHandler));
1491                    }
1492                    if (mContainerService == null) {
1493                        if (!mBound) {
1494                            // Something seriously wrong since we are not bound and we are not
1495                            // waiting for connection. Bail out.
1496                            Slog.e(TAG, "Cannot bind to media container service");
1497                            for (HandlerParams params : mPendingInstalls) {
1498                                // Indicate service bind error
1499                                params.serviceError();
1500                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1501                                        System.identityHashCode(params));
1502                                if (params.traceMethod != null) {
1503                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1504                                            params.traceMethod, params.traceCookie);
1505                                }
1506                                return;
1507                            }
1508                            mPendingInstalls.clear();
1509                        } else {
1510                            Slog.w(TAG, "Waiting to connect to media container service");
1511                        }
1512                    } else if (mPendingInstalls.size() > 0) {
1513                        HandlerParams params = mPendingInstalls.get(0);
1514                        if (params != null) {
1515                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1516                                    System.identityHashCode(params));
1517                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1518                            if (params.startCopy()) {
1519                                // We are done...  look for more work or to
1520                                // go idle.
1521                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1522                                        "Checking for more work or unbind...");
1523                                // Delete pending install
1524                                if (mPendingInstalls.size() > 0) {
1525                                    mPendingInstalls.remove(0);
1526                                }
1527                                if (mPendingInstalls.size() == 0) {
1528                                    if (mBound) {
1529                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1530                                                "Posting delayed MCS_UNBIND");
1531                                        removeMessages(MCS_UNBIND);
1532                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1533                                        // Unbind after a little delay, to avoid
1534                                        // continual thrashing.
1535                                        sendMessageDelayed(ubmsg, 10000);
1536                                    }
1537                                } else {
1538                                    // There are more pending requests in queue.
1539                                    // Just post MCS_BOUND message to trigger processing
1540                                    // of next pending install.
1541                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1542                                            "Posting MCS_BOUND for next work");
1543                                    mHandler.sendEmptyMessage(MCS_BOUND);
1544                                }
1545                            }
1546                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1547                        }
1548                    } else {
1549                        // Should never happen ideally.
1550                        Slog.w(TAG, "Empty queue");
1551                    }
1552                    break;
1553                }
1554                case MCS_RECONNECT: {
1555                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1556                    if (mPendingInstalls.size() > 0) {
1557                        if (mBound) {
1558                            disconnectService();
1559                        }
1560                        if (!connectToService()) {
1561                            Slog.e(TAG, "Failed to bind to media container service");
1562                            for (HandlerParams params : mPendingInstalls) {
1563                                // Indicate service bind error
1564                                params.serviceError();
1565                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1566                                        System.identityHashCode(params));
1567                            }
1568                            mPendingInstalls.clear();
1569                        }
1570                    }
1571                    break;
1572                }
1573                case MCS_UNBIND: {
1574                    // If there is no actual work left, then time to unbind.
1575                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1576
1577                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1578                        if (mBound) {
1579                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1580
1581                            disconnectService();
1582                        }
1583                    } else if (mPendingInstalls.size() > 0) {
1584                        // There are more pending requests in queue.
1585                        // Just post MCS_BOUND message to trigger processing
1586                        // of next pending install.
1587                        mHandler.sendEmptyMessage(MCS_BOUND);
1588                    }
1589
1590                    break;
1591                }
1592                case MCS_GIVE_UP: {
1593                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1594                    HandlerParams params = mPendingInstalls.remove(0);
1595                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1596                            System.identityHashCode(params));
1597                    break;
1598                }
1599                case SEND_PENDING_BROADCAST: {
1600                    String packages[];
1601                    ArrayList<String> components[];
1602                    int size = 0;
1603                    int uids[];
1604                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1605                    synchronized (mPackages) {
1606                        if (mPendingBroadcasts == null) {
1607                            return;
1608                        }
1609                        size = mPendingBroadcasts.size();
1610                        if (size <= 0) {
1611                            // Nothing to be done. Just return
1612                            return;
1613                        }
1614                        packages = new String[size];
1615                        components = new ArrayList[size];
1616                        uids = new int[size];
1617                        int i = 0;  // filling out the above arrays
1618
1619                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1620                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1621                            Iterator<Map.Entry<String, ArrayList<String>>> it
1622                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1623                                            .entrySet().iterator();
1624                            while (it.hasNext() && i < size) {
1625                                Map.Entry<String, ArrayList<String>> ent = it.next();
1626                                packages[i] = ent.getKey();
1627                                components[i] = ent.getValue();
1628                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1629                                uids[i] = (ps != null)
1630                                        ? UserHandle.getUid(packageUserId, ps.appId)
1631                                        : -1;
1632                                i++;
1633                            }
1634                        }
1635                        size = i;
1636                        mPendingBroadcasts.clear();
1637                    }
1638                    // Send broadcasts
1639                    for (int i = 0; i < size; i++) {
1640                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1641                    }
1642                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1643                    break;
1644                }
1645                case START_CLEANING_PACKAGE: {
1646                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1647                    final String packageName = (String)msg.obj;
1648                    final int userId = msg.arg1;
1649                    final boolean andCode = msg.arg2 != 0;
1650                    synchronized (mPackages) {
1651                        if (userId == UserHandle.USER_ALL) {
1652                            int[] users = sUserManager.getUserIds();
1653                            for (int user : users) {
1654                                mSettings.addPackageToCleanLPw(
1655                                        new PackageCleanItem(user, packageName, andCode));
1656                            }
1657                        } else {
1658                            mSettings.addPackageToCleanLPw(
1659                                    new PackageCleanItem(userId, packageName, andCode));
1660                        }
1661                    }
1662                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1663                    startCleaningPackages();
1664                } break;
1665                case POST_INSTALL: {
1666                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1667
1668                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1669                    final boolean didRestore = (msg.arg2 != 0);
1670                    mRunningInstalls.delete(msg.arg1);
1671
1672                    if (data != null) {
1673                        InstallArgs args = data.args;
1674                        PackageInstalledInfo parentRes = data.res;
1675
1676                        final boolean grantPermissions = (args.installFlags
1677                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1678                        final boolean killApp = (args.installFlags
1679                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1680                        final boolean virtualPreload = ((args.installFlags
1681                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1682                        final String[] grantedPermissions = args.installGrantPermissions;
1683
1684                        // Handle the parent package
1685                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1686                                virtualPreload, grantedPermissions, didRestore,
1687                                args.installerPackageName, args.observer);
1688
1689                        // Handle the child packages
1690                        final int childCount = (parentRes.addedChildPackages != null)
1691                                ? parentRes.addedChildPackages.size() : 0;
1692                        for (int i = 0; i < childCount; i++) {
1693                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1694                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1695                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1696                                    args.installerPackageName, args.observer);
1697                        }
1698
1699                        // Log tracing if needed
1700                        if (args.traceMethod != null) {
1701                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1702                                    args.traceCookie);
1703                        }
1704                    } else {
1705                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1706                    }
1707
1708                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1709                } break;
1710                case UPDATED_MEDIA_STATUS: {
1711                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1712                    boolean reportStatus = msg.arg1 == 1;
1713                    boolean doGc = msg.arg2 == 1;
1714                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1715                    if (doGc) {
1716                        // Force a gc to clear up stale containers.
1717                        Runtime.getRuntime().gc();
1718                    }
1719                    if (msg.obj != null) {
1720                        @SuppressWarnings("unchecked")
1721                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1722                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1723                        // Unload containers
1724                        unloadAllContainers(args);
1725                    }
1726                    if (reportStatus) {
1727                        try {
1728                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1729                                    "Invoking StorageManagerService call back");
1730                            PackageHelper.getStorageManager().finishMediaUpdate();
1731                        } catch (RemoteException e) {
1732                            Log.e(TAG, "StorageManagerService not running?");
1733                        }
1734                    }
1735                } break;
1736                case WRITE_SETTINGS: {
1737                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1738                    synchronized (mPackages) {
1739                        removeMessages(WRITE_SETTINGS);
1740                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1741                        mSettings.writeLPr();
1742                        mDirtyUsers.clear();
1743                    }
1744                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1745                } break;
1746                case WRITE_PACKAGE_RESTRICTIONS: {
1747                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1748                    synchronized (mPackages) {
1749                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1750                        for (int userId : mDirtyUsers) {
1751                            mSettings.writePackageRestrictionsLPr(userId);
1752                        }
1753                        mDirtyUsers.clear();
1754                    }
1755                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1756                } break;
1757                case WRITE_PACKAGE_LIST: {
1758                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1759                    synchronized (mPackages) {
1760                        removeMessages(WRITE_PACKAGE_LIST);
1761                        mSettings.writePackageListLPr(msg.arg1);
1762                    }
1763                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1764                } break;
1765                case CHECK_PENDING_VERIFICATION: {
1766                    final int verificationId = msg.arg1;
1767                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1768
1769                    if ((state != null) && !state.timeoutExtended()) {
1770                        final InstallArgs args = state.getInstallArgs();
1771                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1772
1773                        Slog.i(TAG, "Verification timed out for " + originUri);
1774                        mPendingVerification.remove(verificationId);
1775
1776                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1777
1778                        final UserHandle user = args.getUser();
1779                        if (getDefaultVerificationResponse(user)
1780                                == PackageManager.VERIFICATION_ALLOW) {
1781                            Slog.i(TAG, "Continuing with installation of " + originUri);
1782                            state.setVerifierResponse(Binder.getCallingUid(),
1783                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1784                            broadcastPackageVerified(verificationId, originUri,
1785                                    PackageManager.VERIFICATION_ALLOW, user);
1786                            try {
1787                                ret = args.copyApk(mContainerService, true);
1788                            } catch (RemoteException e) {
1789                                Slog.e(TAG, "Could not contact the ContainerService");
1790                            }
1791                        } else {
1792                            broadcastPackageVerified(verificationId, originUri,
1793                                    PackageManager.VERIFICATION_REJECT, user);
1794                        }
1795
1796                        Trace.asyncTraceEnd(
1797                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1798
1799                        processPendingInstall(args, ret);
1800                        mHandler.sendEmptyMessage(MCS_UNBIND);
1801                    }
1802                    break;
1803                }
1804                case PACKAGE_VERIFIED: {
1805                    final int verificationId = msg.arg1;
1806
1807                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1808                    if (state == null) {
1809                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1810                        break;
1811                    }
1812
1813                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1814
1815                    state.setVerifierResponse(response.callerUid, response.code);
1816
1817                    if (state.isVerificationComplete()) {
1818                        mPendingVerification.remove(verificationId);
1819
1820                        final InstallArgs args = state.getInstallArgs();
1821                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1822
1823                        int ret;
1824                        if (state.isInstallAllowed()) {
1825                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1826                            broadcastPackageVerified(verificationId, originUri,
1827                                    response.code, state.getInstallArgs().getUser());
1828                            try {
1829                                ret = args.copyApk(mContainerService, true);
1830                            } catch (RemoteException e) {
1831                                Slog.e(TAG, "Could not contact the ContainerService");
1832                            }
1833                        } else {
1834                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1835                        }
1836
1837                        Trace.asyncTraceEnd(
1838                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1839
1840                        processPendingInstall(args, ret);
1841                        mHandler.sendEmptyMessage(MCS_UNBIND);
1842                    }
1843
1844                    break;
1845                }
1846                case START_INTENT_FILTER_VERIFICATIONS: {
1847                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1848                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1849                            params.replacing, params.pkg);
1850                    break;
1851                }
1852                case INTENT_FILTER_VERIFIED: {
1853                    final int verificationId = msg.arg1;
1854
1855                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1856                            verificationId);
1857                    if (state == null) {
1858                        Slog.w(TAG, "Invalid IntentFilter verification token "
1859                                + verificationId + " received");
1860                        break;
1861                    }
1862
1863                    final int userId = state.getUserId();
1864
1865                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1866                            "Processing IntentFilter verification with token:"
1867                            + verificationId + " and userId:" + userId);
1868
1869                    final IntentFilterVerificationResponse response =
1870                            (IntentFilterVerificationResponse) msg.obj;
1871
1872                    state.setVerifierResponse(response.callerUid, response.code);
1873
1874                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1875                            "IntentFilter verification with token:" + verificationId
1876                            + " and userId:" + userId
1877                            + " is settings verifier response with response code:"
1878                            + response.code);
1879
1880                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1881                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1882                                + response.getFailedDomainsString());
1883                    }
1884
1885                    if (state.isVerificationComplete()) {
1886                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1887                    } else {
1888                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1889                                "IntentFilter verification with token:" + verificationId
1890                                + " was not said to be complete");
1891                    }
1892
1893                    break;
1894                }
1895                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1896                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1897                            mInstantAppResolverConnection,
1898                            (InstantAppRequest) msg.obj,
1899                            mInstantAppInstallerActivity,
1900                            mHandler);
1901                }
1902            }
1903        }
1904    }
1905
1906    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1907            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1908            boolean launchedForRestore, String installerPackage,
1909            IPackageInstallObserver2 installObserver) {
1910        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1911            // Send the removed broadcasts
1912            if (res.removedInfo != null) {
1913                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1914            }
1915
1916            // Now that we successfully installed the package, grant runtime
1917            // permissions if requested before broadcasting the install. Also
1918            // for legacy apps in permission review mode we clear the permission
1919            // review flag which is used to emulate runtime permissions for
1920            // legacy apps.
1921            if (grantPermissions) {
1922                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1923            }
1924
1925            final boolean update = res.removedInfo != null
1926                    && res.removedInfo.removedPackage != null;
1927            final String origInstallerPackageName = res.removedInfo != null
1928                    ? res.removedInfo.installerPackageName : null;
1929
1930            // If this is the first time we have child packages for a disabled privileged
1931            // app that had no children, we grant requested runtime permissions to the new
1932            // children if the parent on the system image had them already granted.
1933            if (res.pkg.parentPackage != null) {
1934                synchronized (mPackages) {
1935                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1936                }
1937            }
1938
1939            synchronized (mPackages) {
1940                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1941            }
1942
1943            final String packageName = res.pkg.applicationInfo.packageName;
1944
1945            // Determine the set of users who are adding this package for
1946            // the first time vs. those who are seeing an update.
1947            int[] firstUsers = EMPTY_INT_ARRAY;
1948            int[] updateUsers = EMPTY_INT_ARRAY;
1949            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1950            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1951            for (int newUser : res.newUsers) {
1952                if (ps.getInstantApp(newUser)) {
1953                    continue;
1954                }
1955                if (allNewUsers) {
1956                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1957                    continue;
1958                }
1959                boolean isNew = true;
1960                for (int origUser : res.origUsers) {
1961                    if (origUser == newUser) {
1962                        isNew = false;
1963                        break;
1964                    }
1965                }
1966                if (isNew) {
1967                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1968                } else {
1969                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1970                }
1971            }
1972
1973            // Send installed broadcasts if the package is not a static shared lib.
1974            if (res.pkg.staticSharedLibName == null) {
1975                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1976
1977                // Send added for users that see the package for the first time
1978                // sendPackageAddedForNewUsers also deals with system apps
1979                int appId = UserHandle.getAppId(res.uid);
1980                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1981                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1982                        virtualPreload /*startReceiver*/, appId, firstUsers);
1983
1984                // Send added for users that don't see the package for the first time
1985                Bundle extras = new Bundle(1);
1986                extras.putInt(Intent.EXTRA_UID, res.uid);
1987                if (update) {
1988                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1989                }
1990                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1991                        extras, 0 /*flags*/,
1992                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1993                if (origInstallerPackageName != null) {
1994                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1995                            extras, 0 /*flags*/,
1996                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1997                }
1998
1999                // Send replaced for users that don't see the package for the first time
2000                if (update) {
2001                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2002                            packageName, extras, 0 /*flags*/,
2003                            null /*targetPackage*/, null /*finishedReceiver*/,
2004                            updateUsers);
2005                    if (origInstallerPackageName != null) {
2006                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2007                                extras, 0 /*flags*/,
2008                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
2009                    }
2010                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2011                            null /*package*/, null /*extras*/, 0 /*flags*/,
2012                            packageName /*targetPackage*/,
2013                            null /*finishedReceiver*/, updateUsers);
2014                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2015                    // First-install and we did a restore, so we're responsible for the
2016                    // first-launch broadcast.
2017                    if (DEBUG_BACKUP) {
2018                        Slog.i(TAG, "Post-restore of " + packageName
2019                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2020                    }
2021                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2022                }
2023
2024                // Send broadcast package appeared if forward locked/external for all users
2025                // treat asec-hosted packages like removable media on upgrade
2026                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2027                    if (DEBUG_INSTALL) {
2028                        Slog.i(TAG, "upgrading pkg " + res.pkg
2029                                + " is ASEC-hosted -> AVAILABLE");
2030                    }
2031                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2032                    ArrayList<String> pkgList = new ArrayList<>(1);
2033                    pkgList.add(packageName);
2034                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2035                }
2036            }
2037
2038            // Work that needs to happen on first install within each user
2039            if (firstUsers != null && firstUsers.length > 0) {
2040                synchronized (mPackages) {
2041                    for (int userId : firstUsers) {
2042                        // If this app is a browser and it's newly-installed for some
2043                        // users, clear any default-browser state in those users. The
2044                        // app's nature doesn't depend on the user, so we can just check
2045                        // its browser nature in any user and generalize.
2046                        if (packageIsBrowser(packageName, userId)) {
2047                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2048                        }
2049
2050                        // We may also need to apply pending (restored) runtime
2051                        // permission grants within these users.
2052                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2053                    }
2054                }
2055            }
2056
2057            // Log current value of "unknown sources" setting
2058            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2059                    getUnknownSourcesSettings());
2060
2061            // Remove the replaced package's older resources safely now
2062            // We delete after a gc for applications  on sdcard.
2063            if (res.removedInfo != null && res.removedInfo.args != null) {
2064                Runtime.getRuntime().gc();
2065                synchronized (mInstallLock) {
2066                    res.removedInfo.args.doPostDeleteLI(true);
2067                }
2068            } else {
2069                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2070                // and not block here.
2071                VMRuntime.getRuntime().requestConcurrentGC();
2072            }
2073
2074            // Notify DexManager that the package was installed for new users.
2075            // The updated users should already be indexed and the package code paths
2076            // should not change.
2077            // Don't notify the manager for ephemeral apps as they are not expected to
2078            // survive long enough to benefit of background optimizations.
2079            for (int userId : firstUsers) {
2080                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2081                // There's a race currently where some install events may interleave with an uninstall.
2082                // This can lead to package info being null (b/36642664).
2083                if (info != null) {
2084                    mDexManager.notifyPackageInstalled(info, userId);
2085                }
2086            }
2087        }
2088
2089        // If someone is watching installs - notify them
2090        if (installObserver != null) {
2091            try {
2092                Bundle extras = extrasForInstallResult(res);
2093                installObserver.onPackageInstalled(res.name, res.returnCode,
2094                        res.returnMsg, extras);
2095            } catch (RemoteException e) {
2096                Slog.i(TAG, "Observer no longer exists.");
2097            }
2098        }
2099    }
2100
2101    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2102            PackageParser.Package pkg) {
2103        if (pkg.parentPackage == null) {
2104            return;
2105        }
2106        if (pkg.requestedPermissions == null) {
2107            return;
2108        }
2109        final PackageSetting disabledSysParentPs = mSettings
2110                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2111        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2112                || !disabledSysParentPs.isPrivileged()
2113                || (disabledSysParentPs.childPackageNames != null
2114                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2115            return;
2116        }
2117        final int[] allUserIds = sUserManager.getUserIds();
2118        final int permCount = pkg.requestedPermissions.size();
2119        for (int i = 0; i < permCount; i++) {
2120            String permission = pkg.requestedPermissions.get(i);
2121            BasePermission bp = mSettings.mPermissions.get(permission);
2122            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2123                continue;
2124            }
2125            for (int userId : allUserIds) {
2126                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2127                        permission, userId)) {
2128                    grantRuntimePermission(pkg.packageName, permission, userId);
2129                }
2130            }
2131        }
2132    }
2133
2134    private StorageEventListener mStorageListener = new StorageEventListener() {
2135        @Override
2136        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2137            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2138                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2139                    final String volumeUuid = vol.getFsUuid();
2140
2141                    // Clean up any users or apps that were removed or recreated
2142                    // while this volume was missing
2143                    sUserManager.reconcileUsers(volumeUuid);
2144                    reconcileApps(volumeUuid);
2145
2146                    // Clean up any install sessions that expired or were
2147                    // cancelled while this volume was missing
2148                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2149
2150                    loadPrivatePackages(vol);
2151
2152                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2153                    unloadPrivatePackages(vol);
2154                }
2155            }
2156
2157            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2158                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2159                    updateExternalMediaStatus(true, false);
2160                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2161                    updateExternalMediaStatus(false, false);
2162                }
2163            }
2164        }
2165
2166        @Override
2167        public void onVolumeForgotten(String fsUuid) {
2168            if (TextUtils.isEmpty(fsUuid)) {
2169                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2170                return;
2171            }
2172
2173            // Remove any apps installed on the forgotten volume
2174            synchronized (mPackages) {
2175                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2176                for (PackageSetting ps : packages) {
2177                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2178                    deletePackageVersioned(new VersionedPackage(ps.name,
2179                            PackageManager.VERSION_CODE_HIGHEST),
2180                            new LegacyPackageDeleteObserver(null).getBinder(),
2181                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2182                    // Try very hard to release any references to this package
2183                    // so we don't risk the system server being killed due to
2184                    // open FDs
2185                    AttributeCache.instance().removePackage(ps.name);
2186                }
2187
2188                mSettings.onVolumeForgotten(fsUuid);
2189                mSettings.writeLPr();
2190            }
2191        }
2192    };
2193
2194    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2195            String[] grantedPermissions) {
2196        for (int userId : userIds) {
2197            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2198        }
2199    }
2200
2201    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2202            String[] grantedPermissions) {
2203        PackageSetting ps = (PackageSetting) pkg.mExtras;
2204        if (ps == null) {
2205            return;
2206        }
2207
2208        PermissionsState permissionsState = ps.getPermissionsState();
2209
2210        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2211                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2212
2213        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2214                >= Build.VERSION_CODES.M;
2215
2216        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2217
2218        for (String permission : pkg.requestedPermissions) {
2219            final BasePermission bp;
2220            synchronized (mPackages) {
2221                bp = mSettings.mPermissions.get(permission);
2222            }
2223            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2224                    && (!instantApp || bp.isInstant())
2225                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2226                    && (grantedPermissions == null
2227                           || ArrayUtils.contains(grantedPermissions, permission))) {
2228                final int flags = permissionsState.getPermissionFlags(permission, userId);
2229                if (supportsRuntimePermissions) {
2230                    // Installer cannot change immutable permissions.
2231                    if ((flags & immutableFlags) == 0) {
2232                        grantRuntimePermission(pkg.packageName, permission, userId);
2233                    }
2234                } else if (mPermissionReviewRequired) {
2235                    // In permission review mode we clear the review flag when we
2236                    // are asked to install the app with all permissions granted.
2237                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2238                        updatePermissionFlags(permission, pkg.packageName,
2239                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2240                    }
2241                }
2242            }
2243        }
2244    }
2245
2246    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2247        Bundle extras = null;
2248        switch (res.returnCode) {
2249            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2250                extras = new Bundle();
2251                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2252                        res.origPermission);
2253                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2254                        res.origPackage);
2255                break;
2256            }
2257            case PackageManager.INSTALL_SUCCEEDED: {
2258                extras = new Bundle();
2259                extras.putBoolean(Intent.EXTRA_REPLACING,
2260                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2261                break;
2262            }
2263        }
2264        return extras;
2265    }
2266
2267    void scheduleWriteSettingsLocked() {
2268        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2269            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2270        }
2271    }
2272
2273    void scheduleWritePackageListLocked(int userId) {
2274        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2275            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2276            msg.arg1 = userId;
2277            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2278        }
2279    }
2280
2281    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2282        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2283        scheduleWritePackageRestrictionsLocked(userId);
2284    }
2285
2286    void scheduleWritePackageRestrictionsLocked(int userId) {
2287        final int[] userIds = (userId == UserHandle.USER_ALL)
2288                ? sUserManager.getUserIds() : new int[]{userId};
2289        for (int nextUserId : userIds) {
2290            if (!sUserManager.exists(nextUserId)) return;
2291            mDirtyUsers.add(nextUserId);
2292            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2293                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2294            }
2295        }
2296    }
2297
2298    public static PackageManagerService main(Context context, Installer installer,
2299            boolean factoryTest, boolean onlyCore) {
2300        // Self-check for initial settings.
2301        PackageManagerServiceCompilerMapping.checkProperties();
2302
2303        PackageManagerService m = new PackageManagerService(context, installer,
2304                factoryTest, onlyCore);
2305        m.enableSystemUserPackages();
2306        ServiceManager.addService("package", m);
2307        return m;
2308    }
2309
2310    private void enableSystemUserPackages() {
2311        if (!UserManager.isSplitSystemUser()) {
2312            return;
2313        }
2314        // For system user, enable apps based on the following conditions:
2315        // - app is whitelisted or belong to one of these groups:
2316        //   -- system app which has no launcher icons
2317        //   -- system app which has INTERACT_ACROSS_USERS permission
2318        //   -- system IME app
2319        // - app is not in the blacklist
2320        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2321        Set<String> enableApps = new ArraySet<>();
2322        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2323                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2324                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2325        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2326        enableApps.addAll(wlApps);
2327        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2328                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2329        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2330        enableApps.removeAll(blApps);
2331        Log.i(TAG, "Applications installed for system user: " + enableApps);
2332        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2333                UserHandle.SYSTEM);
2334        final int allAppsSize = allAps.size();
2335        synchronized (mPackages) {
2336            for (int i = 0; i < allAppsSize; i++) {
2337                String pName = allAps.get(i);
2338                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2339                // Should not happen, but we shouldn't be failing if it does
2340                if (pkgSetting == null) {
2341                    continue;
2342                }
2343                boolean install = enableApps.contains(pName);
2344                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2345                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2346                            + " for system user");
2347                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2348                }
2349            }
2350            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2351        }
2352    }
2353
2354    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2355        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2356                Context.DISPLAY_SERVICE);
2357        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2358    }
2359
2360    /**
2361     * Requests that files preopted on a secondary system partition be copied to the data partition
2362     * if possible.  Note that the actual copying of the files is accomplished by init for security
2363     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2364     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2365     */
2366    private static void requestCopyPreoptedFiles() {
2367        final int WAIT_TIME_MS = 100;
2368        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2369        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2370            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2371            // We will wait for up to 100 seconds.
2372            final long timeStart = SystemClock.uptimeMillis();
2373            final long timeEnd = timeStart + 100 * 1000;
2374            long timeNow = timeStart;
2375            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2376                try {
2377                    Thread.sleep(WAIT_TIME_MS);
2378                } catch (InterruptedException e) {
2379                    // Do nothing
2380                }
2381                timeNow = SystemClock.uptimeMillis();
2382                if (timeNow > timeEnd) {
2383                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2384                    Slog.wtf(TAG, "cppreopt did not finish!");
2385                    break;
2386                }
2387            }
2388
2389            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2390        }
2391    }
2392
2393    public PackageManagerService(Context context, Installer installer,
2394            boolean factoryTest, boolean onlyCore) {
2395        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2396        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2397        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2398                SystemClock.uptimeMillis());
2399
2400        if (mSdkVersion <= 0) {
2401            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2402        }
2403
2404        mContext = context;
2405
2406        mPermissionReviewRequired = context.getResources().getBoolean(
2407                R.bool.config_permissionReviewRequired);
2408
2409        mFactoryTest = factoryTest;
2410        mOnlyCore = onlyCore;
2411        mMetrics = new DisplayMetrics();
2412        mSettings = new Settings(mPackages);
2413        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2414                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2415        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2416                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2417        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2418                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2419        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2420                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2421        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2422                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2423        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2424                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2425
2426        String separateProcesses = SystemProperties.get("debug.separate_processes");
2427        if (separateProcesses != null && separateProcesses.length() > 0) {
2428            if ("*".equals(separateProcesses)) {
2429                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2430                mSeparateProcesses = null;
2431                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2432            } else {
2433                mDefParseFlags = 0;
2434                mSeparateProcesses = separateProcesses.split(",");
2435                Slog.w(TAG, "Running with debug.separate_processes: "
2436                        + separateProcesses);
2437            }
2438        } else {
2439            mDefParseFlags = 0;
2440            mSeparateProcesses = null;
2441        }
2442
2443        mInstaller = installer;
2444        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2445                "*dexopt*");
2446        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2447        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2448
2449        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2450                FgThread.get().getLooper());
2451
2452        getDefaultDisplayMetrics(context, mMetrics);
2453
2454        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2455        SystemConfig systemConfig = SystemConfig.getInstance();
2456        mGlobalGids = systemConfig.getGlobalGids();
2457        mSystemPermissions = systemConfig.getSystemPermissions();
2458        mAvailableFeatures = systemConfig.getAvailableFeatures();
2459        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2460
2461        mProtectedPackages = new ProtectedPackages(mContext);
2462
2463        synchronized (mInstallLock) {
2464        // writer
2465        synchronized (mPackages) {
2466            mHandlerThread = new ServiceThread(TAG,
2467                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2468            mHandlerThread.start();
2469            mHandler = new PackageHandler(mHandlerThread.getLooper());
2470            mProcessLoggingHandler = new ProcessLoggingHandler();
2471            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2472
2473            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2474            mInstantAppRegistry = new InstantAppRegistry(this);
2475
2476            File dataDir = Environment.getDataDirectory();
2477            mAppInstallDir = new File(dataDir, "app");
2478            mAppLib32InstallDir = new File(dataDir, "app-lib");
2479            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2480            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2481            sUserManager = new UserManagerService(context, this,
2482                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2483
2484            // Propagate permission configuration in to package manager.
2485            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2486                    = systemConfig.getPermissions();
2487            for (int i=0; i<permConfig.size(); i++) {
2488                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2489                BasePermission bp = mSettings.mPermissions.get(perm.name);
2490                if (bp == null) {
2491                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2492                    mSettings.mPermissions.put(perm.name, bp);
2493                }
2494                if (perm.gids != null) {
2495                    bp.setGids(perm.gids, perm.perUser);
2496                }
2497            }
2498
2499            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2500            final int builtInLibCount = libConfig.size();
2501            for (int i = 0; i < builtInLibCount; i++) {
2502                String name = libConfig.keyAt(i);
2503                String path = libConfig.valueAt(i);
2504                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2505                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2506            }
2507
2508            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2509
2510            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2511            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2512            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2513
2514            // Clean up orphaned packages for which the code path doesn't exist
2515            // and they are an update to a system app - caused by bug/32321269
2516            final int packageSettingCount = mSettings.mPackages.size();
2517            for (int i = packageSettingCount - 1; i >= 0; i--) {
2518                PackageSetting ps = mSettings.mPackages.valueAt(i);
2519                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2520                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2521                    mSettings.mPackages.removeAt(i);
2522                    mSettings.enableSystemPackageLPw(ps.name);
2523                }
2524            }
2525
2526            if (mFirstBoot) {
2527                requestCopyPreoptedFiles();
2528            }
2529
2530            String customResolverActivity = Resources.getSystem().getString(
2531                    R.string.config_customResolverActivity);
2532            if (TextUtils.isEmpty(customResolverActivity)) {
2533                customResolverActivity = null;
2534            } else {
2535                mCustomResolverComponentName = ComponentName.unflattenFromString(
2536                        customResolverActivity);
2537            }
2538
2539            long startTime = SystemClock.uptimeMillis();
2540
2541            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2542                    startTime);
2543
2544            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2545            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2546
2547            if (bootClassPath == null) {
2548                Slog.w(TAG, "No BOOTCLASSPATH found!");
2549            }
2550
2551            if (systemServerClassPath == null) {
2552                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2553            }
2554
2555            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2556
2557            final VersionInfo ver = mSettings.getInternalVersion();
2558            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2559            if (mIsUpgrade) {
2560                logCriticalInfo(Log.INFO,
2561                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2562            }
2563
2564            // when upgrading from pre-M, promote system app permissions from install to runtime
2565            mPromoteSystemApps =
2566                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2567
2568            // When upgrading from pre-N, we need to handle package extraction like first boot,
2569            // as there is no profiling data available.
2570            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2571
2572            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2573
2574            // save off the names of pre-existing system packages prior to scanning; we don't
2575            // want to automatically grant runtime permissions for new system apps
2576            if (mPromoteSystemApps) {
2577                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2578                while (pkgSettingIter.hasNext()) {
2579                    PackageSetting ps = pkgSettingIter.next();
2580                    if (isSystemApp(ps)) {
2581                        mExistingSystemPackages.add(ps.name);
2582                    }
2583                }
2584            }
2585
2586            mCacheDir = preparePackageParserCache(mIsUpgrade);
2587
2588            // Set flag to monitor and not change apk file paths when
2589            // scanning install directories.
2590            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2591
2592            if (mIsUpgrade || mFirstBoot) {
2593                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2594            }
2595
2596            // Collect vendor overlay packages. (Do this before scanning any apps.)
2597            // For security and version matching reason, only consider
2598            // overlay packages if they reside in the right directory.
2599            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2600                    | PackageParser.PARSE_IS_SYSTEM
2601                    | PackageParser.PARSE_IS_SYSTEM_DIR
2602                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2603
2604            mParallelPackageParserCallback.findStaticOverlayPackages();
2605
2606            // Find base frameworks (resource packages without code).
2607            scanDirTracedLI(frameworkDir, mDefParseFlags
2608                    | PackageParser.PARSE_IS_SYSTEM
2609                    | PackageParser.PARSE_IS_SYSTEM_DIR
2610                    | PackageParser.PARSE_IS_PRIVILEGED,
2611                    scanFlags | SCAN_NO_DEX, 0);
2612
2613            // Collected privileged system packages.
2614            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2615            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2616                    | PackageParser.PARSE_IS_SYSTEM
2617                    | PackageParser.PARSE_IS_SYSTEM_DIR
2618                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2619
2620            // Collect ordinary system packages.
2621            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2622            scanDirTracedLI(systemAppDir, mDefParseFlags
2623                    | PackageParser.PARSE_IS_SYSTEM
2624                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2625
2626            // Collect all vendor packages.
2627            File vendorAppDir = new File("/vendor/app");
2628            try {
2629                vendorAppDir = vendorAppDir.getCanonicalFile();
2630            } catch (IOException e) {
2631                // failed to look up canonical path, continue with original one
2632            }
2633            scanDirTracedLI(vendorAppDir, mDefParseFlags
2634                    | PackageParser.PARSE_IS_SYSTEM
2635                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2636
2637            // Collect all OEM packages.
2638            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2639            scanDirTracedLI(oemAppDir, mDefParseFlags
2640                    | PackageParser.PARSE_IS_SYSTEM
2641                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2642
2643            // Prune any system packages that no longer exist.
2644            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2645            // Stub packages must either be replaced with full versions in the /data
2646            // partition or be disabled.
2647            final List<String> stubSystemApps = new ArrayList<>();
2648            if (!mOnlyCore) {
2649                // do this first before mucking with mPackages for the "expecting better" case
2650                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2651                while (pkgIterator.hasNext()) {
2652                    final PackageParser.Package pkg = pkgIterator.next();
2653                    if (pkg.isStub) {
2654                        stubSystemApps.add(pkg.packageName);
2655                    }
2656                }
2657
2658                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2659                while (psit.hasNext()) {
2660                    PackageSetting ps = psit.next();
2661
2662                    /*
2663                     * If this is not a system app, it can't be a
2664                     * disable system app.
2665                     */
2666                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2667                        continue;
2668                    }
2669
2670                    /*
2671                     * If the package is scanned, it's not erased.
2672                     */
2673                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2674                    if (scannedPkg != null) {
2675                        /*
2676                         * If the system app is both scanned and in the
2677                         * disabled packages list, then it must have been
2678                         * added via OTA. Remove it from the currently
2679                         * scanned package so the previously user-installed
2680                         * application can be scanned.
2681                         */
2682                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2683                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2684                                    + ps.name + "; removing system app.  Last known codePath="
2685                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2686                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2687                                    + scannedPkg.mVersionCode);
2688                            removePackageLI(scannedPkg, true);
2689                            mExpectingBetter.put(ps.name, ps.codePath);
2690                        }
2691
2692                        continue;
2693                    }
2694
2695                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2696                        psit.remove();
2697                        logCriticalInfo(Log.WARN, "System package " + ps.name
2698                                + " no longer exists; it's data will be wiped");
2699                        // Actual deletion of code and data will be handled by later
2700                        // reconciliation step
2701                    } else {
2702                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2703                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2704                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2705                        }
2706                    }
2707                }
2708            }
2709
2710            //look for any incomplete package installations
2711            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2712            for (int i = 0; i < deletePkgsList.size(); i++) {
2713                // Actual deletion of code and data will be handled by later
2714                // reconciliation step
2715                final String packageName = deletePkgsList.get(i).name;
2716                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2717                synchronized (mPackages) {
2718                    mSettings.removePackageLPw(packageName);
2719                }
2720            }
2721
2722            //delete tmp files
2723            deleteTempPackageFiles();
2724
2725            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2726
2727            // Remove any shared userIDs that have no associated packages
2728            mSettings.pruneSharedUsersLPw();
2729            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2730            final int systemPackagesCount = mPackages.size();
2731            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2732                    + " ms, packageCount: " + systemPackagesCount
2733                    + " , timePerPackage: "
2734                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2735                    + " , cached: " + cachedSystemApps);
2736            if (mIsUpgrade && systemPackagesCount > 0) {
2737                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2738                        ((int) systemScanTime) / systemPackagesCount);
2739            }
2740            if (!mOnlyCore) {
2741                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2742                        SystemClock.uptimeMillis());
2743                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2744
2745                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2746                        | PackageParser.PARSE_FORWARD_LOCK,
2747                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2748
2749                // Remove disable package settings for updated system apps that were
2750                // removed via an OTA. If the update is no longer present, remove the
2751                // app completely. Otherwise, revoke their system privileges.
2752                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2753                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2754                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2755
2756                    final String msg;
2757                    if (deletedPkg == null) {
2758                        // should have found an update, but, we didn't; remove everything
2759                        msg = "Updated system package " + deletedAppName
2760                                + " no longer exists; removing its data";
2761                        // Actual deletion of code and data will be handled by later
2762                        // reconciliation step
2763                    } else {
2764                        // found an update; revoke system privileges
2765                        msg = "Updated system package + " + deletedAppName
2766                                + " no longer exists; revoking system privileges";
2767
2768                        // Don't do anything if a stub is removed from the system image. If
2769                        // we were to remove the uncompressed version from the /data partition,
2770                        // this is where it'd be done.
2771
2772                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2773                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2774                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2775                    }
2776                    logCriticalInfo(Log.WARN, msg);
2777                }
2778
2779                /*
2780                 * Make sure all system apps that we expected to appear on
2781                 * the userdata partition actually showed up. If they never
2782                 * appeared, crawl back and revive the system version.
2783                 */
2784                for (int i = 0; i < mExpectingBetter.size(); i++) {
2785                    final String packageName = mExpectingBetter.keyAt(i);
2786                    if (!mPackages.containsKey(packageName)) {
2787                        final File scanFile = mExpectingBetter.valueAt(i);
2788
2789                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2790                                + " but never showed up; reverting to system");
2791
2792                        int reparseFlags = mDefParseFlags;
2793                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2794                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2795                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2796                                    | PackageParser.PARSE_IS_PRIVILEGED;
2797                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2798                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2799                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2800                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2801                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2802                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2803                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2804                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2805                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2806                        } else {
2807                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2808                            continue;
2809                        }
2810
2811                        mSettings.enableSystemPackageLPw(packageName);
2812
2813                        try {
2814                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2815                        } catch (PackageManagerException e) {
2816                            Slog.e(TAG, "Failed to parse original system package: "
2817                                    + e.getMessage());
2818                        }
2819                    }
2820                }
2821
2822                // Uncompress and install any stubbed system applications.
2823                // This must be done last to ensure all stubs are replaced or disabled.
2824                decompressSystemApplications(stubSystemApps, scanFlags);
2825
2826                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2827                                - cachedSystemApps;
2828
2829                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2830                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2831                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2832                        + " ms, packageCount: " + dataPackagesCount
2833                        + " , timePerPackage: "
2834                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2835                        + " , cached: " + cachedNonSystemApps);
2836                if (mIsUpgrade && dataPackagesCount > 0) {
2837                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2838                            ((int) dataScanTime) / dataPackagesCount);
2839                }
2840            }
2841            mExpectingBetter.clear();
2842
2843            // Resolve the storage manager.
2844            mStorageManagerPackage = getStorageManagerPackageName();
2845
2846            // Resolve protected action filters. Only the setup wizard is allowed to
2847            // have a high priority filter for these actions.
2848            mSetupWizardPackage = getSetupWizardPackageName();
2849            if (mProtectedFilters.size() > 0) {
2850                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2851                    Slog.i(TAG, "No setup wizard;"
2852                        + " All protected intents capped to priority 0");
2853                }
2854                for (ActivityIntentInfo filter : mProtectedFilters) {
2855                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2856                        if (DEBUG_FILTERS) {
2857                            Slog.i(TAG, "Found setup wizard;"
2858                                + " allow priority " + filter.getPriority() + ";"
2859                                + " package: " + filter.activity.info.packageName
2860                                + " activity: " + filter.activity.className
2861                                + " priority: " + filter.getPriority());
2862                        }
2863                        // skip setup wizard; allow it to keep the high priority filter
2864                        continue;
2865                    }
2866                    if (DEBUG_FILTERS) {
2867                        Slog.i(TAG, "Protected action; cap priority to 0;"
2868                                + " package: " + filter.activity.info.packageName
2869                                + " activity: " + filter.activity.className
2870                                + " origPrio: " + filter.getPriority());
2871                    }
2872                    filter.setPriority(0);
2873                }
2874            }
2875            mDeferProtectedFilters = false;
2876            mProtectedFilters.clear();
2877
2878            // Now that we know all of the shared libraries, update all clients to have
2879            // the correct library paths.
2880            updateAllSharedLibrariesLPw(null);
2881
2882            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2883                // NOTE: We ignore potential failures here during a system scan (like
2884                // the rest of the commands above) because there's precious little we
2885                // can do about it. A settings error is reported, though.
2886                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2887            }
2888
2889            // Now that we know all the packages we are keeping,
2890            // read and update their last usage times.
2891            mPackageUsage.read(mPackages);
2892            mCompilerStats.read();
2893
2894            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2895                    SystemClock.uptimeMillis());
2896            Slog.i(TAG, "Time to scan packages: "
2897                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2898                    + " seconds");
2899
2900            // If the platform SDK has changed since the last time we booted,
2901            // we need to re-grant app permission to catch any new ones that
2902            // appear.  This is really a hack, and means that apps can in some
2903            // cases get permissions that the user didn't initially explicitly
2904            // allow...  it would be nice to have some better way to handle
2905            // this situation.
2906            int updateFlags = UPDATE_PERMISSIONS_ALL;
2907            if (ver.sdkVersion != mSdkVersion) {
2908                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2909                        + mSdkVersion + "; regranting permissions for internal storage");
2910                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2911            }
2912            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2913            ver.sdkVersion = mSdkVersion;
2914
2915            // If this is the first boot or an update from pre-M, and it is a normal
2916            // boot, then we need to initialize the default preferred apps across
2917            // all defined users.
2918            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2919                for (UserInfo user : sUserManager.getUsers(true)) {
2920                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2921                    applyFactoryDefaultBrowserLPw(user.id);
2922                    primeDomainVerificationsLPw(user.id);
2923                }
2924            }
2925
2926            // Prepare storage for system user really early during boot,
2927            // since core system apps like SettingsProvider and SystemUI
2928            // can't wait for user to start
2929            final int storageFlags;
2930            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2931                storageFlags = StorageManager.FLAG_STORAGE_DE;
2932            } else {
2933                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2934            }
2935            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2936                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2937                    true /* onlyCoreApps */);
2938            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2939                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2940                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2941                traceLog.traceBegin("AppDataFixup");
2942                try {
2943                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2944                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2945                } catch (InstallerException e) {
2946                    Slog.w(TAG, "Trouble fixing GIDs", e);
2947                }
2948                traceLog.traceEnd();
2949
2950                traceLog.traceBegin("AppDataPrepare");
2951                if (deferPackages == null || deferPackages.isEmpty()) {
2952                    return;
2953                }
2954                int count = 0;
2955                for (String pkgName : deferPackages) {
2956                    PackageParser.Package pkg = null;
2957                    synchronized (mPackages) {
2958                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2959                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2960                            pkg = ps.pkg;
2961                        }
2962                    }
2963                    if (pkg != null) {
2964                        synchronized (mInstallLock) {
2965                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2966                                    true /* maybeMigrateAppData */);
2967                        }
2968                        count++;
2969                    }
2970                }
2971                traceLog.traceEnd();
2972                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2973            }, "prepareAppData");
2974
2975            // If this is first boot after an OTA, and a normal boot, then
2976            // we need to clear code cache directories.
2977            // Note that we do *not* clear the application profiles. These remain valid
2978            // across OTAs and are used to drive profile verification (post OTA) and
2979            // profile compilation (without waiting to collect a fresh set of profiles).
2980            if (mIsUpgrade && !onlyCore) {
2981                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2982                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2983                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2984                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2985                        // No apps are running this early, so no need to freeze
2986                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2987                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2988                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2989                    }
2990                }
2991                ver.fingerprint = Build.FINGERPRINT;
2992            }
2993
2994            checkDefaultBrowser();
2995
2996            // clear only after permissions and other defaults have been updated
2997            mExistingSystemPackages.clear();
2998            mPromoteSystemApps = false;
2999
3000            // All the changes are done during package scanning.
3001            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3002
3003            // can downgrade to reader
3004            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3005            mSettings.writeLPr();
3006            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3007            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3008                    SystemClock.uptimeMillis());
3009
3010            if (!mOnlyCore) {
3011                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3012                mRequiredInstallerPackage = getRequiredInstallerLPr();
3013                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3014                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3015                if (mIntentFilterVerifierComponent != null) {
3016                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3017                            mIntentFilterVerifierComponent);
3018                } else {
3019                    mIntentFilterVerifier = null;
3020                }
3021                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3022                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3023                        SharedLibraryInfo.VERSION_UNDEFINED);
3024                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3025                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3026                        SharedLibraryInfo.VERSION_UNDEFINED);
3027            } else {
3028                mRequiredVerifierPackage = null;
3029                mRequiredInstallerPackage = null;
3030                mRequiredUninstallerPackage = null;
3031                mIntentFilterVerifierComponent = null;
3032                mIntentFilterVerifier = null;
3033                mServicesSystemSharedLibraryPackageName = null;
3034                mSharedSystemSharedLibraryPackageName = null;
3035            }
3036
3037            mInstallerService = new PackageInstallerService(context, this);
3038            final Pair<ComponentName, String> instantAppResolverComponent =
3039                    getInstantAppResolverLPr();
3040            if (instantAppResolverComponent != null) {
3041                if (DEBUG_EPHEMERAL) {
3042                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3043                }
3044                mInstantAppResolverConnection = new EphemeralResolverConnection(
3045                        mContext, instantAppResolverComponent.first,
3046                        instantAppResolverComponent.second);
3047                mInstantAppResolverSettingsComponent =
3048                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3049            } else {
3050                mInstantAppResolverConnection = null;
3051                mInstantAppResolverSettingsComponent = null;
3052            }
3053            updateInstantAppInstallerLocked(null);
3054
3055            // Read and update the usage of dex files.
3056            // Do this at the end of PM init so that all the packages have their
3057            // data directory reconciled.
3058            // At this point we know the code paths of the packages, so we can validate
3059            // the disk file and build the internal cache.
3060            // The usage file is expected to be small so loading and verifying it
3061            // should take a fairly small time compare to the other activities (e.g. package
3062            // scanning).
3063            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3064            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3065            for (int userId : currentUserIds) {
3066                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3067            }
3068            mDexManager.load(userPackages);
3069            if (mIsUpgrade) {
3070                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3071                        (int) (SystemClock.uptimeMillis() - startTime));
3072            }
3073        } // synchronized (mPackages)
3074        } // synchronized (mInstallLock)
3075
3076        // Now after opening every single application zip, make sure they
3077        // are all flushed.  Not really needed, but keeps things nice and
3078        // tidy.
3079        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3080        Runtime.getRuntime().gc();
3081        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3082
3083        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3084        FallbackCategoryProvider.loadFallbacks();
3085        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3086
3087        // The initial scanning above does many calls into installd while
3088        // holding the mPackages lock, but we're mostly interested in yelling
3089        // once we have a booted system.
3090        mInstaller.setWarnIfHeld(mPackages);
3091
3092        // Expose private service for system components to use.
3093        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3094        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3095    }
3096
3097    /**
3098     * Uncompress and install stub applications.
3099     * <p>In order to save space on the system partition, some applications are shipped in a
3100     * compressed form. In addition the compressed bits for the full application, the
3101     * system image contains a tiny stub comprised of only the Android manifest.
3102     * <p>During the first boot, attempt to uncompress and install the full application. If
3103     * the application can't be installed for any reason, disable the stub and prevent
3104     * uncompressing the full application during future boots.
3105     * <p>In order to forcefully attempt an installation of a full application, go to app
3106     * settings and enable the application.
3107     */
3108    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3109        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3110            final String pkgName = stubSystemApps.get(i);
3111            // skip if the system package is already disabled
3112            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3113                stubSystemApps.remove(i);
3114                continue;
3115            }
3116            // skip if the package isn't installed (?!); this should never happen
3117            final PackageParser.Package pkg = mPackages.get(pkgName);
3118            if (pkg == null) {
3119                stubSystemApps.remove(i);
3120                continue;
3121            }
3122            // skip if the package has been disabled by the user
3123            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3124            if (ps != null) {
3125                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3126                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3127                    stubSystemApps.remove(i);
3128                    continue;
3129                }
3130            }
3131
3132            if (DEBUG_COMPRESSION) {
3133                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3134            }
3135
3136            // uncompress the binary to its eventual destination on /data
3137            final File scanFile = decompressPackage(pkg);
3138            if (scanFile == null) {
3139                continue;
3140            }
3141
3142            // install the package to replace the stub on /system
3143            try {
3144                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3145                removePackageLI(pkg, true /*chatty*/);
3146                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3147                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3148                        UserHandle.USER_SYSTEM, "android");
3149                stubSystemApps.remove(i);
3150                continue;
3151            } catch (PackageManagerException e) {
3152                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3153            }
3154
3155            // any failed attempt to install the package will be cleaned up later
3156        }
3157
3158        // disable any stub still left; these failed to install the full application
3159        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3160            final String pkgName = stubSystemApps.get(i);
3161            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3162            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3163                    UserHandle.USER_SYSTEM, "android");
3164            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3165        }
3166    }
3167
3168    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3169        if (DEBUG_COMPRESSION) {
3170            Slog.i(TAG, "Decompress file"
3171                    + "; src: " + srcFile.getAbsolutePath()
3172                    + ", dst: " + dstFile.getAbsolutePath());
3173        }
3174        try (
3175                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3176                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3177        ) {
3178            Streams.copy(fileIn, fileOut);
3179            Os.chmod(dstFile.getAbsolutePath(), 0644);
3180            return PackageManager.INSTALL_SUCCEEDED;
3181        } catch (IOException e) {
3182            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3183                    + "; src: " + srcFile.getAbsolutePath()
3184                    + ", dst: " + dstFile.getAbsolutePath());
3185        }
3186        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3187    }
3188
3189    private File[] getCompressedFiles(String codePath) {
3190        return new File(codePath).listFiles(new FilenameFilter() {
3191            @Override
3192            public boolean accept(File dir, String name) {
3193                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3194            }
3195        });
3196    }
3197
3198    private boolean compressedFileExists(String codePath) {
3199        final File[] compressedFiles = getCompressedFiles(codePath);
3200        return compressedFiles != null && compressedFiles.length > 0;
3201    }
3202
3203    /**
3204     * Decompresses the given package on the system image onto
3205     * the /data partition.
3206     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3207     */
3208    private File decompressPackage(PackageParser.Package pkg) {
3209        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3210        if (compressedFiles == null || compressedFiles.length == 0) {
3211            if (DEBUG_COMPRESSION) {
3212                Slog.i(TAG, "No files to decompress");
3213            }
3214            return null;
3215        }
3216        final File dstCodePath =
3217                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3218        int ret = PackageManager.INSTALL_SUCCEEDED;
3219        try {
3220            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3221            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3222            for (File srcFile : compressedFiles) {
3223                final String srcFileName = srcFile.getName();
3224                final String dstFileName = srcFileName.substring(
3225                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3226                final File dstFile = new File(dstCodePath, dstFileName);
3227                ret = decompressFile(srcFile, dstFile);
3228                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3229                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3230                            + "; pkg: " + pkg.packageName
3231                            + ", file: " + dstFileName);
3232                    break;
3233                }
3234            }
3235        } catch (ErrnoException e) {
3236            logCriticalInfo(Log.ERROR, "Failed to decompress"
3237                    + "; pkg: " + pkg.packageName
3238                    + ", err: " + e.errno);
3239        }
3240        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3241            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3242            NativeLibraryHelper.Handle handle = null;
3243            try {
3244                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3245                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3246                        null /*abiOverride*/);
3247            } catch (IOException e) {
3248                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3249                        + "; pkg: " + pkg.packageName);
3250                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3251            } finally {
3252                IoUtils.closeQuietly(handle);
3253            }
3254        }
3255        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3256            if (dstCodePath == null || !dstCodePath.exists()) {
3257                return null;
3258            }
3259            removeCodePathLI(dstCodePath);
3260            return null;
3261        }
3262        return dstCodePath;
3263    }
3264
3265    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3266        // we're only interested in updating the installer appliction when 1) it's not
3267        // already set or 2) the modified package is the installer
3268        if (mInstantAppInstallerActivity != null
3269                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3270                        .equals(modifiedPackage)) {
3271            return;
3272        }
3273        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3274    }
3275
3276    private static File preparePackageParserCache(boolean isUpgrade) {
3277        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3278            return null;
3279        }
3280
3281        // Disable package parsing on eng builds to allow for faster incremental development.
3282        if (Build.IS_ENG) {
3283            return null;
3284        }
3285
3286        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3287            Slog.i(TAG, "Disabling package parser cache due to system property.");
3288            return null;
3289        }
3290
3291        // The base directory for the package parser cache lives under /data/system/.
3292        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3293                "package_cache");
3294        if (cacheBaseDir == null) {
3295            return null;
3296        }
3297
3298        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3299        // This also serves to "GC" unused entries when the package cache version changes (which
3300        // can only happen during upgrades).
3301        if (isUpgrade) {
3302            FileUtils.deleteContents(cacheBaseDir);
3303        }
3304
3305
3306        // Return the versioned package cache directory. This is something like
3307        // "/data/system/package_cache/1"
3308        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3309
3310        // The following is a workaround to aid development on non-numbered userdebug
3311        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3312        // the system partition is newer.
3313        //
3314        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3315        // that starts with "eng." to signify that this is an engineering build and not
3316        // destined for release.
3317        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3318            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3319
3320            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3321            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3322            // in general and should not be used for production changes. In this specific case,
3323            // we know that they will work.
3324            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3325            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3326                FileUtils.deleteContents(cacheBaseDir);
3327                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3328            }
3329        }
3330
3331        return cacheDir;
3332    }
3333
3334    @Override
3335    public boolean isFirstBoot() {
3336        // allow instant applications
3337        return mFirstBoot;
3338    }
3339
3340    @Override
3341    public boolean isOnlyCoreApps() {
3342        // allow instant applications
3343        return mOnlyCore;
3344    }
3345
3346    @Override
3347    public boolean isUpgrade() {
3348        // allow instant applications
3349        return mIsUpgrade;
3350    }
3351
3352    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3353        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3354
3355        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3356                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3357                UserHandle.USER_SYSTEM);
3358        if (matches.size() == 1) {
3359            return matches.get(0).getComponentInfo().packageName;
3360        } else if (matches.size() == 0) {
3361            Log.e(TAG, "There should probably be a verifier, but, none were found");
3362            return null;
3363        }
3364        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3365    }
3366
3367    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3368        synchronized (mPackages) {
3369            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3370            if (libraryEntry == null) {
3371                throw new IllegalStateException("Missing required shared library:" + name);
3372            }
3373            return libraryEntry.apk;
3374        }
3375    }
3376
3377    private @NonNull String getRequiredInstallerLPr() {
3378        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3379        intent.addCategory(Intent.CATEGORY_DEFAULT);
3380        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3381
3382        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3383                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3384                UserHandle.USER_SYSTEM);
3385        if (matches.size() == 1) {
3386            ResolveInfo resolveInfo = matches.get(0);
3387            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3388                throw new RuntimeException("The installer must be a privileged app");
3389            }
3390            return matches.get(0).getComponentInfo().packageName;
3391        } else {
3392            throw new RuntimeException("There must be exactly one installer; found " + matches);
3393        }
3394    }
3395
3396    private @NonNull String getRequiredUninstallerLPr() {
3397        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3398        intent.addCategory(Intent.CATEGORY_DEFAULT);
3399        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3400
3401        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3402                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3403                UserHandle.USER_SYSTEM);
3404        if (resolveInfo == null ||
3405                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3406            throw new RuntimeException("There must be exactly one uninstaller; found "
3407                    + resolveInfo);
3408        }
3409        return resolveInfo.getComponentInfo().packageName;
3410    }
3411
3412    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3413        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3414
3415        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3416                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3417                UserHandle.USER_SYSTEM);
3418        ResolveInfo best = null;
3419        final int N = matches.size();
3420        for (int i = 0; i < N; i++) {
3421            final ResolveInfo cur = matches.get(i);
3422            final String packageName = cur.getComponentInfo().packageName;
3423            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3424                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3425                continue;
3426            }
3427
3428            if (best == null || cur.priority > best.priority) {
3429                best = cur;
3430            }
3431        }
3432
3433        if (best != null) {
3434            return best.getComponentInfo().getComponentName();
3435        }
3436        Slog.w(TAG, "Intent filter verifier not found");
3437        return null;
3438    }
3439
3440    @Override
3441    public @Nullable ComponentName getInstantAppResolverComponent() {
3442        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3443            return null;
3444        }
3445        synchronized (mPackages) {
3446            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3447            if (instantAppResolver == null) {
3448                return null;
3449            }
3450            return instantAppResolver.first;
3451        }
3452    }
3453
3454    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3455        final String[] packageArray =
3456                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3457        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3458            if (DEBUG_EPHEMERAL) {
3459                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3460            }
3461            return null;
3462        }
3463
3464        final int callingUid = Binder.getCallingUid();
3465        final int resolveFlags =
3466                MATCH_DIRECT_BOOT_AWARE
3467                | MATCH_DIRECT_BOOT_UNAWARE
3468                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3469        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3470        final Intent resolverIntent = new Intent(actionName);
3471        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3472                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3473        // temporarily look for the old action
3474        if (resolvers.size() == 0) {
3475            if (DEBUG_EPHEMERAL) {
3476                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3477            }
3478            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3479            resolverIntent.setAction(actionName);
3480            resolvers = queryIntentServicesInternal(resolverIntent, null,
3481                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3482        }
3483        final int N = resolvers.size();
3484        if (N == 0) {
3485            if (DEBUG_EPHEMERAL) {
3486                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3487            }
3488            return null;
3489        }
3490
3491        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3492        for (int i = 0; i < N; i++) {
3493            final ResolveInfo info = resolvers.get(i);
3494
3495            if (info.serviceInfo == null) {
3496                continue;
3497            }
3498
3499            final String packageName = info.serviceInfo.packageName;
3500            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3501                if (DEBUG_EPHEMERAL) {
3502                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3503                            + " pkg: " + packageName + ", info:" + info);
3504                }
3505                continue;
3506            }
3507
3508            if (DEBUG_EPHEMERAL) {
3509                Slog.v(TAG, "Ephemeral resolver found;"
3510                        + " pkg: " + packageName + ", info:" + info);
3511            }
3512            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3513        }
3514        if (DEBUG_EPHEMERAL) {
3515            Slog.v(TAG, "Ephemeral resolver NOT found");
3516        }
3517        return null;
3518    }
3519
3520    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3521        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3522        intent.addCategory(Intent.CATEGORY_DEFAULT);
3523        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3524
3525        final int resolveFlags =
3526                MATCH_DIRECT_BOOT_AWARE
3527                | MATCH_DIRECT_BOOT_UNAWARE
3528                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3529        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3530                resolveFlags, UserHandle.USER_SYSTEM);
3531        // temporarily look for the old action
3532        if (matches.isEmpty()) {
3533            if (DEBUG_EPHEMERAL) {
3534                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3535            }
3536            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3537            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3538                    resolveFlags, UserHandle.USER_SYSTEM);
3539        }
3540        Iterator<ResolveInfo> iter = matches.iterator();
3541        while (iter.hasNext()) {
3542            final ResolveInfo rInfo = iter.next();
3543            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3544            if (ps != null) {
3545                final PermissionsState permissionsState = ps.getPermissionsState();
3546                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3547                    continue;
3548                }
3549            }
3550            iter.remove();
3551        }
3552        if (matches.size() == 0) {
3553            return null;
3554        } else if (matches.size() == 1) {
3555            return (ActivityInfo) matches.get(0).getComponentInfo();
3556        } else {
3557            throw new RuntimeException(
3558                    "There must be at most one ephemeral installer; found " + matches);
3559        }
3560    }
3561
3562    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3563            @NonNull ComponentName resolver) {
3564        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3565                .addCategory(Intent.CATEGORY_DEFAULT)
3566                .setPackage(resolver.getPackageName());
3567        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3568        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3569                UserHandle.USER_SYSTEM);
3570        // temporarily look for the old action
3571        if (matches.isEmpty()) {
3572            if (DEBUG_EPHEMERAL) {
3573                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3574            }
3575            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3576            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3577                    UserHandle.USER_SYSTEM);
3578        }
3579        if (matches.isEmpty()) {
3580            return null;
3581        }
3582        return matches.get(0).getComponentInfo().getComponentName();
3583    }
3584
3585    private void primeDomainVerificationsLPw(int userId) {
3586        if (DEBUG_DOMAIN_VERIFICATION) {
3587            Slog.d(TAG, "Priming domain verifications in user " + userId);
3588        }
3589
3590        SystemConfig systemConfig = SystemConfig.getInstance();
3591        ArraySet<String> packages = systemConfig.getLinkedApps();
3592
3593        for (String packageName : packages) {
3594            PackageParser.Package pkg = mPackages.get(packageName);
3595            if (pkg != null) {
3596                if (!pkg.isSystemApp()) {
3597                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3598                    continue;
3599                }
3600
3601                ArraySet<String> domains = null;
3602                for (PackageParser.Activity a : pkg.activities) {
3603                    for (ActivityIntentInfo filter : a.intents) {
3604                        if (hasValidDomains(filter)) {
3605                            if (domains == null) {
3606                                domains = new ArraySet<String>();
3607                            }
3608                            domains.addAll(filter.getHostsList());
3609                        }
3610                    }
3611                }
3612
3613                if (domains != null && domains.size() > 0) {
3614                    if (DEBUG_DOMAIN_VERIFICATION) {
3615                        Slog.v(TAG, "      + " + packageName);
3616                    }
3617                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3618                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3619                    // and then 'always' in the per-user state actually used for intent resolution.
3620                    final IntentFilterVerificationInfo ivi;
3621                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3622                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3623                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3624                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3625                } else {
3626                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3627                            + "' does not handle web links");
3628                }
3629            } else {
3630                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3631            }
3632        }
3633
3634        scheduleWritePackageRestrictionsLocked(userId);
3635        scheduleWriteSettingsLocked();
3636    }
3637
3638    private void applyFactoryDefaultBrowserLPw(int userId) {
3639        // The default browser app's package name is stored in a string resource,
3640        // with a product-specific overlay used for vendor customization.
3641        String browserPkg = mContext.getResources().getString(
3642                com.android.internal.R.string.default_browser);
3643        if (!TextUtils.isEmpty(browserPkg)) {
3644            // non-empty string => required to be a known package
3645            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3646            if (ps == null) {
3647                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3648                browserPkg = null;
3649            } else {
3650                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3651            }
3652        }
3653
3654        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3655        // default.  If there's more than one, just leave everything alone.
3656        if (browserPkg == null) {
3657            calculateDefaultBrowserLPw(userId);
3658        }
3659    }
3660
3661    private void calculateDefaultBrowserLPw(int userId) {
3662        List<String> allBrowsers = resolveAllBrowserApps(userId);
3663        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3664        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3665    }
3666
3667    private List<String> resolveAllBrowserApps(int userId) {
3668        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3669        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3670                PackageManager.MATCH_ALL, userId);
3671
3672        final int count = list.size();
3673        List<String> result = new ArrayList<String>(count);
3674        for (int i=0; i<count; i++) {
3675            ResolveInfo info = list.get(i);
3676            if (info.activityInfo == null
3677                    || !info.handleAllWebDataURI
3678                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3679                    || result.contains(info.activityInfo.packageName)) {
3680                continue;
3681            }
3682            result.add(info.activityInfo.packageName);
3683        }
3684
3685        return result;
3686    }
3687
3688    private boolean packageIsBrowser(String packageName, int userId) {
3689        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3690                PackageManager.MATCH_ALL, userId);
3691        final int N = list.size();
3692        for (int i = 0; i < N; i++) {
3693            ResolveInfo info = list.get(i);
3694            if (packageName.equals(info.activityInfo.packageName)) {
3695                return true;
3696            }
3697        }
3698        return false;
3699    }
3700
3701    private void checkDefaultBrowser() {
3702        final int myUserId = UserHandle.myUserId();
3703        final String packageName = getDefaultBrowserPackageName(myUserId);
3704        if (packageName != null) {
3705            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3706            if (info == null) {
3707                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3708                synchronized (mPackages) {
3709                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3710                }
3711            }
3712        }
3713    }
3714
3715    @Override
3716    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3717            throws RemoteException {
3718        try {
3719            return super.onTransact(code, data, reply, flags);
3720        } catch (RuntimeException e) {
3721            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3722                Slog.wtf(TAG, "Package Manager Crash", e);
3723            }
3724            throw e;
3725        }
3726    }
3727
3728    static int[] appendInts(int[] cur, int[] add) {
3729        if (add == null) return cur;
3730        if (cur == null) return add;
3731        final int N = add.length;
3732        for (int i=0; i<N; i++) {
3733            cur = appendInt(cur, add[i]);
3734        }
3735        return cur;
3736    }
3737
3738    /**
3739     * Returns whether or not a full application can see an instant application.
3740     * <p>
3741     * Currently, there are three cases in which this can occur:
3742     * <ol>
3743     * <li>The calling application is a "special" process. The special
3744     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3745     *     and {@code 0}</li>
3746     * <li>The calling application has the permission
3747     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3748     * <li>The calling application is the default launcher on the
3749     *     system partition.</li>
3750     * </ol>
3751     */
3752    private boolean canViewInstantApps(int callingUid, int userId) {
3753        if (callingUid == Process.SYSTEM_UID
3754                || callingUid == Process.SHELL_UID
3755                || callingUid == Process.ROOT_UID) {
3756            return true;
3757        }
3758        if (mContext.checkCallingOrSelfPermission(
3759                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3760            return true;
3761        }
3762        if (mContext.checkCallingOrSelfPermission(
3763                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3764            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3765            if (homeComponent != null
3766                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3767                return true;
3768            }
3769        }
3770        return false;
3771    }
3772
3773    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3774        if (!sUserManager.exists(userId)) return null;
3775        if (ps == null) {
3776            return null;
3777        }
3778        PackageParser.Package p = ps.pkg;
3779        if (p == null) {
3780            return null;
3781        }
3782        final int callingUid = Binder.getCallingUid();
3783        // Filter out ephemeral app metadata:
3784        //   * The system/shell/root can see metadata for any app
3785        //   * An installed app can see metadata for 1) other installed apps
3786        //     and 2) ephemeral apps that have explicitly interacted with it
3787        //   * Ephemeral apps can only see their own data and exposed installed apps
3788        //   * Holding a signature permission allows seeing instant apps
3789        if (filterAppAccessLPr(ps, callingUid, userId)) {
3790            return null;
3791        }
3792
3793        final PermissionsState permissionsState = ps.getPermissionsState();
3794
3795        // Compute GIDs only if requested
3796        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3797                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3798        // Compute granted permissions only if package has requested permissions
3799        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3800                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3801        final PackageUserState state = ps.readUserState(userId);
3802
3803        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3804                && ps.isSystem()) {
3805            flags |= MATCH_ANY_USER;
3806        }
3807
3808        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3809                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3810
3811        if (packageInfo == null) {
3812            return null;
3813        }
3814
3815        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3816                resolveExternalPackageNameLPr(p);
3817
3818        return packageInfo;
3819    }
3820
3821    @Override
3822    public void checkPackageStartable(String packageName, int userId) {
3823        final int callingUid = Binder.getCallingUid();
3824        if (getInstantAppPackageName(callingUid) != null) {
3825            throw new SecurityException("Instant applications don't have access to this method");
3826        }
3827        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3828        synchronized (mPackages) {
3829            final PackageSetting ps = mSettings.mPackages.get(packageName);
3830            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3831                throw new SecurityException("Package " + packageName + " was not found!");
3832            }
3833
3834            if (!ps.getInstalled(userId)) {
3835                throw new SecurityException(
3836                        "Package " + packageName + " was not installed for user " + userId + "!");
3837            }
3838
3839            if (mSafeMode && !ps.isSystem()) {
3840                throw new SecurityException("Package " + packageName + " not a system app!");
3841            }
3842
3843            if (mFrozenPackages.contains(packageName)) {
3844                throw new SecurityException("Package " + packageName + " is currently frozen!");
3845            }
3846
3847            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3848                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3849                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3850            }
3851        }
3852    }
3853
3854    @Override
3855    public boolean isPackageAvailable(String packageName, int userId) {
3856        if (!sUserManager.exists(userId)) return false;
3857        final int callingUid = Binder.getCallingUid();
3858        enforceCrossUserPermission(callingUid, userId,
3859                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3860        synchronized (mPackages) {
3861            PackageParser.Package p = mPackages.get(packageName);
3862            if (p != null) {
3863                final PackageSetting ps = (PackageSetting) p.mExtras;
3864                if (filterAppAccessLPr(ps, callingUid, userId)) {
3865                    return false;
3866                }
3867                if (ps != null) {
3868                    final PackageUserState state = ps.readUserState(userId);
3869                    if (state != null) {
3870                        return PackageParser.isAvailable(state);
3871                    }
3872                }
3873            }
3874        }
3875        return false;
3876    }
3877
3878    @Override
3879    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3880        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3881                flags, Binder.getCallingUid(), userId);
3882    }
3883
3884    @Override
3885    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3886            int flags, int userId) {
3887        return getPackageInfoInternal(versionedPackage.getPackageName(),
3888                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3889    }
3890
3891    /**
3892     * Important: The provided filterCallingUid is used exclusively to filter out packages
3893     * that can be seen based on user state. It's typically the original caller uid prior
3894     * to clearing. Because it can only be provided by trusted code, it's value can be
3895     * trusted and will be used as-is; unlike userId which will be validated by this method.
3896     */
3897    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3898            int flags, int filterCallingUid, int userId) {
3899        if (!sUserManager.exists(userId)) return null;
3900        flags = updateFlagsForPackage(flags, userId, packageName);
3901        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3902                false /* requireFullPermission */, false /* checkShell */, "get package info");
3903
3904        // reader
3905        synchronized (mPackages) {
3906            // Normalize package name to handle renamed packages and static libs
3907            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3908
3909            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3910            if (matchFactoryOnly) {
3911                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3912                if (ps != null) {
3913                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3914                        return null;
3915                    }
3916                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3917                        return null;
3918                    }
3919                    return generatePackageInfo(ps, flags, userId);
3920                }
3921            }
3922
3923            PackageParser.Package p = mPackages.get(packageName);
3924            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3925                return null;
3926            }
3927            if (DEBUG_PACKAGE_INFO)
3928                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3929            if (p != null) {
3930                final PackageSetting ps = (PackageSetting) p.mExtras;
3931                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3932                    return null;
3933                }
3934                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3935                    return null;
3936                }
3937                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3938            }
3939            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3940                final PackageSetting ps = mSettings.mPackages.get(packageName);
3941                if (ps == null) return null;
3942                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3943                    return null;
3944                }
3945                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3946                    return null;
3947                }
3948                return generatePackageInfo(ps, flags, userId);
3949            }
3950        }
3951        return null;
3952    }
3953
3954    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3955        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3956            return true;
3957        }
3958        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3959            return true;
3960        }
3961        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3962            return true;
3963        }
3964        return false;
3965    }
3966
3967    private boolean isComponentVisibleToInstantApp(
3968            @Nullable ComponentName component, @ComponentType int type) {
3969        if (type == TYPE_ACTIVITY) {
3970            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3971            return activity != null
3972                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3973                    : false;
3974        } else if (type == TYPE_RECEIVER) {
3975            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3976            return activity != null
3977                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3978                    : false;
3979        } else if (type == TYPE_SERVICE) {
3980            final PackageParser.Service service = mServices.mServices.get(component);
3981            return service != null
3982                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3983                    : false;
3984        } else if (type == TYPE_PROVIDER) {
3985            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3986            return provider != null
3987                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3988                    : false;
3989        } else if (type == TYPE_UNKNOWN) {
3990            return isComponentVisibleToInstantApp(component);
3991        }
3992        return false;
3993    }
3994
3995    /**
3996     * Returns whether or not access to the application should be filtered.
3997     * <p>
3998     * Access may be limited based upon whether the calling or target applications
3999     * are instant applications.
4000     *
4001     * @see #canAccessInstantApps(int)
4002     */
4003    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4004            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4005        // if we're in an isolated process, get the real calling UID
4006        if (Process.isIsolated(callingUid)) {
4007            callingUid = mIsolatedOwners.get(callingUid);
4008        }
4009        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4010        final boolean callerIsInstantApp = instantAppPkgName != null;
4011        if (ps == null) {
4012            if (callerIsInstantApp) {
4013                // pretend the application exists, but, needs to be filtered
4014                return true;
4015            }
4016            return false;
4017        }
4018        // if the target and caller are the same application, don't filter
4019        if (isCallerSameApp(ps.name, callingUid)) {
4020            return false;
4021        }
4022        if (callerIsInstantApp) {
4023            // request for a specific component; if it hasn't been explicitly exposed, filter
4024            if (component != null) {
4025                return !isComponentVisibleToInstantApp(component, componentType);
4026            }
4027            // request for application; if no components have been explicitly exposed, filter
4028            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4029        }
4030        if (ps.getInstantApp(userId)) {
4031            // caller can see all components of all instant applications, don't filter
4032            if (canViewInstantApps(callingUid, userId)) {
4033                return false;
4034            }
4035            // request for a specific instant application component, filter
4036            if (component != null) {
4037                return true;
4038            }
4039            // request for an instant application; if the caller hasn't been granted access, filter
4040            return !mInstantAppRegistry.isInstantAccessGranted(
4041                    userId, UserHandle.getAppId(callingUid), ps.appId);
4042        }
4043        return false;
4044    }
4045
4046    /**
4047     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4048     */
4049    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4050        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4051    }
4052
4053    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4054            int flags) {
4055        // Callers can access only the libs they depend on, otherwise they need to explicitly
4056        // ask for the shared libraries given the caller is allowed to access all static libs.
4057        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4058            // System/shell/root get to see all static libs
4059            final int appId = UserHandle.getAppId(uid);
4060            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4061                    || appId == Process.ROOT_UID) {
4062                return false;
4063            }
4064        }
4065
4066        // No package means no static lib as it is always on internal storage
4067        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4068            return false;
4069        }
4070
4071        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4072                ps.pkg.staticSharedLibVersion);
4073        if (libEntry == null) {
4074            return false;
4075        }
4076
4077        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4078        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4079        if (uidPackageNames == null) {
4080            return true;
4081        }
4082
4083        for (String uidPackageName : uidPackageNames) {
4084            if (ps.name.equals(uidPackageName)) {
4085                return false;
4086            }
4087            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4088            if (uidPs != null) {
4089                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4090                        libEntry.info.getName());
4091                if (index < 0) {
4092                    continue;
4093                }
4094                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4095                    return false;
4096                }
4097            }
4098        }
4099        return true;
4100    }
4101
4102    @Override
4103    public String[] currentToCanonicalPackageNames(String[] names) {
4104        final int callingUid = Binder.getCallingUid();
4105        if (getInstantAppPackageName(callingUid) != null) {
4106            return names;
4107        }
4108        final String[] out = new String[names.length];
4109        // reader
4110        synchronized (mPackages) {
4111            final int callingUserId = UserHandle.getUserId(callingUid);
4112            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4113            for (int i=names.length-1; i>=0; i--) {
4114                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4115                boolean translateName = false;
4116                if (ps != null && ps.realName != null) {
4117                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4118                    translateName = !targetIsInstantApp
4119                            || canViewInstantApps
4120                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4121                                    UserHandle.getAppId(callingUid), ps.appId);
4122                }
4123                out[i] = translateName ? ps.realName : names[i];
4124            }
4125        }
4126        return out;
4127    }
4128
4129    @Override
4130    public String[] canonicalToCurrentPackageNames(String[] names) {
4131        final int callingUid = Binder.getCallingUid();
4132        if (getInstantAppPackageName(callingUid) != null) {
4133            return names;
4134        }
4135        final String[] out = new String[names.length];
4136        // reader
4137        synchronized (mPackages) {
4138            final int callingUserId = UserHandle.getUserId(callingUid);
4139            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4140            for (int i=names.length-1; i>=0; i--) {
4141                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4142                boolean translateName = false;
4143                if (cur != null) {
4144                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4145                    final boolean targetIsInstantApp =
4146                            ps != null && ps.getInstantApp(callingUserId);
4147                    translateName = !targetIsInstantApp
4148                            || canViewInstantApps
4149                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4150                                    UserHandle.getAppId(callingUid), ps.appId);
4151                }
4152                out[i] = translateName ? cur : names[i];
4153            }
4154        }
4155        return out;
4156    }
4157
4158    @Override
4159    public int getPackageUid(String packageName, int flags, int userId) {
4160        if (!sUserManager.exists(userId)) return -1;
4161        final int callingUid = Binder.getCallingUid();
4162        flags = updateFlagsForPackage(flags, userId, packageName);
4163        enforceCrossUserPermission(callingUid, userId,
4164                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4165
4166        // reader
4167        synchronized (mPackages) {
4168            final PackageParser.Package p = mPackages.get(packageName);
4169            if (p != null && p.isMatch(flags)) {
4170                PackageSetting ps = (PackageSetting) p.mExtras;
4171                if (filterAppAccessLPr(ps, callingUid, userId)) {
4172                    return -1;
4173                }
4174                return UserHandle.getUid(userId, p.applicationInfo.uid);
4175            }
4176            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4177                final PackageSetting ps = mSettings.mPackages.get(packageName);
4178                if (ps != null && ps.isMatch(flags)
4179                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4180                    return UserHandle.getUid(userId, ps.appId);
4181                }
4182            }
4183        }
4184
4185        return -1;
4186    }
4187
4188    @Override
4189    public int[] getPackageGids(String packageName, int flags, int userId) {
4190        if (!sUserManager.exists(userId)) return null;
4191        final int callingUid = Binder.getCallingUid();
4192        flags = updateFlagsForPackage(flags, userId, packageName);
4193        enforceCrossUserPermission(callingUid, userId,
4194                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4195
4196        // reader
4197        synchronized (mPackages) {
4198            final PackageParser.Package p = mPackages.get(packageName);
4199            if (p != null && p.isMatch(flags)) {
4200                PackageSetting ps = (PackageSetting) p.mExtras;
4201                if (filterAppAccessLPr(ps, callingUid, userId)) {
4202                    return null;
4203                }
4204                // TODO: Shouldn't this be checking for package installed state for userId and
4205                // return null?
4206                return ps.getPermissionsState().computeGids(userId);
4207            }
4208            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4209                final PackageSetting ps = mSettings.mPackages.get(packageName);
4210                if (ps != null && ps.isMatch(flags)
4211                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4212                    return ps.getPermissionsState().computeGids(userId);
4213                }
4214            }
4215        }
4216
4217        return null;
4218    }
4219
4220    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4221        if (bp.perm != null) {
4222            return PackageParser.generatePermissionInfo(bp.perm, flags);
4223        }
4224        PermissionInfo pi = new PermissionInfo();
4225        pi.name = bp.name;
4226        pi.packageName = bp.sourcePackage;
4227        pi.nonLocalizedLabel = bp.name;
4228        pi.protectionLevel = bp.protectionLevel;
4229        return pi;
4230    }
4231
4232    @Override
4233    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4234        final int callingUid = Binder.getCallingUid();
4235        if (getInstantAppPackageName(callingUid) != null) {
4236            return null;
4237        }
4238        // reader
4239        synchronized (mPackages) {
4240            final BasePermission p = mSettings.mPermissions.get(name);
4241            if (p == null) {
4242                return null;
4243            }
4244            // If the caller is an app that targets pre 26 SDK drop protection flags.
4245            final PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4246            if (permissionInfo != null) {
4247                permissionInfo.protectionLevel = adjustPermissionProtectionFlagsLPr(
4248                        permissionInfo.protectionLevel, packageName, callingUid);
4249            }
4250            return permissionInfo;
4251        }
4252    }
4253
4254    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4255            String packageName, int uid) {
4256        // Signature permission flags area always reported
4257        final int protectionLevelMasked = protectionLevel
4258                & (PermissionInfo.PROTECTION_NORMAL
4259                | PermissionInfo.PROTECTION_DANGEROUS
4260                | PermissionInfo.PROTECTION_SIGNATURE);
4261        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4262            return protectionLevel;
4263        }
4264
4265        // System sees all flags.
4266        final int appId = UserHandle.getAppId(uid);
4267        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4268                || appId == Process.SHELL_UID) {
4269            return protectionLevel;
4270        }
4271
4272        // Normalize package name to handle renamed packages and static libs
4273        packageName = resolveInternalPackageNameLPr(packageName,
4274                PackageManager.VERSION_CODE_HIGHEST);
4275
4276        // Apps that target O see flags for all protection levels.
4277        final PackageSetting ps = mSettings.mPackages.get(packageName);
4278        if (ps == null) {
4279            return protectionLevel;
4280        }
4281        if (ps.appId != appId) {
4282            return protectionLevel;
4283        }
4284
4285        final PackageParser.Package pkg = mPackages.get(packageName);
4286        if (pkg == null) {
4287            return protectionLevel;
4288        }
4289        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4290            return protectionLevelMasked;
4291        }
4292
4293        return protectionLevel;
4294    }
4295
4296    @Override
4297    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4298            int flags) {
4299        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4300            return null;
4301        }
4302        // reader
4303        synchronized (mPackages) {
4304            if (group != null && !mPermissionGroups.containsKey(group)) {
4305                // This is thrown as NameNotFoundException
4306                return null;
4307            }
4308
4309            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4310            for (BasePermission p : mSettings.mPermissions.values()) {
4311                if (group == null) {
4312                    if (p.perm == null || p.perm.info.group == null) {
4313                        out.add(generatePermissionInfo(p, flags));
4314                    }
4315                } else {
4316                    if (p.perm != null && group.equals(p.perm.info.group)) {
4317                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4318                    }
4319                }
4320            }
4321            return new ParceledListSlice<>(out);
4322        }
4323    }
4324
4325    @Override
4326    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4327        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4328            return null;
4329        }
4330        // reader
4331        synchronized (mPackages) {
4332            return PackageParser.generatePermissionGroupInfo(
4333                    mPermissionGroups.get(name), flags);
4334        }
4335    }
4336
4337    @Override
4338    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4339        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4340            return ParceledListSlice.emptyList();
4341        }
4342        // reader
4343        synchronized (mPackages) {
4344            final int N = mPermissionGroups.size();
4345            ArrayList<PermissionGroupInfo> out
4346                    = new ArrayList<PermissionGroupInfo>(N);
4347            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4348                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4349            }
4350            return new ParceledListSlice<>(out);
4351        }
4352    }
4353
4354    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4355            int filterCallingUid, int userId) {
4356        if (!sUserManager.exists(userId)) return null;
4357        PackageSetting ps = mSettings.mPackages.get(packageName);
4358        if (ps != null) {
4359            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4360                return null;
4361            }
4362            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4363                return null;
4364            }
4365            if (ps.pkg == null) {
4366                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4367                if (pInfo != null) {
4368                    return pInfo.applicationInfo;
4369                }
4370                return null;
4371            }
4372            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4373                    ps.readUserState(userId), userId);
4374            if (ai != null) {
4375                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4376            }
4377            return ai;
4378        }
4379        return null;
4380    }
4381
4382    @Override
4383    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4384        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4385    }
4386
4387    /**
4388     * Important: The provided filterCallingUid is used exclusively to filter out applications
4389     * that can be seen based on user state. It's typically the original caller uid prior
4390     * to clearing. Because it can only be provided by trusted code, it's value can be
4391     * trusted and will be used as-is; unlike userId which will be validated by this method.
4392     */
4393    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4394            int filterCallingUid, int userId) {
4395        if (!sUserManager.exists(userId)) return null;
4396        flags = updateFlagsForApplication(flags, userId, packageName);
4397        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4398                false /* requireFullPermission */, false /* checkShell */, "get application info");
4399
4400        // writer
4401        synchronized (mPackages) {
4402            // Normalize package name to handle renamed packages and static libs
4403            packageName = resolveInternalPackageNameLPr(packageName,
4404                    PackageManager.VERSION_CODE_HIGHEST);
4405
4406            PackageParser.Package p = mPackages.get(packageName);
4407            if (DEBUG_PACKAGE_INFO) Log.v(
4408                    TAG, "getApplicationInfo " + packageName
4409                    + ": " + p);
4410            if (p != null) {
4411                PackageSetting ps = mSettings.mPackages.get(packageName);
4412                if (ps == null) return null;
4413                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4414                    return null;
4415                }
4416                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4417                    return null;
4418                }
4419                // Note: isEnabledLP() does not apply here - always return info
4420                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4421                        p, flags, ps.readUserState(userId), userId);
4422                if (ai != null) {
4423                    ai.packageName = resolveExternalPackageNameLPr(p);
4424                }
4425                return ai;
4426            }
4427            if ("android".equals(packageName)||"system".equals(packageName)) {
4428                return mAndroidApplication;
4429            }
4430            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4431                // Already generates the external package name
4432                return generateApplicationInfoFromSettingsLPw(packageName,
4433                        flags, filterCallingUid, userId);
4434            }
4435        }
4436        return null;
4437    }
4438
4439    private String normalizePackageNameLPr(String packageName) {
4440        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4441        return normalizedPackageName != null ? normalizedPackageName : packageName;
4442    }
4443
4444    @Override
4445    public void deletePreloadsFileCache() {
4446        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4447            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4448        }
4449        File dir = Environment.getDataPreloadsFileCacheDirectory();
4450        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4451        FileUtils.deleteContents(dir);
4452    }
4453
4454    @Override
4455    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4456            final int storageFlags, final IPackageDataObserver observer) {
4457        mContext.enforceCallingOrSelfPermission(
4458                android.Manifest.permission.CLEAR_APP_CACHE, null);
4459        mHandler.post(() -> {
4460            boolean success = false;
4461            try {
4462                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4463                success = true;
4464            } catch (IOException e) {
4465                Slog.w(TAG, e);
4466            }
4467            if (observer != null) {
4468                try {
4469                    observer.onRemoveCompleted(null, success);
4470                } catch (RemoteException e) {
4471                    Slog.w(TAG, e);
4472                }
4473            }
4474        });
4475    }
4476
4477    @Override
4478    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4479            final int storageFlags, final IntentSender pi) {
4480        mContext.enforceCallingOrSelfPermission(
4481                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4482        mHandler.post(() -> {
4483            boolean success = false;
4484            try {
4485                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4486                success = true;
4487            } catch (IOException e) {
4488                Slog.w(TAG, e);
4489            }
4490            if (pi != null) {
4491                try {
4492                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4493                } catch (SendIntentException e) {
4494                    Slog.w(TAG, e);
4495                }
4496            }
4497        });
4498    }
4499
4500    /**
4501     * Blocking call to clear various types of cached data across the system
4502     * until the requested bytes are available.
4503     */
4504    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4505        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4506        final File file = storage.findPathForUuid(volumeUuid);
4507        if (file.getUsableSpace() >= bytes) return;
4508
4509        if (ENABLE_FREE_CACHE_V2) {
4510            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4511                    volumeUuid);
4512            final boolean aggressive = (storageFlags
4513                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4514            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4515
4516            // 1. Pre-flight to determine if we have any chance to succeed
4517            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4518            if (internalVolume && (aggressive || SystemProperties
4519                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4520                deletePreloadsFileCache();
4521                if (file.getUsableSpace() >= bytes) return;
4522            }
4523
4524            // 3. Consider parsed APK data (aggressive only)
4525            if (internalVolume && aggressive) {
4526                FileUtils.deleteContents(mCacheDir);
4527                if (file.getUsableSpace() >= bytes) return;
4528            }
4529
4530            // 4. Consider cached app data (above quotas)
4531            try {
4532                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4533                        Installer.FLAG_FREE_CACHE_V2);
4534            } catch (InstallerException ignored) {
4535            }
4536            if (file.getUsableSpace() >= bytes) return;
4537
4538            // 5. Consider shared libraries with refcount=0 and age>min cache period
4539            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4540                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4541                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4542                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4543                return;
4544            }
4545
4546            // 6. Consider dexopt output (aggressive only)
4547            // TODO: Implement
4548
4549            // 7. Consider installed instant apps unused longer than min cache period
4550            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4551                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4552                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4553                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4554                return;
4555            }
4556
4557            // 8. Consider cached app data (below quotas)
4558            try {
4559                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4560                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4561            } catch (InstallerException ignored) {
4562            }
4563            if (file.getUsableSpace() >= bytes) return;
4564
4565            // 9. Consider DropBox entries
4566            // TODO: Implement
4567
4568            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4569            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4570                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4571                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4572                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4573                return;
4574            }
4575        } else {
4576            try {
4577                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4578            } catch (InstallerException ignored) {
4579            }
4580            if (file.getUsableSpace() >= bytes) return;
4581        }
4582
4583        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4584    }
4585
4586    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4587            throws IOException {
4588        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4589        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4590
4591        List<VersionedPackage> packagesToDelete = null;
4592        final long now = System.currentTimeMillis();
4593
4594        synchronized (mPackages) {
4595            final int[] allUsers = sUserManager.getUserIds();
4596            final int libCount = mSharedLibraries.size();
4597            for (int i = 0; i < libCount; i++) {
4598                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4599                if (versionedLib == null) {
4600                    continue;
4601                }
4602                final int versionCount = versionedLib.size();
4603                for (int j = 0; j < versionCount; j++) {
4604                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4605                    // Skip packages that are not static shared libs.
4606                    if (!libInfo.isStatic()) {
4607                        break;
4608                    }
4609                    // Important: We skip static shared libs used for some user since
4610                    // in such a case we need to keep the APK on the device. The check for
4611                    // a lib being used for any user is performed by the uninstall call.
4612                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4613                    // Resolve the package name - we use synthetic package names internally
4614                    final String internalPackageName = resolveInternalPackageNameLPr(
4615                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4616                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4617                    // Skip unused static shared libs cached less than the min period
4618                    // to prevent pruning a lib needed by a subsequently installed package.
4619                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4620                        continue;
4621                    }
4622                    if (packagesToDelete == null) {
4623                        packagesToDelete = new ArrayList<>();
4624                    }
4625                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4626                            declaringPackage.getVersionCode()));
4627                }
4628            }
4629        }
4630
4631        if (packagesToDelete != null) {
4632            final int packageCount = packagesToDelete.size();
4633            for (int i = 0; i < packageCount; i++) {
4634                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4635                // Delete the package synchronously (will fail of the lib used for any user).
4636                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4637                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4638                                == PackageManager.DELETE_SUCCEEDED) {
4639                    if (volume.getUsableSpace() >= neededSpace) {
4640                        return true;
4641                    }
4642                }
4643            }
4644        }
4645
4646        return false;
4647    }
4648
4649    /**
4650     * Update given flags based on encryption status of current user.
4651     */
4652    private int updateFlags(int flags, int userId) {
4653        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4654                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4655            // Caller expressed an explicit opinion about what encryption
4656            // aware/unaware components they want to see, so fall through and
4657            // give them what they want
4658        } else {
4659            // Caller expressed no opinion, so match based on user state
4660            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4661                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4662            } else {
4663                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4664            }
4665        }
4666        return flags;
4667    }
4668
4669    private UserManagerInternal getUserManagerInternal() {
4670        if (mUserManagerInternal == null) {
4671            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4672        }
4673        return mUserManagerInternal;
4674    }
4675
4676    private DeviceIdleController.LocalService getDeviceIdleController() {
4677        if (mDeviceIdleController == null) {
4678            mDeviceIdleController =
4679                    LocalServices.getService(DeviceIdleController.LocalService.class);
4680        }
4681        return mDeviceIdleController;
4682    }
4683
4684    /**
4685     * Update given flags when being used to request {@link PackageInfo}.
4686     */
4687    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4688        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4689        boolean triaged = true;
4690        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4691                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4692            // Caller is asking for component details, so they'd better be
4693            // asking for specific encryption matching behavior, or be triaged
4694            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4695                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4696                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4697                triaged = false;
4698            }
4699        }
4700        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4701                | PackageManager.MATCH_SYSTEM_ONLY
4702                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4703            triaged = false;
4704        }
4705        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4706            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4707                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4708                    + Debug.getCallers(5));
4709        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4710                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4711            // If the caller wants all packages and has a restricted profile associated with it,
4712            // then match all users. This is to make sure that launchers that need to access work
4713            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4714            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4715            flags |= PackageManager.MATCH_ANY_USER;
4716        }
4717        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4718            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4719                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4720        }
4721        return updateFlags(flags, userId);
4722    }
4723
4724    /**
4725     * Update given flags when being used to request {@link ApplicationInfo}.
4726     */
4727    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4728        return updateFlagsForPackage(flags, userId, cookie);
4729    }
4730
4731    /**
4732     * Update given flags when being used to request {@link ComponentInfo}.
4733     */
4734    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4735        if (cookie instanceof Intent) {
4736            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4737                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4738            }
4739        }
4740
4741        boolean triaged = true;
4742        // Caller is asking for component details, so they'd better be
4743        // asking for specific encryption matching behavior, or be triaged
4744        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4745                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4746                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4747            triaged = false;
4748        }
4749        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4750            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4751                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4752        }
4753
4754        return updateFlags(flags, userId);
4755    }
4756
4757    /**
4758     * Update given intent when being used to request {@link ResolveInfo}.
4759     */
4760    private Intent updateIntentForResolve(Intent intent) {
4761        if (intent.getSelector() != null) {
4762            intent = intent.getSelector();
4763        }
4764        if (DEBUG_PREFERRED) {
4765            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4766        }
4767        return intent;
4768    }
4769
4770    /**
4771     * Update given flags when being used to request {@link ResolveInfo}.
4772     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4773     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4774     * flag set. However, this flag is only honoured in three circumstances:
4775     * <ul>
4776     * <li>when called from a system process</li>
4777     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4778     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4779     * action and a {@code android.intent.category.BROWSABLE} category</li>
4780     * </ul>
4781     */
4782    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4783        return updateFlagsForResolve(flags, userId, intent, callingUid,
4784                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4785    }
4786    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4787            boolean wantInstantApps) {
4788        return updateFlagsForResolve(flags, userId, intent, callingUid,
4789                wantInstantApps, false /*onlyExposedExplicitly*/);
4790    }
4791    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4792            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4793        // Safe mode means we shouldn't match any third-party components
4794        if (mSafeMode) {
4795            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4796        }
4797        if (getInstantAppPackageName(callingUid) != null) {
4798            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4799            if (onlyExposedExplicitly) {
4800                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4801            }
4802            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4803            flags |= PackageManager.MATCH_INSTANT;
4804        } else {
4805            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4806            final boolean allowMatchInstant =
4807                    (wantInstantApps
4808                            && Intent.ACTION_VIEW.equals(intent.getAction())
4809                            && hasWebURI(intent))
4810                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4811            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4812                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4813            if (!allowMatchInstant) {
4814                flags &= ~PackageManager.MATCH_INSTANT;
4815            }
4816        }
4817        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4818    }
4819
4820    @Override
4821    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4822        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4823    }
4824
4825    /**
4826     * Important: The provided filterCallingUid is used exclusively to filter out activities
4827     * that can be seen based on user state. It's typically the original caller uid prior
4828     * to clearing. Because it can only be provided by trusted code, it's value can be
4829     * trusted and will be used as-is; unlike userId which will be validated by this method.
4830     */
4831    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4832            int filterCallingUid, int userId) {
4833        if (!sUserManager.exists(userId)) return null;
4834        flags = updateFlagsForComponent(flags, userId, component);
4835        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4836                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4837        synchronized (mPackages) {
4838            PackageParser.Activity a = mActivities.mActivities.get(component);
4839
4840            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4841            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4842                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4843                if (ps == null) return null;
4844                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4845                    return null;
4846                }
4847                return PackageParser.generateActivityInfo(
4848                        a, flags, ps.readUserState(userId), userId);
4849            }
4850            if (mResolveComponentName.equals(component)) {
4851                return PackageParser.generateActivityInfo(
4852                        mResolveActivity, flags, new PackageUserState(), userId);
4853            }
4854        }
4855        return null;
4856    }
4857
4858    @Override
4859    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4860            String resolvedType) {
4861        synchronized (mPackages) {
4862            if (component.equals(mResolveComponentName)) {
4863                // The resolver supports EVERYTHING!
4864                return true;
4865            }
4866            final int callingUid = Binder.getCallingUid();
4867            final int callingUserId = UserHandle.getUserId(callingUid);
4868            PackageParser.Activity a = mActivities.mActivities.get(component);
4869            if (a == null) {
4870                return false;
4871            }
4872            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4873            if (ps == null) {
4874                return false;
4875            }
4876            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4877                return false;
4878            }
4879            for (int i=0; i<a.intents.size(); i++) {
4880                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4881                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4882                    return true;
4883                }
4884            }
4885            return false;
4886        }
4887    }
4888
4889    @Override
4890    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4891        if (!sUserManager.exists(userId)) return null;
4892        final int callingUid = Binder.getCallingUid();
4893        flags = updateFlagsForComponent(flags, userId, component);
4894        enforceCrossUserPermission(callingUid, userId,
4895                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4896        synchronized (mPackages) {
4897            PackageParser.Activity a = mReceivers.mActivities.get(component);
4898            if (DEBUG_PACKAGE_INFO) Log.v(
4899                TAG, "getReceiverInfo " + component + ": " + a);
4900            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4901                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4902                if (ps == null) return null;
4903                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4904                    return null;
4905                }
4906                return PackageParser.generateActivityInfo(
4907                        a, flags, ps.readUserState(userId), userId);
4908            }
4909        }
4910        return null;
4911    }
4912
4913    @Override
4914    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4915            int flags, int userId) {
4916        if (!sUserManager.exists(userId)) return null;
4917        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4918        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4919            return null;
4920        }
4921
4922        flags = updateFlagsForPackage(flags, userId, null);
4923
4924        final boolean canSeeStaticLibraries =
4925                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4926                        == PERMISSION_GRANTED
4927                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4928                        == PERMISSION_GRANTED
4929                || canRequestPackageInstallsInternal(packageName,
4930                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4931                        false  /* throwIfPermNotDeclared*/)
4932                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4933                        == PERMISSION_GRANTED;
4934
4935        synchronized (mPackages) {
4936            List<SharedLibraryInfo> result = null;
4937
4938            final int libCount = mSharedLibraries.size();
4939            for (int i = 0; i < libCount; i++) {
4940                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4941                if (versionedLib == null) {
4942                    continue;
4943                }
4944
4945                final int versionCount = versionedLib.size();
4946                for (int j = 0; j < versionCount; j++) {
4947                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4948                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4949                        break;
4950                    }
4951                    final long identity = Binder.clearCallingIdentity();
4952                    try {
4953                        PackageInfo packageInfo = getPackageInfoVersioned(
4954                                libInfo.getDeclaringPackage(), flags
4955                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4956                        if (packageInfo == null) {
4957                            continue;
4958                        }
4959                    } finally {
4960                        Binder.restoreCallingIdentity(identity);
4961                    }
4962
4963                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4964                            libInfo.getVersion(), libInfo.getType(),
4965                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4966                            flags, userId));
4967
4968                    if (result == null) {
4969                        result = new ArrayList<>();
4970                    }
4971                    result.add(resLibInfo);
4972                }
4973            }
4974
4975            return result != null ? new ParceledListSlice<>(result) : null;
4976        }
4977    }
4978
4979    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4980            SharedLibraryInfo libInfo, int flags, int userId) {
4981        List<VersionedPackage> versionedPackages = null;
4982        final int packageCount = mSettings.mPackages.size();
4983        for (int i = 0; i < packageCount; i++) {
4984            PackageSetting ps = mSettings.mPackages.valueAt(i);
4985
4986            if (ps == null) {
4987                continue;
4988            }
4989
4990            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4991                continue;
4992            }
4993
4994            final String libName = libInfo.getName();
4995            if (libInfo.isStatic()) {
4996                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4997                if (libIdx < 0) {
4998                    continue;
4999                }
5000                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5001                    continue;
5002                }
5003                if (versionedPackages == null) {
5004                    versionedPackages = new ArrayList<>();
5005                }
5006                // If the dependent is a static shared lib, use the public package name
5007                String dependentPackageName = ps.name;
5008                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5009                    dependentPackageName = ps.pkg.manifestPackageName;
5010                }
5011                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5012            } else if (ps.pkg != null) {
5013                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5014                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5015                    if (versionedPackages == null) {
5016                        versionedPackages = new ArrayList<>();
5017                    }
5018                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5019                }
5020            }
5021        }
5022
5023        return versionedPackages;
5024    }
5025
5026    @Override
5027    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5028        if (!sUserManager.exists(userId)) return null;
5029        final int callingUid = Binder.getCallingUid();
5030        flags = updateFlagsForComponent(flags, userId, component);
5031        enforceCrossUserPermission(callingUid, userId,
5032                false /* requireFullPermission */, false /* checkShell */, "get service info");
5033        synchronized (mPackages) {
5034            PackageParser.Service s = mServices.mServices.get(component);
5035            if (DEBUG_PACKAGE_INFO) Log.v(
5036                TAG, "getServiceInfo " + component + ": " + s);
5037            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5038                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5039                if (ps == null) return null;
5040                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5041                    return null;
5042                }
5043                return PackageParser.generateServiceInfo(
5044                        s, flags, ps.readUserState(userId), userId);
5045            }
5046        }
5047        return null;
5048    }
5049
5050    @Override
5051    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5052        if (!sUserManager.exists(userId)) return null;
5053        final int callingUid = Binder.getCallingUid();
5054        flags = updateFlagsForComponent(flags, userId, component);
5055        enforceCrossUserPermission(callingUid, userId,
5056                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5057        synchronized (mPackages) {
5058            PackageParser.Provider p = mProviders.mProviders.get(component);
5059            if (DEBUG_PACKAGE_INFO) Log.v(
5060                TAG, "getProviderInfo " + component + ": " + p);
5061            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5062                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5063                if (ps == null) return null;
5064                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5065                    return null;
5066                }
5067                return PackageParser.generateProviderInfo(
5068                        p, flags, ps.readUserState(userId), userId);
5069            }
5070        }
5071        return null;
5072    }
5073
5074    @Override
5075    public String[] getSystemSharedLibraryNames() {
5076        // allow instant applications
5077        synchronized (mPackages) {
5078            Set<String> libs = null;
5079            final int libCount = mSharedLibraries.size();
5080            for (int i = 0; i < libCount; i++) {
5081                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5082                if (versionedLib == null) {
5083                    continue;
5084                }
5085                final int versionCount = versionedLib.size();
5086                for (int j = 0; j < versionCount; j++) {
5087                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5088                    if (!libEntry.info.isStatic()) {
5089                        if (libs == null) {
5090                            libs = new ArraySet<>();
5091                        }
5092                        libs.add(libEntry.info.getName());
5093                        break;
5094                    }
5095                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5096                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5097                            UserHandle.getUserId(Binder.getCallingUid()),
5098                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5099                        if (libs == null) {
5100                            libs = new ArraySet<>();
5101                        }
5102                        libs.add(libEntry.info.getName());
5103                        break;
5104                    }
5105                }
5106            }
5107
5108            if (libs != null) {
5109                String[] libsArray = new String[libs.size()];
5110                libs.toArray(libsArray);
5111                return libsArray;
5112            }
5113
5114            return null;
5115        }
5116    }
5117
5118    @Override
5119    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5120        // allow instant applications
5121        synchronized (mPackages) {
5122            return mServicesSystemSharedLibraryPackageName;
5123        }
5124    }
5125
5126    @Override
5127    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5128        // allow instant applications
5129        synchronized (mPackages) {
5130            return mSharedSystemSharedLibraryPackageName;
5131        }
5132    }
5133
5134    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5135        for (int i = userList.length - 1; i >= 0; --i) {
5136            final int userId = userList[i];
5137            // don't add instant app to the list of updates
5138            if (pkgSetting.getInstantApp(userId)) {
5139                continue;
5140            }
5141            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5142            if (changedPackages == null) {
5143                changedPackages = new SparseArray<>();
5144                mChangedPackages.put(userId, changedPackages);
5145            }
5146            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5147            if (sequenceNumbers == null) {
5148                sequenceNumbers = new HashMap<>();
5149                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5150            }
5151            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5152            if (sequenceNumber != null) {
5153                changedPackages.remove(sequenceNumber);
5154            }
5155            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5156            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5157        }
5158        mChangedPackagesSequenceNumber++;
5159    }
5160
5161    @Override
5162    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5163        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5164            return null;
5165        }
5166        synchronized (mPackages) {
5167            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5168                return null;
5169            }
5170            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5171            if (changedPackages == null) {
5172                return null;
5173            }
5174            final List<String> packageNames =
5175                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5176            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5177                final String packageName = changedPackages.get(i);
5178                if (packageName != null) {
5179                    packageNames.add(packageName);
5180                }
5181            }
5182            return packageNames.isEmpty()
5183                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5184        }
5185    }
5186
5187    @Override
5188    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5189        // allow instant applications
5190        ArrayList<FeatureInfo> res;
5191        synchronized (mAvailableFeatures) {
5192            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5193            res.addAll(mAvailableFeatures.values());
5194        }
5195        final FeatureInfo fi = new FeatureInfo();
5196        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5197                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5198        res.add(fi);
5199
5200        return new ParceledListSlice<>(res);
5201    }
5202
5203    @Override
5204    public boolean hasSystemFeature(String name, int version) {
5205        // allow instant applications
5206        synchronized (mAvailableFeatures) {
5207            final FeatureInfo feat = mAvailableFeatures.get(name);
5208            if (feat == null) {
5209                return false;
5210            } else {
5211                return feat.version >= version;
5212            }
5213        }
5214    }
5215
5216    @Override
5217    public int checkPermission(String permName, String pkgName, int userId) {
5218        if (!sUserManager.exists(userId)) {
5219            return PackageManager.PERMISSION_DENIED;
5220        }
5221        final int callingUid = Binder.getCallingUid();
5222
5223        synchronized (mPackages) {
5224            final PackageParser.Package p = mPackages.get(pkgName);
5225            if (p != null && p.mExtras != null) {
5226                final PackageSetting ps = (PackageSetting) p.mExtras;
5227                if (filterAppAccessLPr(ps, callingUid, userId)) {
5228                    return PackageManager.PERMISSION_DENIED;
5229                }
5230                final boolean instantApp = ps.getInstantApp(userId);
5231                final PermissionsState permissionsState = ps.getPermissionsState();
5232                if (permissionsState.hasPermission(permName, userId)) {
5233                    if (instantApp) {
5234                        BasePermission bp = mSettings.mPermissions.get(permName);
5235                        if (bp != null && bp.isInstant()) {
5236                            return PackageManager.PERMISSION_GRANTED;
5237                        }
5238                    } else {
5239                        return PackageManager.PERMISSION_GRANTED;
5240                    }
5241                }
5242                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5243                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5244                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5245                    return PackageManager.PERMISSION_GRANTED;
5246                }
5247            }
5248        }
5249
5250        return PackageManager.PERMISSION_DENIED;
5251    }
5252
5253    @Override
5254    public int checkUidPermission(String permName, int uid) {
5255        final int callingUid = Binder.getCallingUid();
5256        final int callingUserId = UserHandle.getUserId(callingUid);
5257        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5258        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5259        final int userId = UserHandle.getUserId(uid);
5260        if (!sUserManager.exists(userId)) {
5261            return PackageManager.PERMISSION_DENIED;
5262        }
5263
5264        synchronized (mPackages) {
5265            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5266            if (obj != null) {
5267                if (obj instanceof SharedUserSetting) {
5268                    if (isCallerInstantApp) {
5269                        return PackageManager.PERMISSION_DENIED;
5270                    }
5271                } else if (obj instanceof PackageSetting) {
5272                    final PackageSetting ps = (PackageSetting) obj;
5273                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5274                        return PackageManager.PERMISSION_DENIED;
5275                    }
5276                }
5277                final SettingBase settingBase = (SettingBase) obj;
5278                final PermissionsState permissionsState = settingBase.getPermissionsState();
5279                if (permissionsState.hasPermission(permName, userId)) {
5280                    if (isUidInstantApp) {
5281                        BasePermission bp = mSettings.mPermissions.get(permName);
5282                        if (bp != null && bp.isInstant()) {
5283                            return PackageManager.PERMISSION_GRANTED;
5284                        }
5285                    } else {
5286                        return PackageManager.PERMISSION_GRANTED;
5287                    }
5288                }
5289                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5290                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5291                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5292                    return PackageManager.PERMISSION_GRANTED;
5293                }
5294            } else {
5295                ArraySet<String> perms = mSystemPermissions.get(uid);
5296                if (perms != null) {
5297                    if (perms.contains(permName)) {
5298                        return PackageManager.PERMISSION_GRANTED;
5299                    }
5300                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5301                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5302                        return PackageManager.PERMISSION_GRANTED;
5303                    }
5304                }
5305            }
5306        }
5307
5308        return PackageManager.PERMISSION_DENIED;
5309    }
5310
5311    @Override
5312    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5313        if (UserHandle.getCallingUserId() != userId) {
5314            mContext.enforceCallingPermission(
5315                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5316                    "isPermissionRevokedByPolicy for user " + userId);
5317        }
5318
5319        if (checkPermission(permission, packageName, userId)
5320                == PackageManager.PERMISSION_GRANTED) {
5321            return false;
5322        }
5323
5324        final int callingUid = Binder.getCallingUid();
5325        if (getInstantAppPackageName(callingUid) != null) {
5326            if (!isCallerSameApp(packageName, callingUid)) {
5327                return false;
5328            }
5329        } else {
5330            if (isInstantApp(packageName, userId)) {
5331                return false;
5332            }
5333        }
5334
5335        final long identity = Binder.clearCallingIdentity();
5336        try {
5337            final int flags = getPermissionFlags(permission, packageName, userId);
5338            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5339        } finally {
5340            Binder.restoreCallingIdentity(identity);
5341        }
5342    }
5343
5344    @Override
5345    public String getPermissionControllerPackageName() {
5346        synchronized (mPackages) {
5347            return mRequiredInstallerPackage;
5348        }
5349    }
5350
5351    /**
5352     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5353     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5354     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5355     * @param message the message to log on security exception
5356     */
5357    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5358            boolean checkShell, String message) {
5359        if (userId < 0) {
5360            throw new IllegalArgumentException("Invalid userId " + userId);
5361        }
5362        if (checkShell) {
5363            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5364        }
5365        if (userId == UserHandle.getUserId(callingUid)) return;
5366        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5367            if (requireFullPermission) {
5368                mContext.enforceCallingOrSelfPermission(
5369                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5370            } else {
5371                try {
5372                    mContext.enforceCallingOrSelfPermission(
5373                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5374                } catch (SecurityException se) {
5375                    mContext.enforceCallingOrSelfPermission(
5376                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5377                }
5378            }
5379        }
5380    }
5381
5382    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5383        if (callingUid == Process.SHELL_UID) {
5384            if (userHandle >= 0
5385                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5386                throw new SecurityException("Shell does not have permission to access user "
5387                        + userHandle);
5388            } else if (userHandle < 0) {
5389                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5390                        + Debug.getCallers(3));
5391            }
5392        }
5393    }
5394
5395    private BasePermission findPermissionTreeLP(String permName) {
5396        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5397            if (permName.startsWith(bp.name) &&
5398                    permName.length() > bp.name.length() &&
5399                    permName.charAt(bp.name.length()) == '.') {
5400                return bp;
5401            }
5402        }
5403        return null;
5404    }
5405
5406    private BasePermission checkPermissionTreeLP(String permName) {
5407        if (permName != null) {
5408            BasePermission bp = findPermissionTreeLP(permName);
5409            if (bp != null) {
5410                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5411                    return bp;
5412                }
5413                throw new SecurityException("Calling uid "
5414                        + Binder.getCallingUid()
5415                        + " is not allowed to add to permission tree "
5416                        + bp.name + " owned by uid " + bp.uid);
5417            }
5418        }
5419        throw new SecurityException("No permission tree found for " + permName);
5420    }
5421
5422    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5423        if (s1 == null) {
5424            return s2 == null;
5425        }
5426        if (s2 == null) {
5427            return false;
5428        }
5429        if (s1.getClass() != s2.getClass()) {
5430            return false;
5431        }
5432        return s1.equals(s2);
5433    }
5434
5435    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5436        if (pi1.icon != pi2.icon) return false;
5437        if (pi1.logo != pi2.logo) return false;
5438        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5439        if (!compareStrings(pi1.name, pi2.name)) return false;
5440        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5441        // We'll take care of setting this one.
5442        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5443        // These are not currently stored in settings.
5444        //if (!compareStrings(pi1.group, pi2.group)) return false;
5445        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5446        //if (pi1.labelRes != pi2.labelRes) return false;
5447        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5448        return true;
5449    }
5450
5451    int permissionInfoFootprint(PermissionInfo info) {
5452        int size = info.name.length();
5453        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5454        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5455        return size;
5456    }
5457
5458    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5459        int size = 0;
5460        for (BasePermission perm : mSettings.mPermissions.values()) {
5461            if (perm.uid == tree.uid) {
5462                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5463            }
5464        }
5465        return size;
5466    }
5467
5468    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5469        // We calculate the max size of permissions defined by this uid and throw
5470        // if that plus the size of 'info' would exceed our stated maximum.
5471        if (tree.uid != Process.SYSTEM_UID) {
5472            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5473            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5474                throw new SecurityException("Permission tree size cap exceeded");
5475            }
5476        }
5477    }
5478
5479    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5480        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5481            throw new SecurityException("Instant apps can't add permissions");
5482        }
5483        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5484            throw new SecurityException("Label must be specified in permission");
5485        }
5486        BasePermission tree = checkPermissionTreeLP(info.name);
5487        BasePermission bp = mSettings.mPermissions.get(info.name);
5488        boolean added = bp == null;
5489        boolean changed = true;
5490        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5491        if (added) {
5492            enforcePermissionCapLocked(info, tree);
5493            bp = new BasePermission(info.name, tree.sourcePackage,
5494                    BasePermission.TYPE_DYNAMIC);
5495        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5496            throw new SecurityException(
5497                    "Not allowed to modify non-dynamic permission "
5498                    + info.name);
5499        } else {
5500            if (bp.protectionLevel == fixedLevel
5501                    && bp.perm.owner.equals(tree.perm.owner)
5502                    && bp.uid == tree.uid
5503                    && comparePermissionInfos(bp.perm.info, info)) {
5504                changed = false;
5505            }
5506        }
5507        bp.protectionLevel = fixedLevel;
5508        info = new PermissionInfo(info);
5509        info.protectionLevel = fixedLevel;
5510        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5511        bp.perm.info.packageName = tree.perm.info.packageName;
5512        bp.uid = tree.uid;
5513        if (added) {
5514            mSettings.mPermissions.put(info.name, bp);
5515        }
5516        if (changed) {
5517            if (!async) {
5518                mSettings.writeLPr();
5519            } else {
5520                scheduleWriteSettingsLocked();
5521            }
5522        }
5523        return added;
5524    }
5525
5526    @Override
5527    public boolean addPermission(PermissionInfo info) {
5528        synchronized (mPackages) {
5529            return addPermissionLocked(info, false);
5530        }
5531    }
5532
5533    @Override
5534    public boolean addPermissionAsync(PermissionInfo info) {
5535        synchronized (mPackages) {
5536            return addPermissionLocked(info, true);
5537        }
5538    }
5539
5540    @Override
5541    public void removePermission(String name) {
5542        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5543            throw new SecurityException("Instant applications don't have access to this method");
5544        }
5545        synchronized (mPackages) {
5546            checkPermissionTreeLP(name);
5547            BasePermission bp = mSettings.mPermissions.get(name);
5548            if (bp != null) {
5549                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5550                    throw new SecurityException(
5551                            "Not allowed to modify non-dynamic permission "
5552                            + name);
5553                }
5554                mSettings.mPermissions.remove(name);
5555                mSettings.writeLPr();
5556            }
5557        }
5558    }
5559
5560    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5561            PackageParser.Package pkg, BasePermission bp) {
5562        int index = pkg.requestedPermissions.indexOf(bp.name);
5563        if (index == -1) {
5564            throw new SecurityException("Package " + pkg.packageName
5565                    + " has not requested permission " + bp.name);
5566        }
5567        if (!bp.isRuntime() && !bp.isDevelopment()) {
5568            throw new SecurityException("Permission " + bp.name
5569                    + " is not a changeable permission type");
5570        }
5571    }
5572
5573    @Override
5574    public void grantRuntimePermission(String packageName, String name, final int userId) {
5575        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5576    }
5577
5578    private void grantRuntimePermission(String packageName, String name, final int userId,
5579            boolean overridePolicy) {
5580        if (!sUserManager.exists(userId)) {
5581            Log.e(TAG, "No such user:" + userId);
5582            return;
5583        }
5584        final int callingUid = Binder.getCallingUid();
5585
5586        mContext.enforceCallingOrSelfPermission(
5587                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5588                "grantRuntimePermission");
5589
5590        enforceCrossUserPermission(callingUid, userId,
5591                true /* requireFullPermission */, true /* checkShell */,
5592                "grantRuntimePermission");
5593
5594        final int uid;
5595        final PackageSetting ps;
5596
5597        synchronized (mPackages) {
5598            final PackageParser.Package pkg = mPackages.get(packageName);
5599            if (pkg == null) {
5600                throw new IllegalArgumentException("Unknown package: " + packageName);
5601            }
5602            final BasePermission bp = mSettings.mPermissions.get(name);
5603            if (bp == null) {
5604                throw new IllegalArgumentException("Unknown permission: " + name);
5605            }
5606            ps = (PackageSetting) pkg.mExtras;
5607            if (ps == null
5608                    || filterAppAccessLPr(ps, callingUid, userId)) {
5609                throw new IllegalArgumentException("Unknown package: " + packageName);
5610            }
5611
5612            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5613
5614            // If a permission review is required for legacy apps we represent
5615            // their permissions as always granted runtime ones since we need
5616            // to keep the review required permission flag per user while an
5617            // install permission's state is shared across all users.
5618            if (mPermissionReviewRequired
5619                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5620                    && bp.isRuntime()) {
5621                return;
5622            }
5623
5624            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5625
5626            final PermissionsState permissionsState = ps.getPermissionsState();
5627
5628            final int flags = permissionsState.getPermissionFlags(name, userId);
5629            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5630                throw new SecurityException("Cannot grant system fixed permission "
5631                        + name + " for package " + packageName);
5632            }
5633            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5634                throw new SecurityException("Cannot grant policy fixed permission "
5635                        + name + " for package " + packageName);
5636            }
5637
5638            if (bp.isDevelopment()) {
5639                // Development permissions must be handled specially, since they are not
5640                // normal runtime permissions.  For now they apply to all users.
5641                if (permissionsState.grantInstallPermission(bp) !=
5642                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5643                    scheduleWriteSettingsLocked();
5644                }
5645                return;
5646            }
5647
5648            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5649                throw new SecurityException("Cannot grant non-ephemeral permission"
5650                        + name + " for package " + packageName);
5651            }
5652
5653            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5654                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5655                return;
5656            }
5657
5658            final int result = permissionsState.grantRuntimePermission(bp, userId);
5659            switch (result) {
5660                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5661                    return;
5662                }
5663
5664                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5665                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5666                    mHandler.post(new Runnable() {
5667                        @Override
5668                        public void run() {
5669                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5670                        }
5671                    });
5672                }
5673                break;
5674            }
5675
5676            if (bp.isRuntime()) {
5677                logPermissionGranted(mContext, name, packageName);
5678            }
5679
5680            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5681
5682            // Not critical if that is lost - app has to request again.
5683            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5684        }
5685
5686        // Only need to do this if user is initialized. Otherwise it's a new user
5687        // and there are no processes running as the user yet and there's no need
5688        // to make an expensive call to remount processes for the changed permissions.
5689        if (READ_EXTERNAL_STORAGE.equals(name)
5690                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5691            final long token = Binder.clearCallingIdentity();
5692            try {
5693                if (sUserManager.isInitialized(userId)) {
5694                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5695                            StorageManagerInternal.class);
5696                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5697                }
5698            } finally {
5699                Binder.restoreCallingIdentity(token);
5700            }
5701        }
5702    }
5703
5704    @Override
5705    public void revokeRuntimePermission(String packageName, String name, int userId) {
5706        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5707    }
5708
5709    private void revokeRuntimePermission(String packageName, String name, int userId,
5710            boolean overridePolicy) {
5711        if (!sUserManager.exists(userId)) {
5712            Log.e(TAG, "No such user:" + userId);
5713            return;
5714        }
5715
5716        mContext.enforceCallingOrSelfPermission(
5717                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5718                "revokeRuntimePermission");
5719
5720        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5721                true /* requireFullPermission */, true /* checkShell */,
5722                "revokeRuntimePermission");
5723
5724        final int appId;
5725
5726        synchronized (mPackages) {
5727            final PackageParser.Package pkg = mPackages.get(packageName);
5728            if (pkg == null) {
5729                throw new IllegalArgumentException("Unknown package: " + packageName);
5730            }
5731            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5732            if (ps == null
5733                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5734                throw new IllegalArgumentException("Unknown package: " + packageName);
5735            }
5736            final BasePermission bp = mSettings.mPermissions.get(name);
5737            if (bp == null) {
5738                throw new IllegalArgumentException("Unknown permission: " + name);
5739            }
5740
5741            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5742
5743            // If a permission review is required for legacy apps we represent
5744            // their permissions as always granted runtime ones since we need
5745            // to keep the review required permission flag per user while an
5746            // install permission's state is shared across all users.
5747            if (mPermissionReviewRequired
5748                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5749                    && bp.isRuntime()) {
5750                return;
5751            }
5752
5753            final PermissionsState permissionsState = ps.getPermissionsState();
5754
5755            final int flags = permissionsState.getPermissionFlags(name, userId);
5756            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5757                throw new SecurityException("Cannot revoke system fixed permission "
5758                        + name + " for package " + packageName);
5759            }
5760            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5761                throw new SecurityException("Cannot revoke policy fixed permission "
5762                        + name + " for package " + packageName);
5763            }
5764
5765            if (bp.isDevelopment()) {
5766                // Development permissions must be handled specially, since they are not
5767                // normal runtime permissions.  For now they apply to all users.
5768                if (permissionsState.revokeInstallPermission(bp) !=
5769                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5770                    scheduleWriteSettingsLocked();
5771                }
5772                return;
5773            }
5774
5775            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5776                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5777                return;
5778            }
5779
5780            if (bp.isRuntime()) {
5781                logPermissionRevoked(mContext, name, packageName);
5782            }
5783
5784            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5785
5786            // Critical, after this call app should never have the permission.
5787            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5788
5789            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5790        }
5791
5792        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5793    }
5794
5795    /**
5796     * Get the first event id for the permission.
5797     *
5798     * <p>There are four events for each permission: <ul>
5799     *     <li>Request permission: first id + 0</li>
5800     *     <li>Grant permission: first id + 1</li>
5801     *     <li>Request for permission denied: first id + 2</li>
5802     *     <li>Revoke permission: first id + 3</li>
5803     * </ul></p>
5804     *
5805     * @param name name of the permission
5806     *
5807     * @return The first event id for the permission
5808     */
5809    private static int getBaseEventId(@NonNull String name) {
5810        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5811
5812        if (eventIdIndex == -1) {
5813            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5814                    || Build.IS_USER) {
5815                Log.i(TAG, "Unknown permission " + name);
5816
5817                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5818            } else {
5819                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5820                //
5821                // Also update
5822                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5823                // - metrics_constants.proto
5824                throw new IllegalStateException("Unknown permission " + name);
5825            }
5826        }
5827
5828        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5829    }
5830
5831    /**
5832     * Log that a permission was revoked.
5833     *
5834     * @param context Context of the caller
5835     * @param name name of the permission
5836     * @param packageName package permission if for
5837     */
5838    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5839            @NonNull String packageName) {
5840        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5841    }
5842
5843    /**
5844     * Log that a permission request was granted.
5845     *
5846     * @param context Context of the caller
5847     * @param name name of the permission
5848     * @param packageName package permission if for
5849     */
5850    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5851            @NonNull String packageName) {
5852        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5853    }
5854
5855    @Override
5856    public void resetRuntimePermissions() {
5857        mContext.enforceCallingOrSelfPermission(
5858                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5859                "revokeRuntimePermission");
5860
5861        int callingUid = Binder.getCallingUid();
5862        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5863            mContext.enforceCallingOrSelfPermission(
5864                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5865                    "resetRuntimePermissions");
5866        }
5867
5868        synchronized (mPackages) {
5869            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5870            for (int userId : UserManagerService.getInstance().getUserIds()) {
5871                final int packageCount = mPackages.size();
5872                for (int i = 0; i < packageCount; i++) {
5873                    PackageParser.Package pkg = mPackages.valueAt(i);
5874                    if (!(pkg.mExtras instanceof PackageSetting)) {
5875                        continue;
5876                    }
5877                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5878                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5879                }
5880            }
5881        }
5882    }
5883
5884    @Override
5885    public int getPermissionFlags(String name, String packageName, int userId) {
5886        if (!sUserManager.exists(userId)) {
5887            return 0;
5888        }
5889
5890        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5891
5892        final int callingUid = Binder.getCallingUid();
5893        enforceCrossUserPermission(callingUid, userId,
5894                true /* requireFullPermission */, false /* checkShell */,
5895                "getPermissionFlags");
5896
5897        synchronized (mPackages) {
5898            final PackageParser.Package pkg = mPackages.get(packageName);
5899            if (pkg == null) {
5900                return 0;
5901            }
5902            final BasePermission bp = mSettings.mPermissions.get(name);
5903            if (bp == null) {
5904                return 0;
5905            }
5906            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5907            if (ps == null
5908                    || filterAppAccessLPr(ps, callingUid, userId)) {
5909                return 0;
5910            }
5911            PermissionsState permissionsState = ps.getPermissionsState();
5912            return permissionsState.getPermissionFlags(name, userId);
5913        }
5914    }
5915
5916    @Override
5917    public void updatePermissionFlags(String name, String packageName, int flagMask,
5918            int flagValues, int userId) {
5919        if (!sUserManager.exists(userId)) {
5920            return;
5921        }
5922
5923        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5924
5925        final int callingUid = Binder.getCallingUid();
5926        enforceCrossUserPermission(callingUid, userId,
5927                true /* requireFullPermission */, true /* checkShell */,
5928                "updatePermissionFlags");
5929
5930        // Only the system can change these flags and nothing else.
5931        if (getCallingUid() != Process.SYSTEM_UID) {
5932            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5933            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5934            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5935            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5936            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5937        }
5938
5939        synchronized (mPackages) {
5940            final PackageParser.Package pkg = mPackages.get(packageName);
5941            if (pkg == null) {
5942                throw new IllegalArgumentException("Unknown package: " + packageName);
5943            }
5944            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5945            if (ps == null
5946                    || filterAppAccessLPr(ps, callingUid, userId)) {
5947                throw new IllegalArgumentException("Unknown package: " + packageName);
5948            }
5949
5950            final BasePermission bp = mSettings.mPermissions.get(name);
5951            if (bp == null) {
5952                throw new IllegalArgumentException("Unknown permission: " + name);
5953            }
5954
5955            PermissionsState permissionsState = ps.getPermissionsState();
5956
5957            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5958
5959            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5960                // Install and runtime permissions are stored in different places,
5961                // so figure out what permission changed and persist the change.
5962                if (permissionsState.getInstallPermissionState(name) != null) {
5963                    scheduleWriteSettingsLocked();
5964                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5965                        || hadState) {
5966                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5967                }
5968            }
5969        }
5970    }
5971
5972    /**
5973     * Update the permission flags for all packages and runtime permissions of a user in order
5974     * to allow device or profile owner to remove POLICY_FIXED.
5975     */
5976    @Override
5977    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5978        if (!sUserManager.exists(userId)) {
5979            return;
5980        }
5981
5982        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5983
5984        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5985                true /* requireFullPermission */, true /* checkShell */,
5986                "updatePermissionFlagsForAllApps");
5987
5988        // Only the system can change system fixed flags.
5989        if (getCallingUid() != Process.SYSTEM_UID) {
5990            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5991            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5992        }
5993
5994        synchronized (mPackages) {
5995            boolean changed = false;
5996            final int packageCount = mPackages.size();
5997            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5998                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5999                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6000                if (ps == null) {
6001                    continue;
6002                }
6003                PermissionsState permissionsState = ps.getPermissionsState();
6004                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6005                        userId, flagMask, flagValues);
6006            }
6007            if (changed) {
6008                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6009            }
6010        }
6011    }
6012
6013    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6014        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6015                != PackageManager.PERMISSION_GRANTED
6016            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6017                != PackageManager.PERMISSION_GRANTED) {
6018            throw new SecurityException(message + " requires "
6019                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6020                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6021        }
6022    }
6023
6024    @Override
6025    public boolean shouldShowRequestPermissionRationale(String permissionName,
6026            String packageName, int userId) {
6027        if (UserHandle.getCallingUserId() != userId) {
6028            mContext.enforceCallingPermission(
6029                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6030                    "canShowRequestPermissionRationale for user " + userId);
6031        }
6032
6033        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6034        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6035            return false;
6036        }
6037
6038        if (checkPermission(permissionName, packageName, userId)
6039                == PackageManager.PERMISSION_GRANTED) {
6040            return false;
6041        }
6042
6043        final int flags;
6044
6045        final long identity = Binder.clearCallingIdentity();
6046        try {
6047            flags = getPermissionFlags(permissionName,
6048                    packageName, userId);
6049        } finally {
6050            Binder.restoreCallingIdentity(identity);
6051        }
6052
6053        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6054                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6055                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6056
6057        if ((flags & fixedFlags) != 0) {
6058            return false;
6059        }
6060
6061        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6062    }
6063
6064    @Override
6065    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6066        mContext.enforceCallingOrSelfPermission(
6067                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6068                "addOnPermissionsChangeListener");
6069
6070        synchronized (mPackages) {
6071            mOnPermissionChangeListeners.addListenerLocked(listener);
6072        }
6073    }
6074
6075    @Override
6076    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6077        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6078            throw new SecurityException("Instant applications don't have access to this method");
6079        }
6080        synchronized (mPackages) {
6081            mOnPermissionChangeListeners.removeListenerLocked(listener);
6082        }
6083    }
6084
6085    @Override
6086    public boolean isProtectedBroadcast(String actionName) {
6087        // allow instant applications
6088        synchronized (mProtectedBroadcasts) {
6089            if (mProtectedBroadcasts.contains(actionName)) {
6090                return true;
6091            } else if (actionName != null) {
6092                // TODO: remove these terrible hacks
6093                if (actionName.startsWith("android.net.netmon.lingerExpired")
6094                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6095                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6096                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6097                    return true;
6098                }
6099            }
6100        }
6101        return false;
6102    }
6103
6104    @Override
6105    public int checkSignatures(String pkg1, String pkg2) {
6106        synchronized (mPackages) {
6107            final PackageParser.Package p1 = mPackages.get(pkg1);
6108            final PackageParser.Package p2 = mPackages.get(pkg2);
6109            if (p1 == null || p1.mExtras == null
6110                    || p2 == null || p2.mExtras == null) {
6111                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6112            }
6113            final int callingUid = Binder.getCallingUid();
6114            final int callingUserId = UserHandle.getUserId(callingUid);
6115            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6116            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6117            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6118                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6119                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6120            }
6121            return compareSignatures(p1.mSignatures, p2.mSignatures);
6122        }
6123    }
6124
6125    @Override
6126    public int checkUidSignatures(int uid1, int uid2) {
6127        final int callingUid = Binder.getCallingUid();
6128        final int callingUserId = UserHandle.getUserId(callingUid);
6129        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6130        // Map to base uids.
6131        uid1 = UserHandle.getAppId(uid1);
6132        uid2 = UserHandle.getAppId(uid2);
6133        // reader
6134        synchronized (mPackages) {
6135            Signature[] s1;
6136            Signature[] s2;
6137            Object obj = mSettings.getUserIdLPr(uid1);
6138            if (obj != null) {
6139                if (obj instanceof SharedUserSetting) {
6140                    if (isCallerInstantApp) {
6141                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6142                    }
6143                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6144                } else if (obj instanceof PackageSetting) {
6145                    final PackageSetting ps = (PackageSetting) obj;
6146                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6147                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6148                    }
6149                    s1 = ps.signatures.mSignatures;
6150                } else {
6151                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6152                }
6153            } else {
6154                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6155            }
6156            obj = mSettings.getUserIdLPr(uid2);
6157            if (obj != null) {
6158                if (obj instanceof SharedUserSetting) {
6159                    if (isCallerInstantApp) {
6160                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6161                    }
6162                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6163                } else if (obj instanceof PackageSetting) {
6164                    final PackageSetting ps = (PackageSetting) obj;
6165                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6166                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6167                    }
6168                    s2 = ps.signatures.mSignatures;
6169                } else {
6170                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6171                }
6172            } else {
6173                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6174            }
6175            return compareSignatures(s1, s2);
6176        }
6177    }
6178
6179    /**
6180     * This method should typically only be used when granting or revoking
6181     * permissions, since the app may immediately restart after this call.
6182     * <p>
6183     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6184     * guard your work against the app being relaunched.
6185     */
6186    private void killUid(int appId, int userId, String reason) {
6187        final long identity = Binder.clearCallingIdentity();
6188        try {
6189            IActivityManager am = ActivityManager.getService();
6190            if (am != null) {
6191                try {
6192                    am.killUid(appId, userId, reason);
6193                } catch (RemoteException e) {
6194                    /* ignore - same process */
6195                }
6196            }
6197        } finally {
6198            Binder.restoreCallingIdentity(identity);
6199        }
6200    }
6201
6202    /**
6203     * Compares two sets of signatures. Returns:
6204     * <br />
6205     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6206     * <br />
6207     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6208     * <br />
6209     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6210     * <br />
6211     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6212     * <br />
6213     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6214     */
6215    static int compareSignatures(Signature[] s1, Signature[] s2) {
6216        if (s1 == null) {
6217            return s2 == null
6218                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6219                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6220        }
6221
6222        if (s2 == null) {
6223            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6224        }
6225
6226        if (s1.length != s2.length) {
6227            return PackageManager.SIGNATURE_NO_MATCH;
6228        }
6229
6230        // Since both signature sets are of size 1, we can compare without HashSets.
6231        if (s1.length == 1) {
6232            return s1[0].equals(s2[0]) ?
6233                    PackageManager.SIGNATURE_MATCH :
6234                    PackageManager.SIGNATURE_NO_MATCH;
6235        }
6236
6237        ArraySet<Signature> set1 = new ArraySet<Signature>();
6238        for (Signature sig : s1) {
6239            set1.add(sig);
6240        }
6241        ArraySet<Signature> set2 = new ArraySet<Signature>();
6242        for (Signature sig : s2) {
6243            set2.add(sig);
6244        }
6245        // Make sure s2 contains all signatures in s1.
6246        if (set1.equals(set2)) {
6247            return PackageManager.SIGNATURE_MATCH;
6248        }
6249        return PackageManager.SIGNATURE_NO_MATCH;
6250    }
6251
6252    /**
6253     * If the database version for this type of package (internal storage or
6254     * external storage) is less than the version where package signatures
6255     * were updated, return true.
6256     */
6257    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6258        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6259        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6260    }
6261
6262    /**
6263     * Used for backward compatibility to make sure any packages with
6264     * certificate chains get upgraded to the new style. {@code existingSigs}
6265     * will be in the old format (since they were stored on disk from before the
6266     * system upgrade) and {@code scannedSigs} will be in the newer format.
6267     */
6268    private int compareSignaturesCompat(PackageSignatures existingSigs,
6269            PackageParser.Package scannedPkg) {
6270        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6271            return PackageManager.SIGNATURE_NO_MATCH;
6272        }
6273
6274        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6275        for (Signature sig : existingSigs.mSignatures) {
6276            existingSet.add(sig);
6277        }
6278        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6279        for (Signature sig : scannedPkg.mSignatures) {
6280            try {
6281                Signature[] chainSignatures = sig.getChainSignatures();
6282                for (Signature chainSig : chainSignatures) {
6283                    scannedCompatSet.add(chainSig);
6284                }
6285            } catch (CertificateEncodingException e) {
6286                scannedCompatSet.add(sig);
6287            }
6288        }
6289        /*
6290         * Make sure the expanded scanned set contains all signatures in the
6291         * existing one.
6292         */
6293        if (scannedCompatSet.equals(existingSet)) {
6294            // Migrate the old signatures to the new scheme.
6295            existingSigs.assignSignatures(scannedPkg.mSignatures);
6296            // The new KeySets will be re-added later in the scanning process.
6297            synchronized (mPackages) {
6298                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6299            }
6300            return PackageManager.SIGNATURE_MATCH;
6301        }
6302        return PackageManager.SIGNATURE_NO_MATCH;
6303    }
6304
6305    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6306        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6307        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6308    }
6309
6310    private int compareSignaturesRecover(PackageSignatures existingSigs,
6311            PackageParser.Package scannedPkg) {
6312        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6313            return PackageManager.SIGNATURE_NO_MATCH;
6314        }
6315
6316        String msg = null;
6317        try {
6318            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6319                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6320                        + scannedPkg.packageName);
6321                return PackageManager.SIGNATURE_MATCH;
6322            }
6323        } catch (CertificateException e) {
6324            msg = e.getMessage();
6325        }
6326
6327        logCriticalInfo(Log.INFO,
6328                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6329        return PackageManager.SIGNATURE_NO_MATCH;
6330    }
6331
6332    @Override
6333    public List<String> getAllPackages() {
6334        final int callingUid = Binder.getCallingUid();
6335        final int callingUserId = UserHandle.getUserId(callingUid);
6336        synchronized (mPackages) {
6337            if (canViewInstantApps(callingUid, callingUserId)) {
6338                return new ArrayList<String>(mPackages.keySet());
6339            }
6340            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6341            final List<String> result = new ArrayList<>();
6342            if (instantAppPkgName != null) {
6343                // caller is an instant application; filter unexposed applications
6344                for (PackageParser.Package pkg : mPackages.values()) {
6345                    if (!pkg.visibleToInstantApps) {
6346                        continue;
6347                    }
6348                    result.add(pkg.packageName);
6349                }
6350            } else {
6351                // caller is a normal application; filter instant applications
6352                for (PackageParser.Package pkg : mPackages.values()) {
6353                    final PackageSetting ps =
6354                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6355                    if (ps != null
6356                            && ps.getInstantApp(callingUserId)
6357                            && !mInstantAppRegistry.isInstantAccessGranted(
6358                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6359                        continue;
6360                    }
6361                    result.add(pkg.packageName);
6362                }
6363            }
6364            return result;
6365        }
6366    }
6367
6368    @Override
6369    public String[] getPackagesForUid(int uid) {
6370        final int callingUid = Binder.getCallingUid();
6371        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6372        final int userId = UserHandle.getUserId(uid);
6373        uid = UserHandle.getAppId(uid);
6374        // reader
6375        synchronized (mPackages) {
6376            Object obj = mSettings.getUserIdLPr(uid);
6377            if (obj instanceof SharedUserSetting) {
6378                if (isCallerInstantApp) {
6379                    return null;
6380                }
6381                final SharedUserSetting sus = (SharedUserSetting) obj;
6382                final int N = sus.packages.size();
6383                String[] res = new String[N];
6384                final Iterator<PackageSetting> it = sus.packages.iterator();
6385                int i = 0;
6386                while (it.hasNext()) {
6387                    PackageSetting ps = it.next();
6388                    if (ps.getInstalled(userId)) {
6389                        res[i++] = ps.name;
6390                    } else {
6391                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6392                    }
6393                }
6394                return res;
6395            } else if (obj instanceof PackageSetting) {
6396                final PackageSetting ps = (PackageSetting) obj;
6397                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6398                    return new String[]{ps.name};
6399                }
6400            }
6401        }
6402        return null;
6403    }
6404
6405    @Override
6406    public String getNameForUid(int uid) {
6407        final int callingUid = Binder.getCallingUid();
6408        if (getInstantAppPackageName(callingUid) != null) {
6409            return null;
6410        }
6411        synchronized (mPackages) {
6412            return getNameForUidLocked(callingUid, uid);
6413        }
6414    }
6415
6416    @Override
6417    public String[] getNamesForUids(int[] uids) {
6418        if (uids == null || uids.length == 0) {
6419            return null;
6420        }
6421        final int callingUid = Binder.getCallingUid();
6422        if (getInstantAppPackageName(callingUid) != null) {
6423            return null;
6424        }
6425        final String[] names = new String[uids.length];
6426        synchronized (mPackages) {
6427            for (int i = uids.length - 1; i >= 0; i--) {
6428                final int uid = uids[i];
6429                names[i] = getNameForUidLocked(callingUid, uid);
6430            }
6431        }
6432        return names;
6433    }
6434
6435    private String getNameForUidLocked(int callingUid, int uid) {
6436        Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6437        if (obj instanceof SharedUserSetting) {
6438            final SharedUserSetting sus = (SharedUserSetting) obj;
6439            return sus.name + ":" + sus.userId;
6440        } else if (obj instanceof PackageSetting) {
6441            final PackageSetting ps = (PackageSetting) obj;
6442            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6443                return null;
6444            }
6445            return ps.name;
6446        }
6447        return null;
6448    }
6449
6450    @Override
6451    public int getUidForSharedUser(String sharedUserName) {
6452        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6453            return -1;
6454        }
6455        if (sharedUserName == null) {
6456            return -1;
6457        }
6458        // reader
6459        synchronized (mPackages) {
6460            SharedUserSetting suid;
6461            try {
6462                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6463                if (suid != null) {
6464                    return suid.userId;
6465                }
6466            } catch (PackageManagerException ignore) {
6467                // can't happen, but, still need to catch it
6468            }
6469            return -1;
6470        }
6471    }
6472
6473    @Override
6474    public int getFlagsForUid(int uid) {
6475        final int callingUid = Binder.getCallingUid();
6476        if (getInstantAppPackageName(callingUid) != null) {
6477            return 0;
6478        }
6479        synchronized (mPackages) {
6480            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6481            if (obj instanceof SharedUserSetting) {
6482                final SharedUserSetting sus = (SharedUserSetting) obj;
6483                return sus.pkgFlags;
6484            } else if (obj instanceof PackageSetting) {
6485                final PackageSetting ps = (PackageSetting) obj;
6486                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6487                    return 0;
6488                }
6489                return ps.pkgFlags;
6490            }
6491        }
6492        return 0;
6493    }
6494
6495    @Override
6496    public int getPrivateFlagsForUid(int uid) {
6497        final int callingUid = Binder.getCallingUid();
6498        if (getInstantAppPackageName(callingUid) != null) {
6499            return 0;
6500        }
6501        synchronized (mPackages) {
6502            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6503            if (obj instanceof SharedUserSetting) {
6504                final SharedUserSetting sus = (SharedUserSetting) obj;
6505                return sus.pkgPrivateFlags;
6506            } else if (obj instanceof PackageSetting) {
6507                final PackageSetting ps = (PackageSetting) obj;
6508                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6509                    return 0;
6510                }
6511                return ps.pkgPrivateFlags;
6512            }
6513        }
6514        return 0;
6515    }
6516
6517    @Override
6518    public boolean isUidPrivileged(int uid) {
6519        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6520            return false;
6521        }
6522        uid = UserHandle.getAppId(uid);
6523        // reader
6524        synchronized (mPackages) {
6525            Object obj = mSettings.getUserIdLPr(uid);
6526            if (obj instanceof SharedUserSetting) {
6527                final SharedUserSetting sus = (SharedUserSetting) obj;
6528                final Iterator<PackageSetting> it = sus.packages.iterator();
6529                while (it.hasNext()) {
6530                    if (it.next().isPrivileged()) {
6531                        return true;
6532                    }
6533                }
6534            } else if (obj instanceof PackageSetting) {
6535                final PackageSetting ps = (PackageSetting) obj;
6536                return ps.isPrivileged();
6537            }
6538        }
6539        return false;
6540    }
6541
6542    @Override
6543    public String[] getAppOpPermissionPackages(String permissionName) {
6544        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6545            return null;
6546        }
6547        synchronized (mPackages) {
6548            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6549            if (pkgs == null) {
6550                return null;
6551            }
6552            return pkgs.toArray(new String[pkgs.size()]);
6553        }
6554    }
6555
6556    @Override
6557    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6558            int flags, int userId) {
6559        return resolveIntentInternal(
6560                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6561    }
6562
6563    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6564            int flags, int userId, boolean resolveForStart) {
6565        try {
6566            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6567
6568            if (!sUserManager.exists(userId)) return null;
6569            final int callingUid = Binder.getCallingUid();
6570            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6571            enforceCrossUserPermission(callingUid, userId,
6572                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6573
6574            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6575            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6576                    flags, callingUid, userId, resolveForStart);
6577            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6578
6579            final ResolveInfo bestChoice =
6580                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6581            return bestChoice;
6582        } finally {
6583            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6584        }
6585    }
6586
6587    @Override
6588    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6589        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6590            throw new SecurityException(
6591                    "findPersistentPreferredActivity can only be run by the system");
6592        }
6593        if (!sUserManager.exists(userId)) {
6594            return null;
6595        }
6596        final int callingUid = Binder.getCallingUid();
6597        intent = updateIntentForResolve(intent);
6598        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6599        final int flags = updateFlagsForResolve(
6600                0, userId, intent, callingUid, false /*includeInstantApps*/);
6601        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6602                userId);
6603        synchronized (mPackages) {
6604            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6605                    userId);
6606        }
6607    }
6608
6609    @Override
6610    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6611            IntentFilter filter, int match, ComponentName activity) {
6612        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6613            return;
6614        }
6615        final int userId = UserHandle.getCallingUserId();
6616        if (DEBUG_PREFERRED) {
6617            Log.v(TAG, "setLastChosenActivity intent=" + intent
6618                + " resolvedType=" + resolvedType
6619                + " flags=" + flags
6620                + " filter=" + filter
6621                + " match=" + match
6622                + " activity=" + activity);
6623            filter.dump(new PrintStreamPrinter(System.out), "    ");
6624        }
6625        intent.setComponent(null);
6626        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6627                userId);
6628        // Find any earlier preferred or last chosen entries and nuke them
6629        findPreferredActivity(intent, resolvedType,
6630                flags, query, 0, false, true, false, userId);
6631        // Add the new activity as the last chosen for this filter
6632        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6633                "Setting last chosen");
6634    }
6635
6636    @Override
6637    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6638        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6639            return null;
6640        }
6641        final int userId = UserHandle.getCallingUserId();
6642        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6643        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6644                userId);
6645        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6646                false, false, false, userId);
6647    }
6648
6649    /**
6650     * Returns whether or not instant apps have been disabled remotely.
6651     */
6652    private boolean isEphemeralDisabled() {
6653        return mEphemeralAppsDisabled;
6654    }
6655
6656    private boolean isInstantAppAllowed(
6657            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6658            boolean skipPackageCheck) {
6659        if (mInstantAppResolverConnection == null) {
6660            return false;
6661        }
6662        if (mInstantAppInstallerActivity == null) {
6663            return false;
6664        }
6665        if (intent.getComponent() != null) {
6666            return false;
6667        }
6668        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6669            return false;
6670        }
6671        if (!skipPackageCheck && intent.getPackage() != null) {
6672            return false;
6673        }
6674        final boolean isWebUri = hasWebURI(intent);
6675        if (!isWebUri || intent.getData().getHost() == null) {
6676            return false;
6677        }
6678        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6679        // Or if there's already an ephemeral app installed that handles the action
6680        synchronized (mPackages) {
6681            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6682            for (int n = 0; n < count; n++) {
6683                final ResolveInfo info = resolvedActivities.get(n);
6684                final String packageName = info.activityInfo.packageName;
6685                final PackageSetting ps = mSettings.mPackages.get(packageName);
6686                if (ps != null) {
6687                    // only check domain verification status if the app is not a browser
6688                    if (!info.handleAllWebDataURI) {
6689                        // Try to get the status from User settings first
6690                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6691                        final int status = (int) (packedStatus >> 32);
6692                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6693                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6694                            if (DEBUG_EPHEMERAL) {
6695                                Slog.v(TAG, "DENY instant app;"
6696                                    + " pkg: " + packageName + ", status: " + status);
6697                            }
6698                            return false;
6699                        }
6700                    }
6701                    if (ps.getInstantApp(userId)) {
6702                        if (DEBUG_EPHEMERAL) {
6703                            Slog.v(TAG, "DENY instant app installed;"
6704                                    + " pkg: " + packageName);
6705                        }
6706                        return false;
6707                    }
6708                }
6709            }
6710        }
6711        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6712        return true;
6713    }
6714
6715    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6716            Intent origIntent, String resolvedType, String callingPackage,
6717            Bundle verificationBundle, int userId) {
6718        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6719                new InstantAppRequest(responseObj, origIntent, resolvedType,
6720                        callingPackage, userId, verificationBundle));
6721        mHandler.sendMessage(msg);
6722    }
6723
6724    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6725            int flags, List<ResolveInfo> query, int userId) {
6726        if (query != null) {
6727            final int N = query.size();
6728            if (N == 1) {
6729                return query.get(0);
6730            } else if (N > 1) {
6731                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6732                // If there is more than one activity with the same priority,
6733                // then let the user decide between them.
6734                ResolveInfo r0 = query.get(0);
6735                ResolveInfo r1 = query.get(1);
6736                if (DEBUG_INTENT_MATCHING || debug) {
6737                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6738                            + r1.activityInfo.name + "=" + r1.priority);
6739                }
6740                // If the first activity has a higher priority, or a different
6741                // default, then it is always desirable to pick it.
6742                if (r0.priority != r1.priority
6743                        || r0.preferredOrder != r1.preferredOrder
6744                        || r0.isDefault != r1.isDefault) {
6745                    return query.get(0);
6746                }
6747                // If we have saved a preference for a preferred activity for
6748                // this Intent, use that.
6749                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6750                        flags, query, r0.priority, true, false, debug, userId);
6751                if (ri != null) {
6752                    return ri;
6753                }
6754                // If we have an ephemeral app, use it
6755                for (int i = 0; i < N; i++) {
6756                    ri = query.get(i);
6757                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6758                        final String packageName = ri.activityInfo.packageName;
6759                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6760                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6761                        final int status = (int)(packedStatus >> 32);
6762                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6763                            return ri;
6764                        }
6765                    }
6766                }
6767                ri = new ResolveInfo(mResolveInfo);
6768                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6769                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6770                // If all of the options come from the same package, show the application's
6771                // label and icon instead of the generic resolver's.
6772                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6773                // and then throw away the ResolveInfo itself, meaning that the caller loses
6774                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6775                // a fallback for this case; we only set the target package's resources on
6776                // the ResolveInfo, not the ActivityInfo.
6777                final String intentPackage = intent.getPackage();
6778                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6779                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6780                    ri.resolvePackageName = intentPackage;
6781                    if (userNeedsBadging(userId)) {
6782                        ri.noResourceId = true;
6783                    } else {
6784                        ri.icon = appi.icon;
6785                    }
6786                    ri.iconResourceId = appi.icon;
6787                    ri.labelRes = appi.labelRes;
6788                }
6789                ri.activityInfo.applicationInfo = new ApplicationInfo(
6790                        ri.activityInfo.applicationInfo);
6791                if (userId != 0) {
6792                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6793                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6794                }
6795                // Make sure that the resolver is displayable in car mode
6796                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6797                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6798                return ri;
6799            }
6800        }
6801        return null;
6802    }
6803
6804    /**
6805     * Return true if the given list is not empty and all of its contents have
6806     * an activityInfo with the given package name.
6807     */
6808    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6809        if (ArrayUtils.isEmpty(list)) {
6810            return false;
6811        }
6812        for (int i = 0, N = list.size(); i < N; i++) {
6813            final ResolveInfo ri = list.get(i);
6814            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6815            if (ai == null || !packageName.equals(ai.packageName)) {
6816                return false;
6817            }
6818        }
6819        return true;
6820    }
6821
6822    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6823            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6824        final int N = query.size();
6825        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6826                .get(userId);
6827        // Get the list of persistent preferred activities that handle the intent
6828        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6829        List<PersistentPreferredActivity> pprefs = ppir != null
6830                ? ppir.queryIntent(intent, resolvedType,
6831                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6832                        userId)
6833                : null;
6834        if (pprefs != null && pprefs.size() > 0) {
6835            final int M = pprefs.size();
6836            for (int i=0; i<M; i++) {
6837                final PersistentPreferredActivity ppa = pprefs.get(i);
6838                if (DEBUG_PREFERRED || debug) {
6839                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6840                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6841                            + "\n  component=" + ppa.mComponent);
6842                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6843                }
6844                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6845                        flags | MATCH_DISABLED_COMPONENTS, userId);
6846                if (DEBUG_PREFERRED || debug) {
6847                    Slog.v(TAG, "Found persistent preferred activity:");
6848                    if (ai != null) {
6849                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6850                    } else {
6851                        Slog.v(TAG, "  null");
6852                    }
6853                }
6854                if (ai == null) {
6855                    // This previously registered persistent preferred activity
6856                    // component is no longer known. Ignore it and do NOT remove it.
6857                    continue;
6858                }
6859                for (int j=0; j<N; j++) {
6860                    final ResolveInfo ri = query.get(j);
6861                    if (!ri.activityInfo.applicationInfo.packageName
6862                            .equals(ai.applicationInfo.packageName)) {
6863                        continue;
6864                    }
6865                    if (!ri.activityInfo.name.equals(ai.name)) {
6866                        continue;
6867                    }
6868                    //  Found a persistent preference that can handle the intent.
6869                    if (DEBUG_PREFERRED || debug) {
6870                        Slog.v(TAG, "Returning persistent preferred activity: " +
6871                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6872                    }
6873                    return ri;
6874                }
6875            }
6876        }
6877        return null;
6878    }
6879
6880    // TODO: handle preferred activities missing while user has amnesia
6881    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6882            List<ResolveInfo> query, int priority, boolean always,
6883            boolean removeMatches, boolean debug, int userId) {
6884        if (!sUserManager.exists(userId)) return null;
6885        final int callingUid = Binder.getCallingUid();
6886        flags = updateFlagsForResolve(
6887                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6888        intent = updateIntentForResolve(intent);
6889        // writer
6890        synchronized (mPackages) {
6891            // Try to find a matching persistent preferred activity.
6892            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6893                    debug, userId);
6894
6895            // If a persistent preferred activity matched, use it.
6896            if (pri != null) {
6897                return pri;
6898            }
6899
6900            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6901            // Get the list of preferred activities that handle the intent
6902            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6903            List<PreferredActivity> prefs = pir != null
6904                    ? pir.queryIntent(intent, resolvedType,
6905                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6906                            userId)
6907                    : null;
6908            if (prefs != null && prefs.size() > 0) {
6909                boolean changed = false;
6910                try {
6911                    // First figure out how good the original match set is.
6912                    // We will only allow preferred activities that came
6913                    // from the same match quality.
6914                    int match = 0;
6915
6916                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6917
6918                    final int N = query.size();
6919                    for (int j=0; j<N; j++) {
6920                        final ResolveInfo ri = query.get(j);
6921                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6922                                + ": 0x" + Integer.toHexString(match));
6923                        if (ri.match > match) {
6924                            match = ri.match;
6925                        }
6926                    }
6927
6928                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6929                            + Integer.toHexString(match));
6930
6931                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6932                    final int M = prefs.size();
6933                    for (int i=0; i<M; i++) {
6934                        final PreferredActivity pa = prefs.get(i);
6935                        if (DEBUG_PREFERRED || debug) {
6936                            Slog.v(TAG, "Checking PreferredActivity ds="
6937                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6938                                    + "\n  component=" + pa.mPref.mComponent);
6939                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6940                        }
6941                        if (pa.mPref.mMatch != match) {
6942                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6943                                    + Integer.toHexString(pa.mPref.mMatch));
6944                            continue;
6945                        }
6946                        // If it's not an "always" type preferred activity and that's what we're
6947                        // looking for, skip it.
6948                        if (always && !pa.mPref.mAlways) {
6949                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6950                            continue;
6951                        }
6952                        final ActivityInfo ai = getActivityInfo(
6953                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6954                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6955                                userId);
6956                        if (DEBUG_PREFERRED || debug) {
6957                            Slog.v(TAG, "Found preferred activity:");
6958                            if (ai != null) {
6959                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6960                            } else {
6961                                Slog.v(TAG, "  null");
6962                            }
6963                        }
6964                        if (ai == null) {
6965                            // This previously registered preferred activity
6966                            // component is no longer known.  Most likely an update
6967                            // to the app was installed and in the new version this
6968                            // component no longer exists.  Clean it up by removing
6969                            // it from the preferred activities list, and skip it.
6970                            Slog.w(TAG, "Removing dangling preferred activity: "
6971                                    + pa.mPref.mComponent);
6972                            pir.removeFilter(pa);
6973                            changed = true;
6974                            continue;
6975                        }
6976                        for (int j=0; j<N; j++) {
6977                            final ResolveInfo ri = query.get(j);
6978                            if (!ri.activityInfo.applicationInfo.packageName
6979                                    .equals(ai.applicationInfo.packageName)) {
6980                                continue;
6981                            }
6982                            if (!ri.activityInfo.name.equals(ai.name)) {
6983                                continue;
6984                            }
6985
6986                            if (removeMatches) {
6987                                pir.removeFilter(pa);
6988                                changed = true;
6989                                if (DEBUG_PREFERRED) {
6990                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6991                                }
6992                                break;
6993                            }
6994
6995                            // Okay we found a previously set preferred or last chosen app.
6996                            // If the result set is different from when this
6997                            // was created, we need to clear it and re-ask the
6998                            // user their preference, if we're looking for an "always" type entry.
6999                            if (always && !pa.mPref.sameSet(query)) {
7000                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
7001                                        + intent + " type " + resolvedType);
7002                                if (DEBUG_PREFERRED) {
7003                                    Slog.v(TAG, "Removing preferred activity since set changed "
7004                                            + pa.mPref.mComponent);
7005                                }
7006                                pir.removeFilter(pa);
7007                                // Re-add the filter as a "last chosen" entry (!always)
7008                                PreferredActivity lastChosen = new PreferredActivity(
7009                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7010                                pir.addFilter(lastChosen);
7011                                changed = true;
7012                                return null;
7013                            }
7014
7015                            // Yay! Either the set matched or we're looking for the last chosen
7016                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7017                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7018                            return ri;
7019                        }
7020                    }
7021                } finally {
7022                    if (changed) {
7023                        if (DEBUG_PREFERRED) {
7024                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7025                        }
7026                        scheduleWritePackageRestrictionsLocked(userId);
7027                    }
7028                }
7029            }
7030        }
7031        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7032        return null;
7033    }
7034
7035    /*
7036     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7037     */
7038    @Override
7039    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7040            int targetUserId) {
7041        mContext.enforceCallingOrSelfPermission(
7042                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7043        List<CrossProfileIntentFilter> matches =
7044                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7045        if (matches != null) {
7046            int size = matches.size();
7047            for (int i = 0; i < size; i++) {
7048                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7049            }
7050        }
7051        if (hasWebURI(intent)) {
7052            // cross-profile app linking works only towards the parent.
7053            final int callingUid = Binder.getCallingUid();
7054            final UserInfo parent = getProfileParent(sourceUserId);
7055            synchronized(mPackages) {
7056                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7057                        false /*includeInstantApps*/);
7058                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7059                        intent, resolvedType, flags, sourceUserId, parent.id);
7060                return xpDomainInfo != null;
7061            }
7062        }
7063        return false;
7064    }
7065
7066    private UserInfo getProfileParent(int userId) {
7067        final long identity = Binder.clearCallingIdentity();
7068        try {
7069            return sUserManager.getProfileParent(userId);
7070        } finally {
7071            Binder.restoreCallingIdentity(identity);
7072        }
7073    }
7074
7075    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7076            String resolvedType, int userId) {
7077        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7078        if (resolver != null) {
7079            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7080        }
7081        return null;
7082    }
7083
7084    @Override
7085    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7086            String resolvedType, int flags, int userId) {
7087        try {
7088            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7089
7090            return new ParceledListSlice<>(
7091                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7092        } finally {
7093            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7094        }
7095    }
7096
7097    /**
7098     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7099     * instant, returns {@code null}.
7100     */
7101    private String getInstantAppPackageName(int callingUid) {
7102        synchronized (mPackages) {
7103            // If the caller is an isolated app use the owner's uid for the lookup.
7104            if (Process.isIsolated(callingUid)) {
7105                callingUid = mIsolatedOwners.get(callingUid);
7106            }
7107            final int appId = UserHandle.getAppId(callingUid);
7108            final Object obj = mSettings.getUserIdLPr(appId);
7109            if (obj instanceof PackageSetting) {
7110                final PackageSetting ps = (PackageSetting) obj;
7111                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7112                return isInstantApp ? ps.pkg.packageName : null;
7113            }
7114        }
7115        return null;
7116    }
7117
7118    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7119            String resolvedType, int flags, int userId) {
7120        return queryIntentActivitiesInternal(
7121                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
7122    }
7123
7124    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7125            String resolvedType, int flags, int filterCallingUid, int userId,
7126            boolean resolveForStart) {
7127        if (!sUserManager.exists(userId)) return Collections.emptyList();
7128        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7129        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7130                false /* requireFullPermission */, false /* checkShell */,
7131                "query intent activities");
7132        final String pkgName = intent.getPackage();
7133        ComponentName comp = intent.getComponent();
7134        if (comp == null) {
7135            if (intent.getSelector() != null) {
7136                intent = intent.getSelector();
7137                comp = intent.getComponent();
7138            }
7139        }
7140
7141        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7142                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7143        if (comp != null) {
7144            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7145            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7146            if (ai != null) {
7147                // When specifying an explicit component, we prevent the activity from being
7148                // used when either 1) the calling package is normal and the activity is within
7149                // an ephemeral application or 2) the calling package is ephemeral and the
7150                // activity is not visible to ephemeral applications.
7151                final boolean matchInstantApp =
7152                        (flags & PackageManager.MATCH_INSTANT) != 0;
7153                final boolean matchVisibleToInstantAppOnly =
7154                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7155                final boolean matchExplicitlyVisibleOnly =
7156                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7157                final boolean isCallerInstantApp =
7158                        instantAppPkgName != null;
7159                final boolean isTargetSameInstantApp =
7160                        comp.getPackageName().equals(instantAppPkgName);
7161                final boolean isTargetInstantApp =
7162                        (ai.applicationInfo.privateFlags
7163                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7164                final boolean isTargetVisibleToInstantApp =
7165                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7166                final boolean isTargetExplicitlyVisibleToInstantApp =
7167                        isTargetVisibleToInstantApp
7168                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7169                final boolean isTargetHiddenFromInstantApp =
7170                        !isTargetVisibleToInstantApp
7171                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7172                final boolean blockResolution =
7173                        !isTargetSameInstantApp
7174                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7175                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7176                                        && isTargetHiddenFromInstantApp));
7177                if (!blockResolution) {
7178                    final ResolveInfo ri = new ResolveInfo();
7179                    ri.activityInfo = ai;
7180                    list.add(ri);
7181                }
7182            }
7183            return applyPostResolutionFilter(list, instantAppPkgName);
7184        }
7185
7186        // reader
7187        boolean sortResult = false;
7188        boolean addEphemeral = false;
7189        List<ResolveInfo> result;
7190        final boolean ephemeralDisabled = isEphemeralDisabled();
7191        synchronized (mPackages) {
7192            if (pkgName == null) {
7193                List<CrossProfileIntentFilter> matchingFilters =
7194                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7195                // Check for results that need to skip the current profile.
7196                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7197                        resolvedType, flags, userId);
7198                if (xpResolveInfo != null) {
7199                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7200                    xpResult.add(xpResolveInfo);
7201                    return applyPostResolutionFilter(
7202                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
7203                }
7204
7205                // Check for results in the current profile.
7206                result = filterIfNotSystemUser(mActivities.queryIntent(
7207                        intent, resolvedType, flags, userId), userId);
7208                addEphemeral = !ephemeralDisabled
7209                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7210                // Check for cross profile results.
7211                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7212                xpResolveInfo = queryCrossProfileIntents(
7213                        matchingFilters, intent, resolvedType, flags, userId,
7214                        hasNonNegativePriorityResult);
7215                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7216                    boolean isVisibleToUser = filterIfNotSystemUser(
7217                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7218                    if (isVisibleToUser) {
7219                        result.add(xpResolveInfo);
7220                        sortResult = true;
7221                    }
7222                }
7223                if (hasWebURI(intent)) {
7224                    CrossProfileDomainInfo xpDomainInfo = null;
7225                    final UserInfo parent = getProfileParent(userId);
7226                    if (parent != null) {
7227                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7228                                flags, userId, parent.id);
7229                    }
7230                    if (xpDomainInfo != null) {
7231                        if (xpResolveInfo != null) {
7232                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7233                            // in the result.
7234                            result.remove(xpResolveInfo);
7235                        }
7236                        if (result.size() == 0 && !addEphemeral) {
7237                            // No result in current profile, but found candidate in parent user.
7238                            // And we are not going to add emphemeral app, so we can return the
7239                            // result straight away.
7240                            result.add(xpDomainInfo.resolveInfo);
7241                            return applyPostResolutionFilter(result, instantAppPkgName);
7242                        }
7243                    } else if (result.size() <= 1 && !addEphemeral) {
7244                        // No result in parent user and <= 1 result in current profile, and we
7245                        // are not going to add emphemeral app, so we can return the result without
7246                        // further processing.
7247                        return applyPostResolutionFilter(result, instantAppPkgName);
7248                    }
7249                    // We have more than one candidate (combining results from current and parent
7250                    // profile), so we need filtering and sorting.
7251                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7252                            intent, flags, result, xpDomainInfo, userId);
7253                    sortResult = true;
7254                }
7255            } else {
7256                final PackageParser.Package pkg = mPackages.get(pkgName);
7257                result = null;
7258                if (pkg != null) {
7259                    result = filterIfNotSystemUser(
7260                            mActivities.queryIntentForPackage(
7261                                    intent, resolvedType, flags, pkg.activities, userId),
7262                            userId);
7263                }
7264                if (result == null || result.size() == 0) {
7265                    // the caller wants to resolve for a particular package; however, there
7266                    // were no installed results, so, try to find an ephemeral result
7267                    addEphemeral = !ephemeralDisabled
7268                            && isInstantAppAllowed(
7269                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7270                    if (result == null) {
7271                        result = new ArrayList<>();
7272                    }
7273                }
7274            }
7275        }
7276        if (addEphemeral) {
7277            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7278        }
7279        if (sortResult) {
7280            Collections.sort(result, mResolvePrioritySorter);
7281        }
7282        return applyPostResolutionFilter(result, instantAppPkgName);
7283    }
7284
7285    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7286            String resolvedType, int flags, int userId) {
7287        // first, check to see if we've got an instant app already installed
7288        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7289        ResolveInfo localInstantApp = null;
7290        boolean blockResolution = false;
7291        if (!alreadyResolvedLocally) {
7292            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7293                    flags
7294                        | PackageManager.GET_RESOLVED_FILTER
7295                        | PackageManager.MATCH_INSTANT
7296                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7297                    userId);
7298            for (int i = instantApps.size() - 1; i >= 0; --i) {
7299                final ResolveInfo info = instantApps.get(i);
7300                final String packageName = info.activityInfo.packageName;
7301                final PackageSetting ps = mSettings.mPackages.get(packageName);
7302                if (ps.getInstantApp(userId)) {
7303                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7304                    final int status = (int)(packedStatus >> 32);
7305                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7306                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7307                        // there's a local instant application installed, but, the user has
7308                        // chosen to never use it; skip resolution and don't acknowledge
7309                        // an instant application is even available
7310                        if (DEBUG_EPHEMERAL) {
7311                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7312                        }
7313                        blockResolution = true;
7314                        break;
7315                    } else {
7316                        // we have a locally installed instant application; skip resolution
7317                        // but acknowledge there's an instant application available
7318                        if (DEBUG_EPHEMERAL) {
7319                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7320                        }
7321                        localInstantApp = info;
7322                        break;
7323                    }
7324                }
7325            }
7326        }
7327        // no app installed, let's see if one's available
7328        AuxiliaryResolveInfo auxiliaryResponse = null;
7329        if (!blockResolution) {
7330            if (localInstantApp == null) {
7331                // we don't have an instant app locally, resolve externally
7332                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7333                final InstantAppRequest requestObject = new InstantAppRequest(
7334                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7335                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7336                auxiliaryResponse =
7337                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7338                                mContext, mInstantAppResolverConnection, requestObject);
7339                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7340            } else {
7341                // we have an instant application locally, but, we can't admit that since
7342                // callers shouldn't be able to determine prior browsing. create a dummy
7343                // auxiliary response so the downstream code behaves as if there's an
7344                // instant application available externally. when it comes time to start
7345                // the instant application, we'll do the right thing.
7346                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7347                auxiliaryResponse = new AuxiliaryResolveInfo(
7348                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7349            }
7350        }
7351        if (auxiliaryResponse != null) {
7352            if (DEBUG_EPHEMERAL) {
7353                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7354            }
7355            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7356            final PackageSetting ps =
7357                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7358            if (ps != null) {
7359                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7360                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7361                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7362                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7363                // make sure this resolver is the default
7364                ephemeralInstaller.isDefault = true;
7365                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7366                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7367                // add a non-generic filter
7368                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7369                ephemeralInstaller.filter.addDataPath(
7370                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7371                ephemeralInstaller.isInstantAppAvailable = true;
7372                result.add(ephemeralInstaller);
7373            }
7374        }
7375        return result;
7376    }
7377
7378    private static class CrossProfileDomainInfo {
7379        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7380        ResolveInfo resolveInfo;
7381        /* Best domain verification status of the activities found in the other profile */
7382        int bestDomainVerificationStatus;
7383    }
7384
7385    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7386            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7387        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7388                sourceUserId)) {
7389            return null;
7390        }
7391        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7392                resolvedType, flags, parentUserId);
7393
7394        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7395            return null;
7396        }
7397        CrossProfileDomainInfo result = null;
7398        int size = resultTargetUser.size();
7399        for (int i = 0; i < size; i++) {
7400            ResolveInfo riTargetUser = resultTargetUser.get(i);
7401            // Intent filter verification is only for filters that specify a host. So don't return
7402            // those that handle all web uris.
7403            if (riTargetUser.handleAllWebDataURI) {
7404                continue;
7405            }
7406            String packageName = riTargetUser.activityInfo.packageName;
7407            PackageSetting ps = mSettings.mPackages.get(packageName);
7408            if (ps == null) {
7409                continue;
7410            }
7411            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7412            int status = (int)(verificationState >> 32);
7413            if (result == null) {
7414                result = new CrossProfileDomainInfo();
7415                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7416                        sourceUserId, parentUserId);
7417                result.bestDomainVerificationStatus = status;
7418            } else {
7419                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7420                        result.bestDomainVerificationStatus);
7421            }
7422        }
7423        // Don't consider matches with status NEVER across profiles.
7424        if (result != null && result.bestDomainVerificationStatus
7425                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7426            return null;
7427        }
7428        return result;
7429    }
7430
7431    /**
7432     * Verification statuses are ordered from the worse to the best, except for
7433     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7434     */
7435    private int bestDomainVerificationStatus(int status1, int status2) {
7436        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7437            return status2;
7438        }
7439        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7440            return status1;
7441        }
7442        return (int) MathUtils.max(status1, status2);
7443    }
7444
7445    private boolean isUserEnabled(int userId) {
7446        long callingId = Binder.clearCallingIdentity();
7447        try {
7448            UserInfo userInfo = sUserManager.getUserInfo(userId);
7449            return userInfo != null && userInfo.isEnabled();
7450        } finally {
7451            Binder.restoreCallingIdentity(callingId);
7452        }
7453    }
7454
7455    /**
7456     * Filter out activities with systemUserOnly flag set, when current user is not System.
7457     *
7458     * @return filtered list
7459     */
7460    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7461        if (userId == UserHandle.USER_SYSTEM) {
7462            return resolveInfos;
7463        }
7464        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7465            ResolveInfo info = resolveInfos.get(i);
7466            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7467                resolveInfos.remove(i);
7468            }
7469        }
7470        return resolveInfos;
7471    }
7472
7473    /**
7474     * Filters out ephemeral activities.
7475     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7476     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7477     *
7478     * @param resolveInfos The pre-filtered list of resolved activities
7479     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7480     *          is performed.
7481     * @return A filtered list of resolved activities.
7482     */
7483    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7484            String ephemeralPkgName) {
7485        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7486            final ResolveInfo info = resolveInfos.get(i);
7487            // TODO: When adding on-demand split support for non-instant apps, remove this check
7488            // and always apply post filtering
7489            // allow activities that are defined in the provided package
7490            if (info.activityInfo.splitName != null
7491                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7492                            info.activityInfo.splitName)) {
7493                // requested activity is defined in a split that hasn't been installed yet.
7494                // add the installer to the resolve list
7495                if (DEBUG_INSTALL) {
7496                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7497                }
7498                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7499                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7500                        info.activityInfo.packageName, info.activityInfo.splitName,
7501                        info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7502                // make sure this resolver is the default
7503                installerInfo.isDefault = true;
7504                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7505                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7506                // add a non-generic filter
7507                installerInfo.filter = new IntentFilter();
7508                // load resources from the correct package
7509                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7510                resolveInfos.set(i, installerInfo);
7511                continue;
7512            }
7513            // caller is a full app, don't need to apply any other filtering
7514            if (ephemeralPkgName == null) {
7515                continue;
7516            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7517                // caller is same app; don't need to apply any other filtering
7518                continue;
7519            }
7520            // allow activities that have been explicitly exposed to ephemeral apps
7521            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7522            if (!isEphemeralApp
7523                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7524                continue;
7525            }
7526            resolveInfos.remove(i);
7527        }
7528        return resolveInfos;
7529    }
7530
7531    /**
7532     * @param resolveInfos list of resolve infos in descending priority order
7533     * @return if the list contains a resolve info with non-negative priority
7534     */
7535    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7536        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7537    }
7538
7539    private static boolean hasWebURI(Intent intent) {
7540        if (intent.getData() == null) {
7541            return false;
7542        }
7543        final String scheme = intent.getScheme();
7544        if (TextUtils.isEmpty(scheme)) {
7545            return false;
7546        }
7547        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7548    }
7549
7550    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7551            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7552            int userId) {
7553        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7554
7555        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7556            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7557                    candidates.size());
7558        }
7559
7560        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7561        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7562        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7563        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7564        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7565        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7566
7567        synchronized (mPackages) {
7568            final int count = candidates.size();
7569            // First, try to use linked apps. Partition the candidates into four lists:
7570            // one for the final results, one for the "do not use ever", one for "undefined status"
7571            // and finally one for "browser app type".
7572            for (int n=0; n<count; n++) {
7573                ResolveInfo info = candidates.get(n);
7574                String packageName = info.activityInfo.packageName;
7575                PackageSetting ps = mSettings.mPackages.get(packageName);
7576                if (ps != null) {
7577                    // Add to the special match all list (Browser use case)
7578                    if (info.handleAllWebDataURI) {
7579                        matchAllList.add(info);
7580                        continue;
7581                    }
7582                    // Try to get the status from User settings first
7583                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7584                    int status = (int)(packedStatus >> 32);
7585                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7586                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7587                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7588                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7589                                    + " : linkgen=" + linkGeneration);
7590                        }
7591                        // Use link-enabled generation as preferredOrder, i.e.
7592                        // prefer newly-enabled over earlier-enabled.
7593                        info.preferredOrder = linkGeneration;
7594                        alwaysList.add(info);
7595                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7596                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7597                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7598                        }
7599                        neverList.add(info);
7600                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7601                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7602                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7603                        }
7604                        alwaysAskList.add(info);
7605                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7606                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7607                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7608                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7609                        }
7610                        undefinedList.add(info);
7611                    }
7612                }
7613            }
7614
7615            // We'll want to include browser possibilities in a few cases
7616            boolean includeBrowser = false;
7617
7618            // First try to add the "always" resolution(s) for the current user, if any
7619            if (alwaysList.size() > 0) {
7620                result.addAll(alwaysList);
7621            } else {
7622                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7623                result.addAll(undefinedList);
7624                // Maybe add one for the other profile.
7625                if (xpDomainInfo != null && (
7626                        xpDomainInfo.bestDomainVerificationStatus
7627                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7628                    result.add(xpDomainInfo.resolveInfo);
7629                }
7630                includeBrowser = true;
7631            }
7632
7633            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7634            // If there were 'always' entries their preferred order has been set, so we also
7635            // back that off to make the alternatives equivalent
7636            if (alwaysAskList.size() > 0) {
7637                for (ResolveInfo i : result) {
7638                    i.preferredOrder = 0;
7639                }
7640                result.addAll(alwaysAskList);
7641                includeBrowser = true;
7642            }
7643
7644            if (includeBrowser) {
7645                // Also add browsers (all of them or only the default one)
7646                if (DEBUG_DOMAIN_VERIFICATION) {
7647                    Slog.v(TAG, "   ...including browsers in candidate set");
7648                }
7649                if ((matchFlags & MATCH_ALL) != 0) {
7650                    result.addAll(matchAllList);
7651                } else {
7652                    // Browser/generic handling case.  If there's a default browser, go straight
7653                    // to that (but only if there is no other higher-priority match).
7654                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7655                    int maxMatchPrio = 0;
7656                    ResolveInfo defaultBrowserMatch = null;
7657                    final int numCandidates = matchAllList.size();
7658                    for (int n = 0; n < numCandidates; n++) {
7659                        ResolveInfo info = matchAllList.get(n);
7660                        // track the highest overall match priority...
7661                        if (info.priority > maxMatchPrio) {
7662                            maxMatchPrio = info.priority;
7663                        }
7664                        // ...and the highest-priority default browser match
7665                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7666                            if (defaultBrowserMatch == null
7667                                    || (defaultBrowserMatch.priority < info.priority)) {
7668                                if (debug) {
7669                                    Slog.v(TAG, "Considering default browser match " + info);
7670                                }
7671                                defaultBrowserMatch = info;
7672                            }
7673                        }
7674                    }
7675                    if (defaultBrowserMatch != null
7676                            && defaultBrowserMatch.priority >= maxMatchPrio
7677                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7678                    {
7679                        if (debug) {
7680                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7681                        }
7682                        result.add(defaultBrowserMatch);
7683                    } else {
7684                        result.addAll(matchAllList);
7685                    }
7686                }
7687
7688                // If there is nothing selected, add all candidates and remove the ones that the user
7689                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7690                if (result.size() == 0) {
7691                    result.addAll(candidates);
7692                    result.removeAll(neverList);
7693                }
7694            }
7695        }
7696        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7697            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7698                    result.size());
7699            for (ResolveInfo info : result) {
7700                Slog.v(TAG, "  + " + info.activityInfo);
7701            }
7702        }
7703        return result;
7704    }
7705
7706    // Returns a packed value as a long:
7707    //
7708    // high 'int'-sized word: link status: undefined/ask/never/always.
7709    // low 'int'-sized word: relative priority among 'always' results.
7710    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7711        long result = ps.getDomainVerificationStatusForUser(userId);
7712        // if none available, get the master status
7713        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7714            if (ps.getIntentFilterVerificationInfo() != null) {
7715                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7716            }
7717        }
7718        return result;
7719    }
7720
7721    private ResolveInfo querySkipCurrentProfileIntents(
7722            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7723            int flags, int sourceUserId) {
7724        if (matchingFilters != null) {
7725            int size = matchingFilters.size();
7726            for (int i = 0; i < size; i ++) {
7727                CrossProfileIntentFilter filter = matchingFilters.get(i);
7728                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7729                    // Checking if there are activities in the target user that can handle the
7730                    // intent.
7731                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7732                            resolvedType, flags, sourceUserId);
7733                    if (resolveInfo != null) {
7734                        return resolveInfo;
7735                    }
7736                }
7737            }
7738        }
7739        return null;
7740    }
7741
7742    // Return matching ResolveInfo in target user if any.
7743    private ResolveInfo queryCrossProfileIntents(
7744            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7745            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7746        if (matchingFilters != null) {
7747            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7748            // match the same intent. For performance reasons, it is better not to
7749            // run queryIntent twice for the same userId
7750            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7751            int size = matchingFilters.size();
7752            for (int i = 0; i < size; i++) {
7753                CrossProfileIntentFilter filter = matchingFilters.get(i);
7754                int targetUserId = filter.getTargetUserId();
7755                boolean skipCurrentProfile =
7756                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7757                boolean skipCurrentProfileIfNoMatchFound =
7758                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7759                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7760                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7761                    // Checking if there are activities in the target user that can handle the
7762                    // intent.
7763                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7764                            resolvedType, flags, sourceUserId);
7765                    if (resolveInfo != null) return resolveInfo;
7766                    alreadyTriedUserIds.put(targetUserId, true);
7767                }
7768            }
7769        }
7770        return null;
7771    }
7772
7773    /**
7774     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7775     * will forward the intent to the filter's target user.
7776     * Otherwise, returns null.
7777     */
7778    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7779            String resolvedType, int flags, int sourceUserId) {
7780        int targetUserId = filter.getTargetUserId();
7781        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7782                resolvedType, flags, targetUserId);
7783        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7784            // If all the matches in the target profile are suspended, return null.
7785            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7786                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7787                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7788                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7789                            targetUserId);
7790                }
7791            }
7792        }
7793        return null;
7794    }
7795
7796    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7797            int sourceUserId, int targetUserId) {
7798        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7799        long ident = Binder.clearCallingIdentity();
7800        boolean targetIsProfile;
7801        try {
7802            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7803        } finally {
7804            Binder.restoreCallingIdentity(ident);
7805        }
7806        String className;
7807        if (targetIsProfile) {
7808            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7809        } else {
7810            className = FORWARD_INTENT_TO_PARENT;
7811        }
7812        ComponentName forwardingActivityComponentName = new ComponentName(
7813                mAndroidApplication.packageName, className);
7814        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7815                sourceUserId);
7816        if (!targetIsProfile) {
7817            forwardingActivityInfo.showUserIcon = targetUserId;
7818            forwardingResolveInfo.noResourceId = true;
7819        }
7820        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7821        forwardingResolveInfo.priority = 0;
7822        forwardingResolveInfo.preferredOrder = 0;
7823        forwardingResolveInfo.match = 0;
7824        forwardingResolveInfo.isDefault = true;
7825        forwardingResolveInfo.filter = filter;
7826        forwardingResolveInfo.targetUserId = targetUserId;
7827        return forwardingResolveInfo;
7828    }
7829
7830    @Override
7831    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7832            Intent[] specifics, String[] specificTypes, Intent intent,
7833            String resolvedType, int flags, int userId) {
7834        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7835                specificTypes, intent, resolvedType, flags, userId));
7836    }
7837
7838    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7839            Intent[] specifics, String[] specificTypes, Intent intent,
7840            String resolvedType, int flags, int userId) {
7841        if (!sUserManager.exists(userId)) return Collections.emptyList();
7842        final int callingUid = Binder.getCallingUid();
7843        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7844                false /*includeInstantApps*/);
7845        enforceCrossUserPermission(callingUid, userId,
7846                false /*requireFullPermission*/, false /*checkShell*/,
7847                "query intent activity options");
7848        final String resultsAction = intent.getAction();
7849
7850        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7851                | PackageManager.GET_RESOLVED_FILTER, userId);
7852
7853        if (DEBUG_INTENT_MATCHING) {
7854            Log.v(TAG, "Query " + intent + ": " + results);
7855        }
7856
7857        int specificsPos = 0;
7858        int N;
7859
7860        // todo: note that the algorithm used here is O(N^2).  This
7861        // isn't a problem in our current environment, but if we start running
7862        // into situations where we have more than 5 or 10 matches then this
7863        // should probably be changed to something smarter...
7864
7865        // First we go through and resolve each of the specific items
7866        // that were supplied, taking care of removing any corresponding
7867        // duplicate items in the generic resolve list.
7868        if (specifics != null) {
7869            for (int i=0; i<specifics.length; i++) {
7870                final Intent sintent = specifics[i];
7871                if (sintent == null) {
7872                    continue;
7873                }
7874
7875                if (DEBUG_INTENT_MATCHING) {
7876                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7877                }
7878
7879                String action = sintent.getAction();
7880                if (resultsAction != null && resultsAction.equals(action)) {
7881                    // If this action was explicitly requested, then don't
7882                    // remove things that have it.
7883                    action = null;
7884                }
7885
7886                ResolveInfo ri = null;
7887                ActivityInfo ai = null;
7888
7889                ComponentName comp = sintent.getComponent();
7890                if (comp == null) {
7891                    ri = resolveIntent(
7892                        sintent,
7893                        specificTypes != null ? specificTypes[i] : null,
7894                            flags, userId);
7895                    if (ri == null) {
7896                        continue;
7897                    }
7898                    if (ri == mResolveInfo) {
7899                        // ACK!  Must do something better with this.
7900                    }
7901                    ai = ri.activityInfo;
7902                    comp = new ComponentName(ai.applicationInfo.packageName,
7903                            ai.name);
7904                } else {
7905                    ai = getActivityInfo(comp, flags, userId);
7906                    if (ai == null) {
7907                        continue;
7908                    }
7909                }
7910
7911                // Look for any generic query activities that are duplicates
7912                // of this specific one, and remove them from the results.
7913                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7914                N = results.size();
7915                int j;
7916                for (j=specificsPos; j<N; j++) {
7917                    ResolveInfo sri = results.get(j);
7918                    if ((sri.activityInfo.name.equals(comp.getClassName())
7919                            && sri.activityInfo.applicationInfo.packageName.equals(
7920                                    comp.getPackageName()))
7921                        || (action != null && sri.filter.matchAction(action))) {
7922                        results.remove(j);
7923                        if (DEBUG_INTENT_MATCHING) Log.v(
7924                            TAG, "Removing duplicate item from " + j
7925                            + " due to specific " + specificsPos);
7926                        if (ri == null) {
7927                            ri = sri;
7928                        }
7929                        j--;
7930                        N--;
7931                    }
7932                }
7933
7934                // Add this specific item to its proper place.
7935                if (ri == null) {
7936                    ri = new ResolveInfo();
7937                    ri.activityInfo = ai;
7938                }
7939                results.add(specificsPos, ri);
7940                ri.specificIndex = i;
7941                specificsPos++;
7942            }
7943        }
7944
7945        // Now we go through the remaining generic results and remove any
7946        // duplicate actions that are found here.
7947        N = results.size();
7948        for (int i=specificsPos; i<N-1; i++) {
7949            final ResolveInfo rii = results.get(i);
7950            if (rii.filter == null) {
7951                continue;
7952            }
7953
7954            // Iterate over all of the actions of this result's intent
7955            // filter...  typically this should be just one.
7956            final Iterator<String> it = rii.filter.actionsIterator();
7957            if (it == null) {
7958                continue;
7959            }
7960            while (it.hasNext()) {
7961                final String action = it.next();
7962                if (resultsAction != null && resultsAction.equals(action)) {
7963                    // If this action was explicitly requested, then don't
7964                    // remove things that have it.
7965                    continue;
7966                }
7967                for (int j=i+1; j<N; j++) {
7968                    final ResolveInfo rij = results.get(j);
7969                    if (rij.filter != null && rij.filter.hasAction(action)) {
7970                        results.remove(j);
7971                        if (DEBUG_INTENT_MATCHING) Log.v(
7972                            TAG, "Removing duplicate item from " + j
7973                            + " due to action " + action + " at " + i);
7974                        j--;
7975                        N--;
7976                    }
7977                }
7978            }
7979
7980            // If the caller didn't request filter information, drop it now
7981            // so we don't have to marshall/unmarshall it.
7982            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7983                rii.filter = null;
7984            }
7985        }
7986
7987        // Filter out the caller activity if so requested.
7988        if (caller != null) {
7989            N = results.size();
7990            for (int i=0; i<N; i++) {
7991                ActivityInfo ainfo = results.get(i).activityInfo;
7992                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7993                        && caller.getClassName().equals(ainfo.name)) {
7994                    results.remove(i);
7995                    break;
7996                }
7997            }
7998        }
7999
8000        // If the caller didn't request filter information,
8001        // drop them now so we don't have to
8002        // marshall/unmarshall it.
8003        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8004            N = results.size();
8005            for (int i=0; i<N; i++) {
8006                results.get(i).filter = null;
8007            }
8008        }
8009
8010        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8011        return results;
8012    }
8013
8014    @Override
8015    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8016            String resolvedType, int flags, int userId) {
8017        return new ParceledListSlice<>(
8018                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
8019    }
8020
8021    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8022            String resolvedType, int flags, int userId) {
8023        if (!sUserManager.exists(userId)) return Collections.emptyList();
8024        final int callingUid = Binder.getCallingUid();
8025        enforceCrossUserPermission(callingUid, userId,
8026                false /*requireFullPermission*/, false /*checkShell*/,
8027                "query intent receivers");
8028        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8029        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8030                false /*includeInstantApps*/);
8031        ComponentName comp = intent.getComponent();
8032        if (comp == null) {
8033            if (intent.getSelector() != null) {
8034                intent = intent.getSelector();
8035                comp = intent.getComponent();
8036            }
8037        }
8038        if (comp != null) {
8039            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8040            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8041            if (ai != null) {
8042                // When specifying an explicit component, we prevent the activity from being
8043                // used when either 1) the calling package is normal and the activity is within
8044                // an instant application or 2) the calling package is ephemeral and the
8045                // activity is not visible to instant applications.
8046                final boolean matchInstantApp =
8047                        (flags & PackageManager.MATCH_INSTANT) != 0;
8048                final boolean matchVisibleToInstantAppOnly =
8049                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8050                final boolean matchExplicitlyVisibleOnly =
8051                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8052                final boolean isCallerInstantApp =
8053                        instantAppPkgName != null;
8054                final boolean isTargetSameInstantApp =
8055                        comp.getPackageName().equals(instantAppPkgName);
8056                final boolean isTargetInstantApp =
8057                        (ai.applicationInfo.privateFlags
8058                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8059                final boolean isTargetVisibleToInstantApp =
8060                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8061                final boolean isTargetExplicitlyVisibleToInstantApp =
8062                        isTargetVisibleToInstantApp
8063                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8064                final boolean isTargetHiddenFromInstantApp =
8065                        !isTargetVisibleToInstantApp
8066                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8067                final boolean blockResolution =
8068                        !isTargetSameInstantApp
8069                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8070                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8071                                        && isTargetHiddenFromInstantApp));
8072                if (!blockResolution) {
8073                    ResolveInfo ri = new ResolveInfo();
8074                    ri.activityInfo = ai;
8075                    list.add(ri);
8076                }
8077            }
8078            return applyPostResolutionFilter(list, instantAppPkgName);
8079        }
8080
8081        // reader
8082        synchronized (mPackages) {
8083            String pkgName = intent.getPackage();
8084            if (pkgName == null) {
8085                final List<ResolveInfo> result =
8086                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8087                return applyPostResolutionFilter(result, instantAppPkgName);
8088            }
8089            final PackageParser.Package pkg = mPackages.get(pkgName);
8090            if (pkg != null) {
8091                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8092                        intent, resolvedType, flags, pkg.receivers, userId);
8093                return applyPostResolutionFilter(result, instantAppPkgName);
8094            }
8095            return Collections.emptyList();
8096        }
8097    }
8098
8099    @Override
8100    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8101        final int callingUid = Binder.getCallingUid();
8102        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8103    }
8104
8105    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8106            int userId, int callingUid) {
8107        if (!sUserManager.exists(userId)) return null;
8108        flags = updateFlagsForResolve(
8109                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8110        List<ResolveInfo> query = queryIntentServicesInternal(
8111                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8112        if (query != null) {
8113            if (query.size() >= 1) {
8114                // If there is more than one service with the same priority,
8115                // just arbitrarily pick the first one.
8116                return query.get(0);
8117            }
8118        }
8119        return null;
8120    }
8121
8122    @Override
8123    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8124            String resolvedType, int flags, int userId) {
8125        final int callingUid = Binder.getCallingUid();
8126        return new ParceledListSlice<>(queryIntentServicesInternal(
8127                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8128    }
8129
8130    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8131            String resolvedType, int flags, int userId, int callingUid,
8132            boolean includeInstantApps) {
8133        if (!sUserManager.exists(userId)) return Collections.emptyList();
8134        enforceCrossUserPermission(callingUid, userId,
8135                false /*requireFullPermission*/, false /*checkShell*/,
8136                "query intent receivers");
8137        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8138        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8139        ComponentName comp = intent.getComponent();
8140        if (comp == null) {
8141            if (intent.getSelector() != null) {
8142                intent = intent.getSelector();
8143                comp = intent.getComponent();
8144            }
8145        }
8146        if (comp != null) {
8147            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8148            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8149            if (si != null) {
8150                // When specifying an explicit component, we prevent the service from being
8151                // used when either 1) the service is in an instant application and the
8152                // caller is not the same instant application or 2) the calling package is
8153                // ephemeral and the activity is not visible to ephemeral applications.
8154                final boolean matchInstantApp =
8155                        (flags & PackageManager.MATCH_INSTANT) != 0;
8156                final boolean matchVisibleToInstantAppOnly =
8157                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8158                final boolean isCallerInstantApp =
8159                        instantAppPkgName != null;
8160                final boolean isTargetSameInstantApp =
8161                        comp.getPackageName().equals(instantAppPkgName);
8162                final boolean isTargetInstantApp =
8163                        (si.applicationInfo.privateFlags
8164                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8165                final boolean isTargetHiddenFromInstantApp =
8166                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8167                final boolean blockResolution =
8168                        !isTargetSameInstantApp
8169                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8170                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8171                                        && isTargetHiddenFromInstantApp));
8172                if (!blockResolution) {
8173                    final ResolveInfo ri = new ResolveInfo();
8174                    ri.serviceInfo = si;
8175                    list.add(ri);
8176                }
8177            }
8178            return list;
8179        }
8180
8181        // reader
8182        synchronized (mPackages) {
8183            String pkgName = intent.getPackage();
8184            if (pkgName == null) {
8185                return applyPostServiceResolutionFilter(
8186                        mServices.queryIntent(intent, resolvedType, flags, userId),
8187                        instantAppPkgName);
8188            }
8189            final PackageParser.Package pkg = mPackages.get(pkgName);
8190            if (pkg != null) {
8191                return applyPostServiceResolutionFilter(
8192                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8193                                userId),
8194                        instantAppPkgName);
8195            }
8196            return Collections.emptyList();
8197        }
8198    }
8199
8200    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8201            String instantAppPkgName) {
8202        // TODO: When adding on-demand split support for non-instant apps, remove this check
8203        // and always apply post filtering
8204        if (instantAppPkgName == null) {
8205            return resolveInfos;
8206        }
8207        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8208            final ResolveInfo info = resolveInfos.get(i);
8209            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8210            // allow services that are defined in the provided package
8211            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8212                if (info.serviceInfo.splitName != null
8213                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8214                                info.serviceInfo.splitName)) {
8215                    // requested service is defined in a split that hasn't been installed yet.
8216                    // add the installer to the resolve list
8217                    if (DEBUG_EPHEMERAL) {
8218                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8219                    }
8220                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8221                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8222                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8223                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
8224                    // make sure this resolver is the default
8225                    installerInfo.isDefault = true;
8226                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8227                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8228                    // add a non-generic filter
8229                    installerInfo.filter = new IntentFilter();
8230                    // load resources from the correct package
8231                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8232                    resolveInfos.set(i, installerInfo);
8233                }
8234                continue;
8235            }
8236            // allow services that have been explicitly exposed to ephemeral apps
8237            if (!isEphemeralApp
8238                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8239                continue;
8240            }
8241            resolveInfos.remove(i);
8242        }
8243        return resolveInfos;
8244    }
8245
8246    @Override
8247    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8248            String resolvedType, int flags, int userId) {
8249        return new ParceledListSlice<>(
8250                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8251    }
8252
8253    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8254            Intent intent, String resolvedType, int flags, int userId) {
8255        if (!sUserManager.exists(userId)) return Collections.emptyList();
8256        final int callingUid = Binder.getCallingUid();
8257        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8258        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8259                false /*includeInstantApps*/);
8260        ComponentName comp = intent.getComponent();
8261        if (comp == null) {
8262            if (intent.getSelector() != null) {
8263                intent = intent.getSelector();
8264                comp = intent.getComponent();
8265            }
8266        }
8267        if (comp != null) {
8268            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8269            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8270            if (pi != null) {
8271                // When specifying an explicit component, we prevent the provider from being
8272                // used when either 1) the provider is in an instant application and the
8273                // caller is not the same instant application or 2) the calling package is an
8274                // instant application and the provider is not visible to instant applications.
8275                final boolean matchInstantApp =
8276                        (flags & PackageManager.MATCH_INSTANT) != 0;
8277                final boolean matchVisibleToInstantAppOnly =
8278                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8279                final boolean isCallerInstantApp =
8280                        instantAppPkgName != null;
8281                final boolean isTargetSameInstantApp =
8282                        comp.getPackageName().equals(instantAppPkgName);
8283                final boolean isTargetInstantApp =
8284                        (pi.applicationInfo.privateFlags
8285                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8286                final boolean isTargetHiddenFromInstantApp =
8287                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8288                final boolean blockResolution =
8289                        !isTargetSameInstantApp
8290                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8291                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8292                                        && isTargetHiddenFromInstantApp));
8293                if (!blockResolution) {
8294                    final ResolveInfo ri = new ResolveInfo();
8295                    ri.providerInfo = pi;
8296                    list.add(ri);
8297                }
8298            }
8299            return list;
8300        }
8301
8302        // reader
8303        synchronized (mPackages) {
8304            String pkgName = intent.getPackage();
8305            if (pkgName == null) {
8306                return applyPostContentProviderResolutionFilter(
8307                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8308                        instantAppPkgName);
8309            }
8310            final PackageParser.Package pkg = mPackages.get(pkgName);
8311            if (pkg != null) {
8312                return applyPostContentProviderResolutionFilter(
8313                        mProviders.queryIntentForPackage(
8314                        intent, resolvedType, flags, pkg.providers, userId),
8315                        instantAppPkgName);
8316            }
8317            return Collections.emptyList();
8318        }
8319    }
8320
8321    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8322            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8323        // TODO: When adding on-demand split support for non-instant applications, remove
8324        // this check and always apply post filtering
8325        if (instantAppPkgName == null) {
8326            return resolveInfos;
8327        }
8328        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8329            final ResolveInfo info = resolveInfos.get(i);
8330            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8331            // allow providers that are defined in the provided package
8332            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8333                if (info.providerInfo.splitName != null
8334                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8335                                info.providerInfo.splitName)) {
8336                    // requested provider is defined in a split that hasn't been installed yet.
8337                    // add the installer to the resolve list
8338                    if (DEBUG_EPHEMERAL) {
8339                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8340                    }
8341                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8342                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8343                            info.providerInfo.packageName, info.providerInfo.splitName,
8344                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8345                    // make sure this resolver is the default
8346                    installerInfo.isDefault = true;
8347                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8348                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8349                    // add a non-generic filter
8350                    installerInfo.filter = new IntentFilter();
8351                    // load resources from the correct package
8352                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8353                    resolveInfos.set(i, installerInfo);
8354                }
8355                continue;
8356            }
8357            // allow providers that have been explicitly exposed to instant applications
8358            if (!isEphemeralApp
8359                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8360                continue;
8361            }
8362            resolveInfos.remove(i);
8363        }
8364        return resolveInfos;
8365    }
8366
8367    @Override
8368    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8369        final int callingUid = Binder.getCallingUid();
8370        if (getInstantAppPackageName(callingUid) != null) {
8371            return ParceledListSlice.emptyList();
8372        }
8373        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8374        flags = updateFlagsForPackage(flags, userId, null);
8375        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8376        enforceCrossUserPermission(callingUid, userId,
8377                true /* requireFullPermission */, false /* checkShell */,
8378                "get installed packages");
8379
8380        // writer
8381        synchronized (mPackages) {
8382            ArrayList<PackageInfo> list;
8383            if (listUninstalled) {
8384                list = new ArrayList<>(mSettings.mPackages.size());
8385                for (PackageSetting ps : mSettings.mPackages.values()) {
8386                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8387                        continue;
8388                    }
8389                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8390                        return null;
8391                    }
8392                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8393                    if (pi != null) {
8394                        list.add(pi);
8395                    }
8396                }
8397            } else {
8398                list = new ArrayList<>(mPackages.size());
8399                for (PackageParser.Package p : mPackages.values()) {
8400                    final PackageSetting ps = (PackageSetting) p.mExtras;
8401                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8402                        continue;
8403                    }
8404                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8405                        return null;
8406                    }
8407                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8408                            p.mExtras, flags, userId);
8409                    if (pi != null) {
8410                        list.add(pi);
8411                    }
8412                }
8413            }
8414
8415            return new ParceledListSlice<>(list);
8416        }
8417    }
8418
8419    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8420            String[] permissions, boolean[] tmp, int flags, int userId) {
8421        int numMatch = 0;
8422        final PermissionsState permissionsState = ps.getPermissionsState();
8423        for (int i=0; i<permissions.length; i++) {
8424            final String permission = permissions[i];
8425            if (permissionsState.hasPermission(permission, userId)) {
8426                tmp[i] = true;
8427                numMatch++;
8428            } else {
8429                tmp[i] = false;
8430            }
8431        }
8432        if (numMatch == 0) {
8433            return;
8434        }
8435        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8436
8437        // The above might return null in cases of uninstalled apps or install-state
8438        // skew across users/profiles.
8439        if (pi != null) {
8440            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8441                if (numMatch == permissions.length) {
8442                    pi.requestedPermissions = permissions;
8443                } else {
8444                    pi.requestedPermissions = new String[numMatch];
8445                    numMatch = 0;
8446                    for (int i=0; i<permissions.length; i++) {
8447                        if (tmp[i]) {
8448                            pi.requestedPermissions[numMatch] = permissions[i];
8449                            numMatch++;
8450                        }
8451                    }
8452                }
8453            }
8454            list.add(pi);
8455        }
8456    }
8457
8458    @Override
8459    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8460            String[] permissions, int flags, int userId) {
8461        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8462        flags = updateFlagsForPackage(flags, userId, permissions);
8463        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8464                true /* requireFullPermission */, false /* checkShell */,
8465                "get packages holding permissions");
8466        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8467
8468        // writer
8469        synchronized (mPackages) {
8470            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8471            boolean[] tmpBools = new boolean[permissions.length];
8472            if (listUninstalled) {
8473                for (PackageSetting ps : mSettings.mPackages.values()) {
8474                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8475                            userId);
8476                }
8477            } else {
8478                for (PackageParser.Package pkg : mPackages.values()) {
8479                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8480                    if (ps != null) {
8481                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8482                                userId);
8483                    }
8484                }
8485            }
8486
8487            return new ParceledListSlice<PackageInfo>(list);
8488        }
8489    }
8490
8491    @Override
8492    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8493        final int callingUid = Binder.getCallingUid();
8494        if (getInstantAppPackageName(callingUid) != null) {
8495            return ParceledListSlice.emptyList();
8496        }
8497        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8498        flags = updateFlagsForApplication(flags, userId, null);
8499        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8500
8501        // writer
8502        synchronized (mPackages) {
8503            ArrayList<ApplicationInfo> list;
8504            if (listUninstalled) {
8505                list = new ArrayList<>(mSettings.mPackages.size());
8506                for (PackageSetting ps : mSettings.mPackages.values()) {
8507                    ApplicationInfo ai;
8508                    int effectiveFlags = flags;
8509                    if (ps.isSystem()) {
8510                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8511                    }
8512                    if (ps.pkg != null) {
8513                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8514                            continue;
8515                        }
8516                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8517                            return null;
8518                        }
8519                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8520                                ps.readUserState(userId), userId);
8521                        if (ai != null) {
8522                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8523                        }
8524                    } else {
8525                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8526                        // and already converts to externally visible package name
8527                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8528                                callingUid, effectiveFlags, userId);
8529                    }
8530                    if (ai != null) {
8531                        list.add(ai);
8532                    }
8533                }
8534            } else {
8535                list = new ArrayList<>(mPackages.size());
8536                for (PackageParser.Package p : mPackages.values()) {
8537                    if (p.mExtras != null) {
8538                        PackageSetting ps = (PackageSetting) p.mExtras;
8539                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8540                            continue;
8541                        }
8542                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8543                            return null;
8544                        }
8545                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8546                                ps.readUserState(userId), userId);
8547                        if (ai != null) {
8548                            ai.packageName = resolveExternalPackageNameLPr(p);
8549                            list.add(ai);
8550                        }
8551                    }
8552                }
8553            }
8554
8555            return new ParceledListSlice<>(list);
8556        }
8557    }
8558
8559    @Override
8560    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8561        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8562            return null;
8563        }
8564        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8565            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8566                    "getEphemeralApplications");
8567        }
8568        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8569                true /* requireFullPermission */, false /* checkShell */,
8570                "getEphemeralApplications");
8571        synchronized (mPackages) {
8572            List<InstantAppInfo> instantApps = mInstantAppRegistry
8573                    .getInstantAppsLPr(userId);
8574            if (instantApps != null) {
8575                return new ParceledListSlice<>(instantApps);
8576            }
8577        }
8578        return null;
8579    }
8580
8581    @Override
8582    public boolean isInstantApp(String packageName, int userId) {
8583        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8584                true /* requireFullPermission */, false /* checkShell */,
8585                "isInstantApp");
8586        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8587            return false;
8588        }
8589
8590        synchronized (mPackages) {
8591            int callingUid = Binder.getCallingUid();
8592            if (Process.isIsolated(callingUid)) {
8593                callingUid = mIsolatedOwners.get(callingUid);
8594            }
8595            final PackageSetting ps = mSettings.mPackages.get(packageName);
8596            PackageParser.Package pkg = mPackages.get(packageName);
8597            final boolean returnAllowed =
8598                    ps != null
8599                    && (isCallerSameApp(packageName, callingUid)
8600                            || canViewInstantApps(callingUid, userId)
8601                            || mInstantAppRegistry.isInstantAccessGranted(
8602                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8603            if (returnAllowed) {
8604                return ps.getInstantApp(userId);
8605            }
8606        }
8607        return false;
8608    }
8609
8610    @Override
8611    public byte[] getInstantAppCookie(String packageName, int userId) {
8612        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8613            return null;
8614        }
8615
8616        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8617                true /* requireFullPermission */, false /* checkShell */,
8618                "getInstantAppCookie");
8619        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8620            return null;
8621        }
8622        synchronized (mPackages) {
8623            return mInstantAppRegistry.getInstantAppCookieLPw(
8624                    packageName, userId);
8625        }
8626    }
8627
8628    @Override
8629    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8630        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8631            return true;
8632        }
8633
8634        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8635                true /* requireFullPermission */, true /* checkShell */,
8636                "setInstantAppCookie");
8637        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8638            return false;
8639        }
8640        synchronized (mPackages) {
8641            return mInstantAppRegistry.setInstantAppCookieLPw(
8642                    packageName, cookie, userId);
8643        }
8644    }
8645
8646    @Override
8647    public Bitmap getInstantAppIcon(String packageName, int userId) {
8648        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8649            return null;
8650        }
8651
8652        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8653            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8654                    "getInstantAppIcon");
8655        }
8656        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8657                true /* requireFullPermission */, false /* checkShell */,
8658                "getInstantAppIcon");
8659
8660        synchronized (mPackages) {
8661            return mInstantAppRegistry.getInstantAppIconLPw(
8662                    packageName, userId);
8663        }
8664    }
8665
8666    private boolean isCallerSameApp(String packageName, int uid) {
8667        PackageParser.Package pkg = mPackages.get(packageName);
8668        return pkg != null
8669                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8670    }
8671
8672    @Override
8673    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8674        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8675            return ParceledListSlice.emptyList();
8676        }
8677        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8678    }
8679
8680    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8681        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8682
8683        // reader
8684        synchronized (mPackages) {
8685            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8686            final int userId = UserHandle.getCallingUserId();
8687            while (i.hasNext()) {
8688                final PackageParser.Package p = i.next();
8689                if (p.applicationInfo == null) continue;
8690
8691                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8692                        && !p.applicationInfo.isDirectBootAware();
8693                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8694                        && p.applicationInfo.isDirectBootAware();
8695
8696                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8697                        && (!mSafeMode || isSystemApp(p))
8698                        && (matchesUnaware || matchesAware)) {
8699                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8700                    if (ps != null) {
8701                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8702                                ps.readUserState(userId), userId);
8703                        if (ai != null) {
8704                            finalList.add(ai);
8705                        }
8706                    }
8707                }
8708            }
8709        }
8710
8711        return finalList;
8712    }
8713
8714    @Override
8715    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8716        if (!sUserManager.exists(userId)) return null;
8717        flags = updateFlagsForComponent(flags, userId, name);
8718        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8719        // reader
8720        synchronized (mPackages) {
8721            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8722            PackageSetting ps = provider != null
8723                    ? mSettings.mPackages.get(provider.owner.packageName)
8724                    : null;
8725            if (ps != null) {
8726                final boolean isInstantApp = ps.getInstantApp(userId);
8727                // normal application; filter out instant application provider
8728                if (instantAppPkgName == null && isInstantApp) {
8729                    return null;
8730                }
8731                // instant application; filter out other instant applications
8732                if (instantAppPkgName != null
8733                        && isInstantApp
8734                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8735                    return null;
8736                }
8737                // instant application; filter out non-exposed provider
8738                if (instantAppPkgName != null
8739                        && !isInstantApp
8740                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8741                    return null;
8742                }
8743                // provider not enabled
8744                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8745                    return null;
8746                }
8747                return PackageParser.generateProviderInfo(
8748                        provider, flags, ps.readUserState(userId), userId);
8749            }
8750            return null;
8751        }
8752    }
8753
8754    /**
8755     * @deprecated
8756     */
8757    @Deprecated
8758    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8759        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8760            return;
8761        }
8762        // reader
8763        synchronized (mPackages) {
8764            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8765                    .entrySet().iterator();
8766            final int userId = UserHandle.getCallingUserId();
8767            while (i.hasNext()) {
8768                Map.Entry<String, PackageParser.Provider> entry = i.next();
8769                PackageParser.Provider p = entry.getValue();
8770                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8771
8772                if (ps != null && p.syncable
8773                        && (!mSafeMode || (p.info.applicationInfo.flags
8774                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8775                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8776                            ps.readUserState(userId), userId);
8777                    if (info != null) {
8778                        outNames.add(entry.getKey());
8779                        outInfo.add(info);
8780                    }
8781                }
8782            }
8783        }
8784    }
8785
8786    @Override
8787    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8788            int uid, int flags, String metaDataKey) {
8789        final int callingUid = Binder.getCallingUid();
8790        final int userId = processName != null ? UserHandle.getUserId(uid)
8791                : UserHandle.getCallingUserId();
8792        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8793        flags = updateFlagsForComponent(flags, userId, processName);
8794        ArrayList<ProviderInfo> finalList = null;
8795        // reader
8796        synchronized (mPackages) {
8797            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8798            while (i.hasNext()) {
8799                final PackageParser.Provider p = i.next();
8800                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8801                if (ps != null && p.info.authority != null
8802                        && (processName == null
8803                                || (p.info.processName.equals(processName)
8804                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8805                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8806
8807                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8808                    // parameter.
8809                    if (metaDataKey != null
8810                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8811                        continue;
8812                    }
8813                    final ComponentName component =
8814                            new ComponentName(p.info.packageName, p.info.name);
8815                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8816                        continue;
8817                    }
8818                    if (finalList == null) {
8819                        finalList = new ArrayList<ProviderInfo>(3);
8820                    }
8821                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8822                            ps.readUserState(userId), userId);
8823                    if (info != null) {
8824                        finalList.add(info);
8825                    }
8826                }
8827            }
8828        }
8829
8830        if (finalList != null) {
8831            Collections.sort(finalList, mProviderInitOrderSorter);
8832            return new ParceledListSlice<ProviderInfo>(finalList);
8833        }
8834
8835        return ParceledListSlice.emptyList();
8836    }
8837
8838    @Override
8839    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8840        // reader
8841        synchronized (mPackages) {
8842            final int callingUid = Binder.getCallingUid();
8843            final int callingUserId = UserHandle.getUserId(callingUid);
8844            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8845            if (ps == null) return null;
8846            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8847                return null;
8848            }
8849            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8850            return PackageParser.generateInstrumentationInfo(i, flags);
8851        }
8852    }
8853
8854    @Override
8855    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8856            String targetPackage, int flags) {
8857        final int callingUid = Binder.getCallingUid();
8858        final int callingUserId = UserHandle.getUserId(callingUid);
8859        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8860        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8861            return ParceledListSlice.emptyList();
8862        }
8863        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8864    }
8865
8866    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8867            int flags) {
8868        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8869
8870        // reader
8871        synchronized (mPackages) {
8872            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8873            while (i.hasNext()) {
8874                final PackageParser.Instrumentation p = i.next();
8875                if (targetPackage == null
8876                        || targetPackage.equals(p.info.targetPackage)) {
8877                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8878                            flags);
8879                    if (ii != null) {
8880                        finalList.add(ii);
8881                    }
8882                }
8883            }
8884        }
8885
8886        return finalList;
8887    }
8888
8889    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8890        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8891        try {
8892            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8893        } finally {
8894            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8895        }
8896    }
8897
8898    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8899        final File[] files = dir.listFiles();
8900        if (ArrayUtils.isEmpty(files)) {
8901            Log.d(TAG, "No files in app dir " + dir);
8902            return;
8903        }
8904
8905        if (DEBUG_PACKAGE_SCANNING) {
8906            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8907                    + " flags=0x" + Integer.toHexString(parseFlags));
8908        }
8909        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8910                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8911                mParallelPackageParserCallback);
8912
8913        // Submit files for parsing in parallel
8914        int fileCount = 0;
8915        for (File file : files) {
8916            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8917                    && !PackageInstallerService.isStageName(file.getName());
8918            if (!isPackage) {
8919                // Ignore entries which are not packages
8920                continue;
8921            }
8922            parallelPackageParser.submit(file, parseFlags);
8923            fileCount++;
8924        }
8925
8926        // Process results one by one
8927        for (; fileCount > 0; fileCount--) {
8928            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8929            Throwable throwable = parseResult.throwable;
8930            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8931
8932            if (throwable == null) {
8933                // Static shared libraries have synthetic package names
8934                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8935                    renameStaticSharedLibraryPackage(parseResult.pkg);
8936                }
8937                try {
8938                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8939                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8940                                currentTime, null);
8941                    }
8942                } catch (PackageManagerException e) {
8943                    errorCode = e.error;
8944                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8945                }
8946            } else if (throwable instanceof PackageParser.PackageParserException) {
8947                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8948                        throwable;
8949                errorCode = e.error;
8950                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8951            } else {
8952                throw new IllegalStateException("Unexpected exception occurred while parsing "
8953                        + parseResult.scanFile, throwable);
8954            }
8955
8956            // Delete invalid userdata apps
8957            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8958                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8959                logCriticalInfo(Log.WARN,
8960                        "Deleting invalid package at " + parseResult.scanFile);
8961                removeCodePathLI(parseResult.scanFile);
8962            }
8963        }
8964        parallelPackageParser.close();
8965    }
8966
8967    private static File getSettingsProblemFile() {
8968        File dataDir = Environment.getDataDirectory();
8969        File systemDir = new File(dataDir, "system");
8970        File fname = new File(systemDir, "uiderrors.txt");
8971        return fname;
8972    }
8973
8974    static void reportSettingsProblem(int priority, String msg) {
8975        logCriticalInfo(priority, msg);
8976    }
8977
8978    public static void logCriticalInfo(int priority, String msg) {
8979        Slog.println(priority, TAG, msg);
8980        EventLogTags.writePmCriticalInfo(msg);
8981        try {
8982            File fname = getSettingsProblemFile();
8983            FileOutputStream out = new FileOutputStream(fname, true);
8984            PrintWriter pw = new FastPrintWriter(out);
8985            SimpleDateFormat formatter = new SimpleDateFormat();
8986            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8987            pw.println(dateString + ": " + msg);
8988            pw.close();
8989            FileUtils.setPermissions(
8990                    fname.toString(),
8991                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8992                    -1, -1);
8993        } catch (java.io.IOException e) {
8994        }
8995    }
8996
8997    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8998        if (srcFile.isDirectory()) {
8999            final File baseFile = new File(pkg.baseCodePath);
9000            long maxModifiedTime = baseFile.lastModified();
9001            if (pkg.splitCodePaths != null) {
9002                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9003                    final File splitFile = new File(pkg.splitCodePaths[i]);
9004                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9005                }
9006            }
9007            return maxModifiedTime;
9008        }
9009        return srcFile.lastModified();
9010    }
9011
9012    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9013            final int policyFlags) throws PackageManagerException {
9014        // When upgrading from pre-N MR1, verify the package time stamp using the package
9015        // directory and not the APK file.
9016        final long lastModifiedTime = mIsPreNMR1Upgrade
9017                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9018        if (ps != null
9019                && ps.codePath.equals(srcFile)
9020                && ps.timeStamp == lastModifiedTime
9021                && !isCompatSignatureUpdateNeeded(pkg)
9022                && !isRecoverSignatureUpdateNeeded(pkg)) {
9023            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9024            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9025            ArraySet<PublicKey> signingKs;
9026            synchronized (mPackages) {
9027                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9028            }
9029            if (ps.signatures.mSignatures != null
9030                    && ps.signatures.mSignatures.length != 0
9031                    && signingKs != null) {
9032                // Optimization: reuse the existing cached certificates
9033                // if the package appears to be unchanged.
9034                pkg.mSignatures = ps.signatures.mSignatures;
9035                pkg.mSigningKeys = signingKs;
9036                return;
9037            }
9038
9039            Slog.w(TAG, "PackageSetting for " + ps.name
9040                    + " is missing signatures.  Collecting certs again to recover them.");
9041        } else {
9042            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9043        }
9044
9045        try {
9046            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9047            PackageParser.collectCertificates(pkg, policyFlags);
9048        } catch (PackageParserException e) {
9049            throw PackageManagerException.from(e);
9050        } finally {
9051            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9052        }
9053    }
9054
9055    /**
9056     *  Traces a package scan.
9057     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9058     */
9059    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9060            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9061        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9062        try {
9063            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9064        } finally {
9065            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9066        }
9067    }
9068
9069    /**
9070     *  Scans a package and returns the newly parsed package.
9071     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9072     */
9073    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9074            long currentTime, UserHandle user) throws PackageManagerException {
9075        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9076        PackageParser pp = new PackageParser();
9077        pp.setSeparateProcesses(mSeparateProcesses);
9078        pp.setOnlyCoreApps(mOnlyCore);
9079        pp.setDisplayMetrics(mMetrics);
9080        pp.setCallback(mPackageParserCallback);
9081
9082        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9083            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9084        }
9085
9086        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9087        final PackageParser.Package pkg;
9088        try {
9089            pkg = pp.parsePackage(scanFile, parseFlags);
9090        } catch (PackageParserException e) {
9091            throw PackageManagerException.from(e);
9092        } finally {
9093            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9094        }
9095
9096        // Static shared libraries have synthetic package names
9097        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9098            renameStaticSharedLibraryPackage(pkg);
9099        }
9100
9101        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9102    }
9103
9104    /**
9105     *  Scans a package and returns the newly parsed package.
9106     *  @throws PackageManagerException on a parse error.
9107     */
9108    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9109            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9110            throws PackageManagerException {
9111        // If the package has children and this is the first dive in the function
9112        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9113        // packages (parent and children) would be successfully scanned before the
9114        // actual scan since scanning mutates internal state and we want to atomically
9115        // install the package and its children.
9116        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9117            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9118                scanFlags |= SCAN_CHECK_ONLY;
9119            }
9120        } else {
9121            scanFlags &= ~SCAN_CHECK_ONLY;
9122        }
9123
9124        // Scan the parent
9125        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9126                scanFlags, currentTime, user);
9127
9128        // Scan the children
9129        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9130        for (int i = 0; i < childCount; i++) {
9131            PackageParser.Package childPackage = pkg.childPackages.get(i);
9132            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9133                    currentTime, user);
9134        }
9135
9136
9137        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9138            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9139        }
9140
9141        return scannedPkg;
9142    }
9143
9144    /**
9145     *  Scans a package and returns the newly parsed package.
9146     *  @throws PackageManagerException on a parse error.
9147     */
9148    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9149            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9150            throws PackageManagerException {
9151        PackageSetting ps = null;
9152        PackageSetting updatedPkg;
9153        // reader
9154        synchronized (mPackages) {
9155            // Look to see if we already know about this package.
9156            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9157            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9158                // This package has been renamed to its original name.  Let's
9159                // use that.
9160                ps = mSettings.getPackageLPr(oldName);
9161            }
9162            // If there was no original package, see one for the real package name.
9163            if (ps == null) {
9164                ps = mSettings.getPackageLPr(pkg.packageName);
9165            }
9166            // Check to see if this package could be hiding/updating a system
9167            // package.  Must look for it either under the original or real
9168            // package name depending on our state.
9169            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9170            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9171
9172            // If this is a package we don't know about on the system partition, we
9173            // may need to remove disabled child packages on the system partition
9174            // or may need to not add child packages if the parent apk is updated
9175            // on the data partition and no longer defines this child package.
9176            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9177                // If this is a parent package for an updated system app and this system
9178                // app got an OTA update which no longer defines some of the child packages
9179                // we have to prune them from the disabled system packages.
9180                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9181                if (disabledPs != null) {
9182                    final int scannedChildCount = (pkg.childPackages != null)
9183                            ? pkg.childPackages.size() : 0;
9184                    final int disabledChildCount = disabledPs.childPackageNames != null
9185                            ? disabledPs.childPackageNames.size() : 0;
9186                    for (int i = 0; i < disabledChildCount; i++) {
9187                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9188                        boolean disabledPackageAvailable = false;
9189                        for (int j = 0; j < scannedChildCount; j++) {
9190                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9191                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9192                                disabledPackageAvailable = true;
9193                                break;
9194                            }
9195                         }
9196                         if (!disabledPackageAvailable) {
9197                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9198                         }
9199                    }
9200                }
9201            }
9202        }
9203
9204        final boolean isUpdatedPkg = updatedPkg != null;
9205        final boolean isUpdatedSystemPkg = isUpdatedPkg
9206                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9207        boolean isUpdatedPkgBetter = false;
9208        // First check if this is a system package that may involve an update
9209        if (isUpdatedSystemPkg) {
9210            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9211            // it needs to drop FLAG_PRIVILEGED.
9212            if (locationIsPrivileged(scanFile)) {
9213                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9214            } else {
9215                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9216            }
9217
9218            if (ps != null && !ps.codePath.equals(scanFile)) {
9219                // The path has changed from what was last scanned...  check the
9220                // version of the new path against what we have stored to determine
9221                // what to do.
9222                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9223                if (pkg.mVersionCode <= ps.versionCode) {
9224                    // The system package has been updated and the code path does not match
9225                    // Ignore entry. Skip it.
9226                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9227                            + " ignored: updated version " + ps.versionCode
9228                            + " better than this " + pkg.mVersionCode);
9229                    if (!updatedPkg.codePath.equals(scanFile)) {
9230                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9231                                + ps.name + " changing from " + updatedPkg.codePathString
9232                                + " to " + scanFile);
9233                        updatedPkg.codePath = scanFile;
9234                        updatedPkg.codePathString = scanFile.toString();
9235                        updatedPkg.resourcePath = scanFile;
9236                        updatedPkg.resourcePathString = scanFile.toString();
9237                    }
9238                    updatedPkg.pkg = pkg;
9239                    updatedPkg.versionCode = pkg.mVersionCode;
9240
9241                    // Update the disabled system child packages to point to the package too.
9242                    final int childCount = updatedPkg.childPackageNames != null
9243                            ? updatedPkg.childPackageNames.size() : 0;
9244                    for (int i = 0; i < childCount; i++) {
9245                        String childPackageName = updatedPkg.childPackageNames.get(i);
9246                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9247                                childPackageName);
9248                        if (updatedChildPkg != null) {
9249                            updatedChildPkg.pkg = pkg;
9250                            updatedChildPkg.versionCode = pkg.mVersionCode;
9251                        }
9252                    }
9253                } else {
9254                    // The current app on the system partition is better than
9255                    // what we have updated to on the data partition; switch
9256                    // back to the system partition version.
9257                    // At this point, its safely assumed that package installation for
9258                    // apps in system partition will go through. If not there won't be a working
9259                    // version of the app
9260                    // writer
9261                    synchronized (mPackages) {
9262                        // Just remove the loaded entries from package lists.
9263                        mPackages.remove(ps.name);
9264                    }
9265
9266                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9267                            + " reverting from " + ps.codePathString
9268                            + ": new version " + pkg.mVersionCode
9269                            + " better than installed " + ps.versionCode);
9270
9271                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9272                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9273                    synchronized (mInstallLock) {
9274                        args.cleanUpResourcesLI();
9275                    }
9276                    synchronized (mPackages) {
9277                        mSettings.enableSystemPackageLPw(ps.name);
9278                    }
9279                    isUpdatedPkgBetter = true;
9280                }
9281            }
9282        }
9283
9284        String resourcePath = null;
9285        String baseResourcePath = null;
9286        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9287            if (ps != null && ps.resourcePathString != null) {
9288                resourcePath = ps.resourcePathString;
9289                baseResourcePath = ps.resourcePathString;
9290            } else {
9291                // Should not happen at all. Just log an error.
9292                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9293            }
9294        } else {
9295            resourcePath = pkg.codePath;
9296            baseResourcePath = pkg.baseCodePath;
9297        }
9298
9299        // Set application objects path explicitly.
9300        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9301        pkg.setApplicationInfoCodePath(pkg.codePath);
9302        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9303        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9304        pkg.setApplicationInfoResourcePath(resourcePath);
9305        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9306        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9307
9308        // throw an exception if we have an update to a system application, but, it's not more
9309        // recent than the package we've already scanned
9310        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9311            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9312                    + scanFile + " ignored: updated version " + ps.versionCode
9313                    + " better than this " + pkg.mVersionCode);
9314        }
9315
9316        if (isUpdatedPkg) {
9317            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9318            // initially
9319            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9320
9321            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9322            // flag set initially
9323            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9324                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9325            }
9326        }
9327
9328        // Verify certificates against what was last scanned
9329        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9330
9331        /*
9332         * A new system app appeared, but we already had a non-system one of the
9333         * same name installed earlier.
9334         */
9335        boolean shouldHideSystemApp = false;
9336        if (!isUpdatedPkg && ps != null
9337                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9338            /*
9339             * Check to make sure the signatures match first. If they don't,
9340             * wipe the installed application and its data.
9341             */
9342            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9343                    != PackageManager.SIGNATURE_MATCH) {
9344                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9345                        + " signatures don't match existing userdata copy; removing");
9346                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9347                        "scanPackageInternalLI")) {
9348                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9349                }
9350                ps = null;
9351            } else {
9352                /*
9353                 * If the newly-added system app is an older version than the
9354                 * already installed version, hide it. It will be scanned later
9355                 * and re-added like an update.
9356                 */
9357                if (pkg.mVersionCode <= ps.versionCode) {
9358                    shouldHideSystemApp = true;
9359                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9360                            + " but new version " + pkg.mVersionCode + " better than installed "
9361                            + ps.versionCode + "; hiding system");
9362                } else {
9363                    /*
9364                     * The newly found system app is a newer version that the
9365                     * one previously installed. Simply remove the
9366                     * already-installed application and replace it with our own
9367                     * while keeping the application data.
9368                     */
9369                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9370                            + " reverting from " + ps.codePathString + ": new version "
9371                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9372                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9373                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9374                    synchronized (mInstallLock) {
9375                        args.cleanUpResourcesLI();
9376                    }
9377                }
9378            }
9379        }
9380
9381        // The apk is forward locked (not public) if its code and resources
9382        // are kept in different files. (except for app in either system or
9383        // vendor path).
9384        // TODO grab this value from PackageSettings
9385        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9386            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9387                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9388            }
9389        }
9390
9391        final int userId = ((user == null) ? 0 : user.getIdentifier());
9392        if (ps != null && ps.getInstantApp(userId)) {
9393            scanFlags |= SCAN_AS_INSTANT_APP;
9394        }
9395
9396        // Note that we invoke the following method only if we are about to unpack an application
9397        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9398                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9399
9400        /*
9401         * If the system app should be overridden by a previously installed
9402         * data, hide the system app now and let the /data/app scan pick it up
9403         * again.
9404         */
9405        if (shouldHideSystemApp) {
9406            synchronized (mPackages) {
9407                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9408            }
9409        }
9410
9411        return scannedPkg;
9412    }
9413
9414    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9415        // Derive the new package synthetic package name
9416        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9417                + pkg.staticSharedLibVersion);
9418    }
9419
9420    private static String fixProcessName(String defProcessName,
9421            String processName) {
9422        if (processName == null) {
9423            return defProcessName;
9424        }
9425        return processName;
9426    }
9427
9428    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9429            throws PackageManagerException {
9430        if (pkgSetting.signatures.mSignatures != null) {
9431            // Already existing package. Make sure signatures match
9432            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9433                    == PackageManager.SIGNATURE_MATCH;
9434            if (!match) {
9435                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9436                        == PackageManager.SIGNATURE_MATCH;
9437            }
9438            if (!match) {
9439                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9440                        == PackageManager.SIGNATURE_MATCH;
9441            }
9442            if (!match) {
9443                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9444                        + pkg.packageName + " signatures do not match the "
9445                        + "previously installed version; ignoring!");
9446            }
9447        }
9448
9449        // Check for shared user signatures
9450        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9451            // Already existing package. Make sure signatures match
9452            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9453                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9454            if (!match) {
9455                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9456                        == PackageManager.SIGNATURE_MATCH;
9457            }
9458            if (!match) {
9459                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9460                        == PackageManager.SIGNATURE_MATCH;
9461            }
9462            if (!match) {
9463                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9464                        "Package " + pkg.packageName
9465                        + " has no signatures that match those in shared user "
9466                        + pkgSetting.sharedUser.name + "; ignoring!");
9467            }
9468        }
9469    }
9470
9471    /**
9472     * Enforces that only the system UID or root's UID can call a method exposed
9473     * via Binder.
9474     *
9475     * @param message used as message if SecurityException is thrown
9476     * @throws SecurityException if the caller is not system or root
9477     */
9478    private static final void enforceSystemOrRoot(String message) {
9479        final int uid = Binder.getCallingUid();
9480        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9481            throw new SecurityException(message);
9482        }
9483    }
9484
9485    @Override
9486    public void performFstrimIfNeeded() {
9487        enforceSystemOrRoot("Only the system can request fstrim");
9488
9489        // Before everything else, see whether we need to fstrim.
9490        try {
9491            IStorageManager sm = PackageHelper.getStorageManager();
9492            if (sm != null) {
9493                boolean doTrim = false;
9494                final long interval = android.provider.Settings.Global.getLong(
9495                        mContext.getContentResolver(),
9496                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9497                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9498                if (interval > 0) {
9499                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9500                    if (timeSinceLast > interval) {
9501                        doTrim = true;
9502                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9503                                + "; running immediately");
9504                    }
9505                }
9506                if (doTrim) {
9507                    final boolean dexOptDialogShown;
9508                    synchronized (mPackages) {
9509                        dexOptDialogShown = mDexOptDialogShown;
9510                    }
9511                    if (!isFirstBoot() && dexOptDialogShown) {
9512                        try {
9513                            ActivityManager.getService().showBootMessage(
9514                                    mContext.getResources().getString(
9515                                            R.string.android_upgrading_fstrim), true);
9516                        } catch (RemoteException e) {
9517                        }
9518                    }
9519                    sm.runMaintenance();
9520                }
9521            } else {
9522                Slog.e(TAG, "storageManager service unavailable!");
9523            }
9524        } catch (RemoteException e) {
9525            // Can't happen; StorageManagerService is local
9526        }
9527    }
9528
9529    @Override
9530    public void updatePackagesIfNeeded() {
9531        enforceSystemOrRoot("Only the system can request package update");
9532
9533        // We need to re-extract after an OTA.
9534        boolean causeUpgrade = isUpgrade();
9535
9536        // First boot or factory reset.
9537        // Note: we also handle devices that are upgrading to N right now as if it is their
9538        //       first boot, as they do not have profile data.
9539        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9540
9541        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9542        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9543
9544        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9545            return;
9546        }
9547
9548        List<PackageParser.Package> pkgs;
9549        synchronized (mPackages) {
9550            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9551        }
9552
9553        final long startTime = System.nanoTime();
9554        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9555                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9556                    false /* bootComplete */);
9557
9558        final int elapsedTimeSeconds =
9559                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9560
9561        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9562        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9563        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9564        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9565        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9566    }
9567
9568    /*
9569     * Return the prebuilt profile path given a package base code path.
9570     */
9571    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9572        return pkg.baseCodePath + ".prof";
9573    }
9574
9575    /**
9576     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9577     * containing statistics about the invocation. The array consists of three elements,
9578     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9579     * and {@code numberOfPackagesFailed}.
9580     */
9581    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9582            String compilerFilter, boolean bootComplete) {
9583
9584        int numberOfPackagesVisited = 0;
9585        int numberOfPackagesOptimized = 0;
9586        int numberOfPackagesSkipped = 0;
9587        int numberOfPackagesFailed = 0;
9588        final int numberOfPackagesToDexopt = pkgs.size();
9589
9590        for (PackageParser.Package pkg : pkgs) {
9591            numberOfPackagesVisited++;
9592
9593            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9594                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9595                // that are already compiled.
9596                File profileFile = new File(getPrebuildProfilePath(pkg));
9597                // Copy profile if it exists.
9598                if (profileFile.exists()) {
9599                    try {
9600                        // We could also do this lazily before calling dexopt in
9601                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9602                        // is that we don't have a good way to say "do this only once".
9603                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9604                                pkg.applicationInfo.uid, pkg.packageName)) {
9605                            Log.e(TAG, "Installer failed to copy system profile!");
9606                        }
9607                    } catch (Exception e) {
9608                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9609                                e);
9610                    }
9611                }
9612            }
9613
9614            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9615                if (DEBUG_DEXOPT) {
9616                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9617                }
9618                numberOfPackagesSkipped++;
9619                continue;
9620            }
9621
9622            if (DEBUG_DEXOPT) {
9623                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9624                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9625            }
9626
9627            if (showDialog) {
9628                try {
9629                    ActivityManager.getService().showBootMessage(
9630                            mContext.getResources().getString(R.string.android_upgrading_apk,
9631                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9632                } catch (RemoteException e) {
9633                }
9634                synchronized (mPackages) {
9635                    mDexOptDialogShown = true;
9636                }
9637            }
9638
9639            // If the OTA updates a system app which was previously preopted to a non-preopted state
9640            // the app might end up being verified at runtime. That's because by default the apps
9641            // are verify-profile but for preopted apps there's no profile.
9642            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9643            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9644            // filter (by default 'quicken').
9645            // Note that at this stage unused apps are already filtered.
9646            if (isSystemApp(pkg) &&
9647                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9648                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9649                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9650            }
9651
9652            // checkProfiles is false to avoid merging profiles during boot which
9653            // might interfere with background compilation (b/28612421).
9654            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9655            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9656            // trade-off worth doing to save boot time work.
9657            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9658            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9659                    pkg.packageName,
9660                    compilerFilter,
9661                    dexoptFlags));
9662
9663            if (pkg.isSystemApp()) {
9664                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9665                // too much boot after an OTA.
9666                int secondaryDexoptFlags = dexoptFlags |
9667                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9668                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9669                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9670                        pkg.packageName,
9671                        compilerFilter,
9672                        secondaryDexoptFlags));
9673            }
9674
9675            // TODO(shubhamajmera): Record secondary dexopt stats.
9676            switch (primaryDexOptStaus) {
9677                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9678                    numberOfPackagesOptimized++;
9679                    break;
9680                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9681                    numberOfPackagesSkipped++;
9682                    break;
9683                case PackageDexOptimizer.DEX_OPT_FAILED:
9684                    numberOfPackagesFailed++;
9685                    break;
9686                default:
9687                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9688                    break;
9689            }
9690        }
9691
9692        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9693                numberOfPackagesFailed };
9694    }
9695
9696    @Override
9697    public void notifyPackageUse(String packageName, int reason) {
9698        synchronized (mPackages) {
9699            final int callingUid = Binder.getCallingUid();
9700            final int callingUserId = UserHandle.getUserId(callingUid);
9701            if (getInstantAppPackageName(callingUid) != null) {
9702                if (!isCallerSameApp(packageName, callingUid)) {
9703                    return;
9704                }
9705            } else {
9706                if (isInstantApp(packageName, callingUserId)) {
9707                    return;
9708                }
9709            }
9710            final PackageParser.Package p = mPackages.get(packageName);
9711            if (p == null) {
9712                return;
9713            }
9714            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9715        }
9716    }
9717
9718    @Override
9719    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9720            List<String> classPaths, String loaderIsa) {
9721        int userId = UserHandle.getCallingUserId();
9722        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9723        if (ai == null) {
9724            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9725                + loadingPackageName + ", user=" + userId);
9726            return;
9727        }
9728        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9729    }
9730
9731    @Override
9732    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9733            IDexModuleRegisterCallback callback) {
9734        int userId = UserHandle.getCallingUserId();
9735        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9736        DexManager.RegisterDexModuleResult result;
9737        if (ai == null) {
9738            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9739                     " calling user. package=" + packageName + ", user=" + userId);
9740            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9741        } else {
9742            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9743        }
9744
9745        if (callback != null) {
9746            mHandler.post(() -> {
9747                try {
9748                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9749                } catch (RemoteException e) {
9750                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9751                }
9752            });
9753        }
9754    }
9755
9756    /**
9757     * Ask the package manager to perform a dex-opt with the given compiler filter.
9758     *
9759     * Note: exposed only for the shell command to allow moving packages explicitly to a
9760     *       definite state.
9761     */
9762    @Override
9763    public boolean performDexOptMode(String packageName,
9764            boolean checkProfiles, String targetCompilerFilter, boolean force,
9765            boolean bootComplete, String splitName) {
9766        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9767                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9768                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9769        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9770                splitName, flags));
9771    }
9772
9773    /**
9774     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9775     * secondary dex files belonging to the given package.
9776     *
9777     * Note: exposed only for the shell command to allow moving packages explicitly to a
9778     *       definite state.
9779     */
9780    @Override
9781    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9782            boolean force) {
9783        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9784                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9785                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9786                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9787        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9788    }
9789
9790    /*package*/ boolean performDexOpt(DexoptOptions options) {
9791        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9792            return false;
9793        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9794            return false;
9795        }
9796
9797        if (options.isDexoptOnlySecondaryDex()) {
9798            return mDexManager.dexoptSecondaryDex(options);
9799        } else {
9800            int dexoptStatus = performDexOptWithStatus(options);
9801            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9802        }
9803    }
9804
9805    /**
9806     * Perform dexopt on the given package and return one of following result:
9807     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9808     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9809     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9810     */
9811    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9812        return performDexOptTraced(options);
9813    }
9814
9815    private int performDexOptTraced(DexoptOptions options) {
9816        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9817        try {
9818            return performDexOptInternal(options);
9819        } finally {
9820            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9821        }
9822    }
9823
9824    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9825    // if the package can now be considered up to date for the given filter.
9826    private int performDexOptInternal(DexoptOptions options) {
9827        PackageParser.Package p;
9828        synchronized (mPackages) {
9829            p = mPackages.get(options.getPackageName());
9830            if (p == null) {
9831                // Package could not be found. Report failure.
9832                return PackageDexOptimizer.DEX_OPT_FAILED;
9833            }
9834            mPackageUsage.maybeWriteAsync(mPackages);
9835            mCompilerStats.maybeWriteAsync();
9836        }
9837        long callingId = Binder.clearCallingIdentity();
9838        try {
9839            synchronized (mInstallLock) {
9840                return performDexOptInternalWithDependenciesLI(p, options);
9841            }
9842        } finally {
9843            Binder.restoreCallingIdentity(callingId);
9844        }
9845    }
9846
9847    public ArraySet<String> getOptimizablePackages() {
9848        ArraySet<String> pkgs = new ArraySet<String>();
9849        synchronized (mPackages) {
9850            for (PackageParser.Package p : mPackages.values()) {
9851                if (PackageDexOptimizer.canOptimizePackage(p)) {
9852                    pkgs.add(p.packageName);
9853                }
9854            }
9855        }
9856        return pkgs;
9857    }
9858
9859    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9860            DexoptOptions options) {
9861        // Select the dex optimizer based on the force parameter.
9862        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9863        //       allocate an object here.
9864        PackageDexOptimizer pdo = options.isForce()
9865                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9866                : mPackageDexOptimizer;
9867
9868        // Dexopt all dependencies first. Note: we ignore the return value and march on
9869        // on errors.
9870        // Note that we are going to call performDexOpt on those libraries as many times as
9871        // they are referenced in packages. When we do a batch of performDexOpt (for example
9872        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9873        // and the first package that uses the library will dexopt it. The
9874        // others will see that the compiled code for the library is up to date.
9875        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9876        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9877        if (!deps.isEmpty()) {
9878            for (PackageParser.Package depPackage : deps) {
9879                // TODO: Analyze and investigate if we (should) profile libraries.
9880                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9881                        getOrCreateCompilerPackageStats(depPackage),
9882                        true /* isUsedByOtherApps */,
9883                        options);
9884            }
9885        }
9886        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9887                getOrCreateCompilerPackageStats(p),
9888                mDexManager.isUsedByOtherApps(p.packageName), options);
9889    }
9890
9891    /**
9892     * Reconcile the information we have about the secondary dex files belonging to
9893     * {@code packagName} and the actual dex files. For all dex files that were
9894     * deleted, update the internal records and delete the generated oat files.
9895     */
9896    @Override
9897    public void reconcileSecondaryDexFiles(String packageName) {
9898        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9899            return;
9900        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9901            return;
9902        }
9903        mDexManager.reconcileSecondaryDexFiles(packageName);
9904    }
9905
9906    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9907    // a reference there.
9908    /*package*/ DexManager getDexManager() {
9909        return mDexManager;
9910    }
9911
9912    /**
9913     * Execute the background dexopt job immediately.
9914     */
9915    @Override
9916    public boolean runBackgroundDexoptJob() {
9917        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9918            return false;
9919        }
9920        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9921    }
9922
9923    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9924        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9925                || p.usesStaticLibraries != null) {
9926            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9927            Set<String> collectedNames = new HashSet<>();
9928            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9929
9930            retValue.remove(p);
9931
9932            return retValue;
9933        } else {
9934            return Collections.emptyList();
9935        }
9936    }
9937
9938    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9939            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9940        if (!collectedNames.contains(p.packageName)) {
9941            collectedNames.add(p.packageName);
9942            collected.add(p);
9943
9944            if (p.usesLibraries != null) {
9945                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9946                        null, collected, collectedNames);
9947            }
9948            if (p.usesOptionalLibraries != null) {
9949                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9950                        null, collected, collectedNames);
9951            }
9952            if (p.usesStaticLibraries != null) {
9953                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9954                        p.usesStaticLibrariesVersions, collected, collectedNames);
9955            }
9956        }
9957    }
9958
9959    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9960            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9961        final int libNameCount = libs.size();
9962        for (int i = 0; i < libNameCount; i++) {
9963            String libName = libs.get(i);
9964            int version = (versions != null && versions.length == libNameCount)
9965                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9966            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9967            if (libPkg != null) {
9968                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9969            }
9970        }
9971    }
9972
9973    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9974        synchronized (mPackages) {
9975            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9976            if (libEntry != null) {
9977                return mPackages.get(libEntry.apk);
9978            }
9979            return null;
9980        }
9981    }
9982
9983    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9984        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9985        if (versionedLib == null) {
9986            return null;
9987        }
9988        return versionedLib.get(version);
9989    }
9990
9991    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9992        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9993                pkg.staticSharedLibName);
9994        if (versionedLib == null) {
9995            return null;
9996        }
9997        int previousLibVersion = -1;
9998        final int versionCount = versionedLib.size();
9999        for (int i = 0; i < versionCount; i++) {
10000            final int libVersion = versionedLib.keyAt(i);
10001            if (libVersion < pkg.staticSharedLibVersion) {
10002                previousLibVersion = Math.max(previousLibVersion, libVersion);
10003            }
10004        }
10005        if (previousLibVersion >= 0) {
10006            return versionedLib.get(previousLibVersion);
10007        }
10008        return null;
10009    }
10010
10011    public void shutdown() {
10012        mPackageUsage.writeNow(mPackages);
10013        mCompilerStats.writeNow();
10014        mDexManager.savePackageDexUsageNow();
10015    }
10016
10017    @Override
10018    public void dumpProfiles(String packageName) {
10019        PackageParser.Package pkg;
10020        synchronized (mPackages) {
10021            pkg = mPackages.get(packageName);
10022            if (pkg == null) {
10023                throw new IllegalArgumentException("Unknown package: " + packageName);
10024            }
10025        }
10026        /* Only the shell, root, or the app user should be able to dump profiles. */
10027        int callingUid = Binder.getCallingUid();
10028        if (callingUid != Process.SHELL_UID &&
10029            callingUid != Process.ROOT_UID &&
10030            callingUid != pkg.applicationInfo.uid) {
10031            throw new SecurityException("dumpProfiles");
10032        }
10033
10034        synchronized (mInstallLock) {
10035            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10036            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10037            try {
10038                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10039                String codePaths = TextUtils.join(";", allCodePaths);
10040                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10041            } catch (InstallerException e) {
10042                Slog.w(TAG, "Failed to dump profiles", e);
10043            }
10044            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10045        }
10046    }
10047
10048    @Override
10049    public void forceDexOpt(String packageName) {
10050        enforceSystemOrRoot("forceDexOpt");
10051
10052        PackageParser.Package pkg;
10053        synchronized (mPackages) {
10054            pkg = mPackages.get(packageName);
10055            if (pkg == null) {
10056                throw new IllegalArgumentException("Unknown package: " + packageName);
10057            }
10058        }
10059
10060        synchronized (mInstallLock) {
10061            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10062
10063            // Whoever is calling forceDexOpt wants a compiled package.
10064            // Don't use profiles since that may cause compilation to be skipped.
10065            final int res = performDexOptInternalWithDependenciesLI(
10066                    pkg,
10067                    new DexoptOptions(packageName,
10068                            getDefaultCompilerFilter(),
10069                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10070
10071            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10072            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10073                throw new IllegalStateException("Failed to dexopt: " + res);
10074            }
10075        }
10076    }
10077
10078    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10079        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10080            Slog.w(TAG, "Unable to update from " + oldPkg.name
10081                    + " to " + newPkg.packageName
10082                    + ": old package not in system partition");
10083            return false;
10084        } else if (mPackages.get(oldPkg.name) != null) {
10085            Slog.w(TAG, "Unable to update from " + oldPkg.name
10086                    + " to " + newPkg.packageName
10087                    + ": old package still exists");
10088            return false;
10089        }
10090        return true;
10091    }
10092
10093    void removeCodePathLI(File codePath) {
10094        if (codePath.isDirectory()) {
10095            try {
10096                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10097            } catch (InstallerException e) {
10098                Slog.w(TAG, "Failed to remove code path", e);
10099            }
10100        } else {
10101            codePath.delete();
10102        }
10103    }
10104
10105    private int[] resolveUserIds(int userId) {
10106        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10107    }
10108
10109    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10110        if (pkg == null) {
10111            Slog.wtf(TAG, "Package was null!", new Throwable());
10112            return;
10113        }
10114        clearAppDataLeafLIF(pkg, userId, flags);
10115        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10116        for (int i = 0; i < childCount; i++) {
10117            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10118        }
10119    }
10120
10121    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10122        final PackageSetting ps;
10123        synchronized (mPackages) {
10124            ps = mSettings.mPackages.get(pkg.packageName);
10125        }
10126        for (int realUserId : resolveUserIds(userId)) {
10127            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10128            try {
10129                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10130                        ceDataInode);
10131            } catch (InstallerException e) {
10132                Slog.w(TAG, String.valueOf(e));
10133            }
10134        }
10135    }
10136
10137    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10138        if (pkg == null) {
10139            Slog.wtf(TAG, "Package was null!", new Throwable());
10140            return;
10141        }
10142        destroyAppDataLeafLIF(pkg, userId, flags);
10143        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10144        for (int i = 0; i < childCount; i++) {
10145            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10146        }
10147    }
10148
10149    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10150        final PackageSetting ps;
10151        synchronized (mPackages) {
10152            ps = mSettings.mPackages.get(pkg.packageName);
10153        }
10154        for (int realUserId : resolveUserIds(userId)) {
10155            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10156            try {
10157                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10158                        ceDataInode);
10159            } catch (InstallerException e) {
10160                Slog.w(TAG, String.valueOf(e));
10161            }
10162            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10163        }
10164    }
10165
10166    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10167        if (pkg == null) {
10168            Slog.wtf(TAG, "Package was null!", new Throwable());
10169            return;
10170        }
10171        destroyAppProfilesLeafLIF(pkg);
10172        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10173        for (int i = 0; i < childCount; i++) {
10174            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10175        }
10176    }
10177
10178    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10179        try {
10180            mInstaller.destroyAppProfiles(pkg.packageName);
10181        } catch (InstallerException e) {
10182            Slog.w(TAG, String.valueOf(e));
10183        }
10184    }
10185
10186    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10187        if (pkg == null) {
10188            Slog.wtf(TAG, "Package was null!", new Throwable());
10189            return;
10190        }
10191        clearAppProfilesLeafLIF(pkg);
10192        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10193        for (int i = 0; i < childCount; i++) {
10194            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10195        }
10196    }
10197
10198    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10199        try {
10200            mInstaller.clearAppProfiles(pkg.packageName);
10201        } catch (InstallerException e) {
10202            Slog.w(TAG, String.valueOf(e));
10203        }
10204    }
10205
10206    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10207            long lastUpdateTime) {
10208        // Set parent install/update time
10209        PackageSetting ps = (PackageSetting) pkg.mExtras;
10210        if (ps != null) {
10211            ps.firstInstallTime = firstInstallTime;
10212            ps.lastUpdateTime = lastUpdateTime;
10213        }
10214        // Set children install/update time
10215        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10216        for (int i = 0; i < childCount; i++) {
10217            PackageParser.Package childPkg = pkg.childPackages.get(i);
10218            ps = (PackageSetting) childPkg.mExtras;
10219            if (ps != null) {
10220                ps.firstInstallTime = firstInstallTime;
10221                ps.lastUpdateTime = lastUpdateTime;
10222            }
10223        }
10224    }
10225
10226    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10227            PackageParser.Package changingLib) {
10228        if (file.path != null) {
10229            usesLibraryFiles.add(file.path);
10230            return;
10231        }
10232        PackageParser.Package p = mPackages.get(file.apk);
10233        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10234            // If we are doing this while in the middle of updating a library apk,
10235            // then we need to make sure to use that new apk for determining the
10236            // dependencies here.  (We haven't yet finished committing the new apk
10237            // to the package manager state.)
10238            if (p == null || p.packageName.equals(changingLib.packageName)) {
10239                p = changingLib;
10240            }
10241        }
10242        if (p != null) {
10243            usesLibraryFiles.addAll(p.getAllCodePaths());
10244            if (p.usesLibraryFiles != null) {
10245                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10246            }
10247        }
10248    }
10249
10250    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10251            PackageParser.Package changingLib) throws PackageManagerException {
10252        if (pkg == null) {
10253            return;
10254        }
10255        ArraySet<String> usesLibraryFiles = null;
10256        if (pkg.usesLibraries != null) {
10257            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10258                    null, null, pkg.packageName, changingLib, true, null);
10259        }
10260        if (pkg.usesStaticLibraries != null) {
10261            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10262                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10263                    pkg.packageName, changingLib, true, usesLibraryFiles);
10264        }
10265        if (pkg.usesOptionalLibraries != null) {
10266            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10267                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
10268        }
10269        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10270            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10271        } else {
10272            pkg.usesLibraryFiles = null;
10273        }
10274    }
10275
10276    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10277            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10278            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10279            boolean required, @Nullable ArraySet<String> outUsedLibraries)
10280            throws PackageManagerException {
10281        final int libCount = requestedLibraries.size();
10282        for (int i = 0; i < libCount; i++) {
10283            final String libName = requestedLibraries.get(i);
10284            final int libVersion = requiredVersions != null ? requiredVersions[i]
10285                    : SharedLibraryInfo.VERSION_UNDEFINED;
10286            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10287            if (libEntry == null) {
10288                if (required) {
10289                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10290                            "Package " + packageName + " requires unavailable shared library "
10291                                    + libName + "; failing!");
10292                } else if (DEBUG_SHARED_LIBRARIES) {
10293                    Slog.i(TAG, "Package " + packageName
10294                            + " desires unavailable shared library "
10295                            + libName + "; ignoring!");
10296                }
10297            } else {
10298                if (requiredVersions != null && requiredCertDigests != null) {
10299                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10300                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10301                            "Package " + packageName + " requires unavailable static shared"
10302                                    + " library " + libName + " version "
10303                                    + libEntry.info.getVersion() + "; failing!");
10304                    }
10305
10306                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10307                    if (libPkg == null) {
10308                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10309                                "Package " + packageName + " requires unavailable static shared"
10310                                        + " library; failing!");
10311                    }
10312
10313                    String expectedCertDigest = requiredCertDigests[i];
10314                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10315                                libPkg.mSignatures[0]);
10316                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10317                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10318                                "Package " + packageName + " requires differently signed" +
10319                                        " static shared library; failing!");
10320                    }
10321                }
10322
10323                if (outUsedLibraries == null) {
10324                    outUsedLibraries = new ArraySet<>();
10325                }
10326                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10327            }
10328        }
10329        return outUsedLibraries;
10330    }
10331
10332    private static boolean hasString(List<String> list, List<String> which) {
10333        if (list == null) {
10334            return false;
10335        }
10336        for (int i=list.size()-1; i>=0; i--) {
10337            for (int j=which.size()-1; j>=0; j--) {
10338                if (which.get(j).equals(list.get(i))) {
10339                    return true;
10340                }
10341            }
10342        }
10343        return false;
10344    }
10345
10346    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10347            PackageParser.Package changingPkg) {
10348        ArrayList<PackageParser.Package> res = null;
10349        for (PackageParser.Package pkg : mPackages.values()) {
10350            if (changingPkg != null
10351                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10352                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10353                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10354                            changingPkg.staticSharedLibName)) {
10355                return null;
10356            }
10357            if (res == null) {
10358                res = new ArrayList<>();
10359            }
10360            res.add(pkg);
10361            try {
10362                updateSharedLibrariesLPr(pkg, changingPkg);
10363            } catch (PackageManagerException e) {
10364                // If a system app update or an app and a required lib missing we
10365                // delete the package and for updated system apps keep the data as
10366                // it is better for the user to reinstall than to be in an limbo
10367                // state. Also libs disappearing under an app should never happen
10368                // - just in case.
10369                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10370                    final int flags = pkg.isUpdatedSystemApp()
10371                            ? PackageManager.DELETE_KEEP_DATA : 0;
10372                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10373                            flags , null, true, null);
10374                }
10375                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10376            }
10377        }
10378        return res;
10379    }
10380
10381    /**
10382     * Derive the value of the {@code cpuAbiOverride} based on the provided
10383     * value and an optional stored value from the package settings.
10384     */
10385    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10386        String cpuAbiOverride = null;
10387
10388        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10389            cpuAbiOverride = null;
10390        } else if (abiOverride != null) {
10391            cpuAbiOverride = abiOverride;
10392        } else if (settings != null) {
10393            cpuAbiOverride = settings.cpuAbiOverrideString;
10394        }
10395
10396        return cpuAbiOverride;
10397    }
10398
10399    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10400            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10401                    throws PackageManagerException {
10402        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10403        // If the package has children and this is the first dive in the function
10404        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10405        // whether all packages (parent and children) would be successfully scanned
10406        // before the actual scan since scanning mutates internal state and we want
10407        // to atomically install the package and its children.
10408        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10409            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10410                scanFlags |= SCAN_CHECK_ONLY;
10411            }
10412        } else {
10413            scanFlags &= ~SCAN_CHECK_ONLY;
10414        }
10415
10416        final PackageParser.Package scannedPkg;
10417        try {
10418            // Scan the parent
10419            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10420            // Scan the children
10421            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10422            for (int i = 0; i < childCount; i++) {
10423                PackageParser.Package childPkg = pkg.childPackages.get(i);
10424                scanPackageLI(childPkg, policyFlags,
10425                        scanFlags, currentTime, user);
10426            }
10427        } finally {
10428            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10429        }
10430
10431        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10432            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10433        }
10434
10435        return scannedPkg;
10436    }
10437
10438    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10439            int scanFlags, long currentTime, @Nullable UserHandle user)
10440                    throws PackageManagerException {
10441        boolean success = false;
10442        try {
10443            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10444                    currentTime, user);
10445            success = true;
10446            return res;
10447        } finally {
10448            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10449                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10450                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10451                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10452                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10453            }
10454        }
10455    }
10456
10457    /**
10458     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10459     */
10460    private static boolean apkHasCode(String fileName) {
10461        StrictJarFile jarFile = null;
10462        try {
10463            jarFile = new StrictJarFile(fileName,
10464                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10465            return jarFile.findEntry("classes.dex") != null;
10466        } catch (IOException ignore) {
10467        } finally {
10468            try {
10469                if (jarFile != null) {
10470                    jarFile.close();
10471                }
10472            } catch (IOException ignore) {}
10473        }
10474        return false;
10475    }
10476
10477    /**
10478     * Enforces code policy for the package. This ensures that if an APK has
10479     * declared hasCode="true" in its manifest that the APK actually contains
10480     * code.
10481     *
10482     * @throws PackageManagerException If bytecode could not be found when it should exist
10483     */
10484    private static void assertCodePolicy(PackageParser.Package pkg)
10485            throws PackageManagerException {
10486        final boolean shouldHaveCode =
10487                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10488        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10489            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10490                    "Package " + pkg.baseCodePath + " code is missing");
10491        }
10492
10493        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10494            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10495                final boolean splitShouldHaveCode =
10496                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10497                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10498                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10499                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10500                }
10501            }
10502        }
10503    }
10504
10505    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10506            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10507                    throws PackageManagerException {
10508        if (DEBUG_PACKAGE_SCANNING) {
10509            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10510                Log.d(TAG, "Scanning package " + pkg.packageName);
10511        }
10512
10513        applyPolicy(pkg, policyFlags);
10514
10515        assertPackageIsValid(pkg, policyFlags, scanFlags);
10516
10517        // Initialize package source and resource directories
10518        final File scanFile = new File(pkg.codePath);
10519        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10520        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10521
10522        SharedUserSetting suid = null;
10523        PackageSetting pkgSetting = null;
10524
10525        // Getting the package setting may have a side-effect, so if we
10526        // are only checking if scan would succeed, stash a copy of the
10527        // old setting to restore at the end.
10528        PackageSetting nonMutatedPs = null;
10529
10530        // We keep references to the derived CPU Abis from settings in oder to reuse
10531        // them in the case where we're not upgrading or booting for the first time.
10532        String primaryCpuAbiFromSettings = null;
10533        String secondaryCpuAbiFromSettings = null;
10534
10535        // writer
10536        synchronized (mPackages) {
10537            if (pkg.mSharedUserId != null) {
10538                // SIDE EFFECTS; may potentially allocate a new shared user
10539                suid = mSettings.getSharedUserLPw(
10540                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10541                if (DEBUG_PACKAGE_SCANNING) {
10542                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10543                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10544                                + "): packages=" + suid.packages);
10545                }
10546            }
10547
10548            // Check if we are renaming from an original package name.
10549            PackageSetting origPackage = null;
10550            String realName = null;
10551            if (pkg.mOriginalPackages != null) {
10552                // This package may need to be renamed to a previously
10553                // installed name.  Let's check on that...
10554                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10555                if (pkg.mOriginalPackages.contains(renamed)) {
10556                    // This package had originally been installed as the
10557                    // original name, and we have already taken care of
10558                    // transitioning to the new one.  Just update the new
10559                    // one to continue using the old name.
10560                    realName = pkg.mRealPackage;
10561                    if (!pkg.packageName.equals(renamed)) {
10562                        // Callers into this function may have already taken
10563                        // care of renaming the package; only do it here if
10564                        // it is not already done.
10565                        pkg.setPackageName(renamed);
10566                    }
10567                } else {
10568                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10569                        if ((origPackage = mSettings.getPackageLPr(
10570                                pkg.mOriginalPackages.get(i))) != null) {
10571                            // We do have the package already installed under its
10572                            // original name...  should we use it?
10573                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10574                                // New package is not compatible with original.
10575                                origPackage = null;
10576                                continue;
10577                            } else if (origPackage.sharedUser != null) {
10578                                // Make sure uid is compatible between packages.
10579                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10580                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10581                                            + " to " + pkg.packageName + ": old uid "
10582                                            + origPackage.sharedUser.name
10583                                            + " differs from " + pkg.mSharedUserId);
10584                                    origPackage = null;
10585                                    continue;
10586                                }
10587                                // TODO: Add case when shared user id is added [b/28144775]
10588                            } else {
10589                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10590                                        + pkg.packageName + " to old name " + origPackage.name);
10591                            }
10592                            break;
10593                        }
10594                    }
10595                }
10596            }
10597
10598            if (mTransferedPackages.contains(pkg.packageName)) {
10599                Slog.w(TAG, "Package " + pkg.packageName
10600                        + " was transferred to another, but its .apk remains");
10601            }
10602
10603            // See comments in nonMutatedPs declaration
10604            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10605                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10606                if (foundPs != null) {
10607                    nonMutatedPs = new PackageSetting(foundPs);
10608                }
10609            }
10610
10611            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10612                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10613                if (foundPs != null) {
10614                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10615                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10616                }
10617            }
10618
10619            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10620            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10621                PackageManagerService.reportSettingsProblem(Log.WARN,
10622                        "Package " + pkg.packageName + " shared user changed from "
10623                                + (pkgSetting.sharedUser != null
10624                                        ? pkgSetting.sharedUser.name : "<nothing>")
10625                                + " to "
10626                                + (suid != null ? suid.name : "<nothing>")
10627                                + "; replacing with new");
10628                pkgSetting = null;
10629            }
10630            final PackageSetting oldPkgSetting =
10631                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10632            final PackageSetting disabledPkgSetting =
10633                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10634
10635            String[] usesStaticLibraries = null;
10636            if (pkg.usesStaticLibraries != null) {
10637                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10638                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10639            }
10640
10641            if (pkgSetting == null) {
10642                final String parentPackageName = (pkg.parentPackage != null)
10643                        ? pkg.parentPackage.packageName : null;
10644                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10645                // REMOVE SharedUserSetting from method; update in a separate call
10646                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10647                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10648                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10649                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10650                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10651                        true /*allowInstall*/, instantApp, parentPackageName,
10652                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10653                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10654                // SIDE EFFECTS; updates system state; move elsewhere
10655                if (origPackage != null) {
10656                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10657                }
10658                mSettings.addUserToSettingLPw(pkgSetting);
10659            } else {
10660                // REMOVE SharedUserSetting from method; update in a separate call.
10661                //
10662                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10663                // secondaryCpuAbi are not known at this point so we always update them
10664                // to null here, only to reset them at a later point.
10665                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10666                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10667                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10668                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10669                        UserManagerService.getInstance(), usesStaticLibraries,
10670                        pkg.usesStaticLibrariesVersions);
10671            }
10672            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10673            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10674
10675            // SIDE EFFECTS; modifies system state; move elsewhere
10676            if (pkgSetting.origPackage != null) {
10677                // If we are first transitioning from an original package,
10678                // fix up the new package's name now.  We need to do this after
10679                // looking up the package under its new name, so getPackageLP
10680                // can take care of fiddling things correctly.
10681                pkg.setPackageName(origPackage.name);
10682
10683                // File a report about this.
10684                String msg = "New package " + pkgSetting.realName
10685                        + " renamed to replace old package " + pkgSetting.name;
10686                reportSettingsProblem(Log.WARN, msg);
10687
10688                // Make a note of it.
10689                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10690                    mTransferedPackages.add(origPackage.name);
10691                }
10692
10693                // No longer need to retain this.
10694                pkgSetting.origPackage = null;
10695            }
10696
10697            // SIDE EFFECTS; modifies system state; move elsewhere
10698            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10699                // Make a note of it.
10700                mTransferedPackages.add(pkg.packageName);
10701            }
10702
10703            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10704                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10705            }
10706
10707            if ((scanFlags & SCAN_BOOTING) == 0
10708                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10709                // Check all shared libraries and map to their actual file path.
10710                // We only do this here for apps not on a system dir, because those
10711                // are the only ones that can fail an install due to this.  We
10712                // will take care of the system apps by updating all of their
10713                // library paths after the scan is done. Also during the initial
10714                // scan don't update any libs as we do this wholesale after all
10715                // apps are scanned to avoid dependency based scanning.
10716                updateSharedLibrariesLPr(pkg, null);
10717            }
10718
10719            if (mFoundPolicyFile) {
10720                SELinuxMMAC.assignSeInfoValue(pkg);
10721            }
10722            pkg.applicationInfo.uid = pkgSetting.appId;
10723            pkg.mExtras = pkgSetting;
10724
10725
10726            // Static shared libs have same package with different versions where
10727            // we internally use a synthetic package name to allow multiple versions
10728            // of the same package, therefore we need to compare signatures against
10729            // the package setting for the latest library version.
10730            PackageSetting signatureCheckPs = pkgSetting;
10731            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10732                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10733                if (libraryEntry != null) {
10734                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10735                }
10736            }
10737
10738            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10739                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10740                    // We just determined the app is signed correctly, so bring
10741                    // over the latest parsed certs.
10742                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10743                } else {
10744                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10745                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10746                                "Package " + pkg.packageName + " upgrade keys do not match the "
10747                                + "previously installed version");
10748                    } else {
10749                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10750                        String msg = "System package " + pkg.packageName
10751                                + " signature changed; retaining data.";
10752                        reportSettingsProblem(Log.WARN, msg);
10753                    }
10754                }
10755            } else {
10756                try {
10757                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10758                    verifySignaturesLP(signatureCheckPs, pkg);
10759                    // We just determined the app is signed correctly, so bring
10760                    // over the latest parsed certs.
10761                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10762                } catch (PackageManagerException e) {
10763                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10764                        throw e;
10765                    }
10766                    // The signature has changed, but this package is in the system
10767                    // image...  let's recover!
10768                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10769                    // However...  if this package is part of a shared user, but it
10770                    // doesn't match the signature of the shared user, let's fail.
10771                    // What this means is that you can't change the signatures
10772                    // associated with an overall shared user, which doesn't seem all
10773                    // that unreasonable.
10774                    if (signatureCheckPs.sharedUser != null) {
10775                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10776                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10777                            throw new PackageManagerException(
10778                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10779                                    "Signature mismatch for shared user: "
10780                                            + pkgSetting.sharedUser);
10781                        }
10782                    }
10783                    // File a report about this.
10784                    String msg = "System package " + pkg.packageName
10785                            + " signature changed; retaining data.";
10786                    reportSettingsProblem(Log.WARN, msg);
10787                }
10788            }
10789
10790            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10791                // This package wants to adopt ownership of permissions from
10792                // another package.
10793                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10794                    final String origName = pkg.mAdoptPermissions.get(i);
10795                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10796                    if (orig != null) {
10797                        if (verifyPackageUpdateLPr(orig, pkg)) {
10798                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10799                                    + pkg.packageName);
10800                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10801                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10802                        }
10803                    }
10804                }
10805            }
10806        }
10807
10808        pkg.applicationInfo.processName = fixProcessName(
10809                pkg.applicationInfo.packageName,
10810                pkg.applicationInfo.processName);
10811
10812        if (pkg != mPlatformPackage) {
10813            // Get all of our default paths setup
10814            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10815        }
10816
10817        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10818
10819        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10820            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10821                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10822                final boolean extractNativeLibs = !pkg.isLibrary();
10823                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10824                        mAppLib32InstallDir);
10825                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10826
10827                // Some system apps still use directory structure for native libraries
10828                // in which case we might end up not detecting abi solely based on apk
10829                // structure. Try to detect abi based on directory structure.
10830                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10831                        pkg.applicationInfo.primaryCpuAbi == null) {
10832                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10833                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10834                }
10835            } else {
10836                // This is not a first boot or an upgrade, don't bother deriving the
10837                // ABI during the scan. Instead, trust the value that was stored in the
10838                // package setting.
10839                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10840                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10841
10842                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10843
10844                if (DEBUG_ABI_SELECTION) {
10845                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10846                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10847                        pkg.applicationInfo.secondaryCpuAbi);
10848                }
10849            }
10850        } else {
10851            if ((scanFlags & SCAN_MOVE) != 0) {
10852                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10853                // but we already have this packages package info in the PackageSetting. We just
10854                // use that and derive the native library path based on the new codepath.
10855                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10856                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10857            }
10858
10859            // Set native library paths again. For moves, the path will be updated based on the
10860            // ABIs we've determined above. For non-moves, the path will be updated based on the
10861            // ABIs we determined during compilation, but the path will depend on the final
10862            // package path (after the rename away from the stage path).
10863            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10864        }
10865
10866        // This is a special case for the "system" package, where the ABI is
10867        // dictated by the zygote configuration (and init.rc). We should keep track
10868        // of this ABI so that we can deal with "normal" applications that run under
10869        // the same UID correctly.
10870        if (mPlatformPackage == pkg) {
10871            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10872                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10873        }
10874
10875        // If there's a mismatch between the abi-override in the package setting
10876        // and the abiOverride specified for the install. Warn about this because we
10877        // would've already compiled the app without taking the package setting into
10878        // account.
10879        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10880            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10881                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10882                        " for package " + pkg.packageName);
10883            }
10884        }
10885
10886        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10887        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10888        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10889
10890        // Copy the derived override back to the parsed package, so that we can
10891        // update the package settings accordingly.
10892        pkg.cpuAbiOverride = cpuAbiOverride;
10893
10894        if (DEBUG_ABI_SELECTION) {
10895            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10896                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10897                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10898        }
10899
10900        // Push the derived path down into PackageSettings so we know what to
10901        // clean up at uninstall time.
10902        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10903
10904        if (DEBUG_ABI_SELECTION) {
10905            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10906                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10907                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10908        }
10909
10910        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10911        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10912            // We don't do this here during boot because we can do it all
10913            // at once after scanning all existing packages.
10914            //
10915            // We also do this *before* we perform dexopt on this package, so that
10916            // we can avoid redundant dexopts, and also to make sure we've got the
10917            // code and package path correct.
10918            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10919        }
10920
10921        if (mFactoryTest && pkg.requestedPermissions.contains(
10922                android.Manifest.permission.FACTORY_TEST)) {
10923            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10924        }
10925
10926        if (isSystemApp(pkg)) {
10927            pkgSetting.isOrphaned = true;
10928        }
10929
10930        // Take care of first install / last update times.
10931        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10932        if (currentTime != 0) {
10933            if (pkgSetting.firstInstallTime == 0) {
10934                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10935            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10936                pkgSetting.lastUpdateTime = currentTime;
10937            }
10938        } else if (pkgSetting.firstInstallTime == 0) {
10939            // We need *something*.  Take time time stamp of the file.
10940            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10941        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10942            if (scanFileTime != pkgSetting.timeStamp) {
10943                // A package on the system image has changed; consider this
10944                // to be an update.
10945                pkgSetting.lastUpdateTime = scanFileTime;
10946            }
10947        }
10948        pkgSetting.setTimeStamp(scanFileTime);
10949
10950        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10951            if (nonMutatedPs != null) {
10952                synchronized (mPackages) {
10953                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10954                }
10955            }
10956        } else {
10957            final int userId = user == null ? 0 : user.getIdentifier();
10958            // Modify state for the given package setting
10959            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10960                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10961            if (pkgSetting.getInstantApp(userId)) {
10962                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10963            }
10964        }
10965        return pkg;
10966    }
10967
10968    /**
10969     * Applies policy to the parsed package based upon the given policy flags.
10970     * Ensures the package is in a good state.
10971     * <p>
10972     * Implementation detail: This method must NOT have any side effect. It would
10973     * ideally be static, but, it requires locks to read system state.
10974     */
10975    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10976        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10977            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10978            if (pkg.applicationInfo.isDirectBootAware()) {
10979                // we're direct boot aware; set for all components
10980                for (PackageParser.Service s : pkg.services) {
10981                    s.info.encryptionAware = s.info.directBootAware = true;
10982                }
10983                for (PackageParser.Provider p : pkg.providers) {
10984                    p.info.encryptionAware = p.info.directBootAware = true;
10985                }
10986                for (PackageParser.Activity a : pkg.activities) {
10987                    a.info.encryptionAware = a.info.directBootAware = true;
10988                }
10989                for (PackageParser.Activity r : pkg.receivers) {
10990                    r.info.encryptionAware = r.info.directBootAware = true;
10991                }
10992            }
10993            if (compressedFileExists(pkg.baseCodePath)) {
10994                pkg.isStub = true;
10995            }
10996        } else {
10997            // Only allow system apps to be flagged as core apps.
10998            pkg.coreApp = false;
10999            // clear flags not applicable to regular apps
11000            pkg.applicationInfo.privateFlags &=
11001                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11002            pkg.applicationInfo.privateFlags &=
11003                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11004        }
11005        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11006
11007        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11008            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11009        }
11010
11011        if (!isSystemApp(pkg)) {
11012            // Only system apps can use these features.
11013            pkg.mOriginalPackages = null;
11014            pkg.mRealPackage = null;
11015            pkg.mAdoptPermissions = null;
11016        }
11017    }
11018
11019    /**
11020     * Asserts the parsed package is valid according to the given policy. If the
11021     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11022     * <p>
11023     * Implementation detail: This method must NOT have any side effects. It would
11024     * ideally be static, but, it requires locks to read system state.
11025     *
11026     * @throws PackageManagerException If the package fails any of the validation checks
11027     */
11028    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11029            throws PackageManagerException {
11030        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11031            assertCodePolicy(pkg);
11032        }
11033
11034        if (pkg.applicationInfo.getCodePath() == null ||
11035                pkg.applicationInfo.getResourcePath() == null) {
11036            // Bail out. The resource and code paths haven't been set.
11037            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11038                    "Code and resource paths haven't been set correctly");
11039        }
11040
11041        // Make sure we're not adding any bogus keyset info
11042        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11043        ksms.assertScannedPackageValid(pkg);
11044
11045        synchronized (mPackages) {
11046            // The special "android" package can only be defined once
11047            if (pkg.packageName.equals("android")) {
11048                if (mAndroidApplication != null) {
11049                    Slog.w(TAG, "*************************************************");
11050                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11051                    Slog.w(TAG, " codePath=" + pkg.codePath);
11052                    Slog.w(TAG, "*************************************************");
11053                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11054                            "Core android package being redefined.  Skipping.");
11055                }
11056            }
11057
11058            // A package name must be unique; don't allow duplicates
11059            if (mPackages.containsKey(pkg.packageName)) {
11060                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11061                        "Application package " + pkg.packageName
11062                        + " already installed.  Skipping duplicate.");
11063            }
11064
11065            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11066                // Static libs have a synthetic package name containing the version
11067                // but we still want the base name to be unique.
11068                if (mPackages.containsKey(pkg.manifestPackageName)) {
11069                    throw new PackageManagerException(
11070                            "Duplicate static shared lib provider package");
11071                }
11072
11073                // Static shared libraries should have at least O target SDK
11074                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11075                    throw new PackageManagerException(
11076                            "Packages declaring static-shared libs must target O SDK or higher");
11077                }
11078
11079                // Package declaring static a shared lib cannot be instant apps
11080                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11081                    throw new PackageManagerException(
11082                            "Packages declaring static-shared libs cannot be instant apps");
11083                }
11084
11085                // Package declaring static a shared lib cannot be renamed since the package
11086                // name is synthetic and apps can't code around package manager internals.
11087                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11088                    throw new PackageManagerException(
11089                            "Packages declaring static-shared libs cannot be renamed");
11090                }
11091
11092                // Package declaring static a shared lib cannot declare child packages
11093                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11094                    throw new PackageManagerException(
11095                            "Packages declaring static-shared libs cannot have child packages");
11096                }
11097
11098                // Package declaring static a shared lib cannot declare dynamic libs
11099                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11100                    throw new PackageManagerException(
11101                            "Packages declaring static-shared libs cannot declare dynamic libs");
11102                }
11103
11104                // Package declaring static a shared lib cannot declare shared users
11105                if (pkg.mSharedUserId != null) {
11106                    throw new PackageManagerException(
11107                            "Packages declaring static-shared libs cannot declare shared users");
11108                }
11109
11110                // Static shared libs cannot declare activities
11111                if (!pkg.activities.isEmpty()) {
11112                    throw new PackageManagerException(
11113                            "Static shared libs cannot declare activities");
11114                }
11115
11116                // Static shared libs cannot declare services
11117                if (!pkg.services.isEmpty()) {
11118                    throw new PackageManagerException(
11119                            "Static shared libs cannot declare services");
11120                }
11121
11122                // Static shared libs cannot declare providers
11123                if (!pkg.providers.isEmpty()) {
11124                    throw new PackageManagerException(
11125                            "Static shared libs cannot declare content providers");
11126                }
11127
11128                // Static shared libs cannot declare receivers
11129                if (!pkg.receivers.isEmpty()) {
11130                    throw new PackageManagerException(
11131                            "Static shared libs cannot declare broadcast receivers");
11132                }
11133
11134                // Static shared libs cannot declare permission groups
11135                if (!pkg.permissionGroups.isEmpty()) {
11136                    throw new PackageManagerException(
11137                            "Static shared libs cannot declare permission groups");
11138                }
11139
11140                // Static shared libs cannot declare permissions
11141                if (!pkg.permissions.isEmpty()) {
11142                    throw new PackageManagerException(
11143                            "Static shared libs cannot declare permissions");
11144                }
11145
11146                // Static shared libs cannot declare protected broadcasts
11147                if (pkg.protectedBroadcasts != null) {
11148                    throw new PackageManagerException(
11149                            "Static shared libs cannot declare protected broadcasts");
11150                }
11151
11152                // Static shared libs cannot be overlay targets
11153                if (pkg.mOverlayTarget != null) {
11154                    throw new PackageManagerException(
11155                            "Static shared libs cannot be overlay targets");
11156                }
11157
11158                // The version codes must be ordered as lib versions
11159                int minVersionCode = Integer.MIN_VALUE;
11160                int maxVersionCode = Integer.MAX_VALUE;
11161
11162                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11163                        pkg.staticSharedLibName);
11164                if (versionedLib != null) {
11165                    final int versionCount = versionedLib.size();
11166                    for (int i = 0; i < versionCount; i++) {
11167                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11168                        final int libVersionCode = libInfo.getDeclaringPackage()
11169                                .getVersionCode();
11170                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11171                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11172                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11173                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11174                        } else {
11175                            minVersionCode = maxVersionCode = libVersionCode;
11176                            break;
11177                        }
11178                    }
11179                }
11180                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11181                    throw new PackageManagerException("Static shared"
11182                            + " lib version codes must be ordered as lib versions");
11183                }
11184            }
11185
11186            // Only privileged apps and updated privileged apps can add child packages.
11187            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11188                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11189                    throw new PackageManagerException("Only privileged apps can add child "
11190                            + "packages. Ignoring package " + pkg.packageName);
11191                }
11192                final int childCount = pkg.childPackages.size();
11193                for (int i = 0; i < childCount; i++) {
11194                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11195                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11196                            childPkg.packageName)) {
11197                        throw new PackageManagerException("Can't override child of "
11198                                + "another disabled app. Ignoring package " + pkg.packageName);
11199                    }
11200                }
11201            }
11202
11203            // If we're only installing presumed-existing packages, require that the
11204            // scanned APK is both already known and at the path previously established
11205            // for it.  Previously unknown packages we pick up normally, but if we have an
11206            // a priori expectation about this package's install presence, enforce it.
11207            // With a singular exception for new system packages. When an OTA contains
11208            // a new system package, we allow the codepath to change from a system location
11209            // to the user-installed location. If we don't allow this change, any newer,
11210            // user-installed version of the application will be ignored.
11211            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11212                if (mExpectingBetter.containsKey(pkg.packageName)) {
11213                    logCriticalInfo(Log.WARN,
11214                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11215                } else {
11216                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11217                    if (known != null) {
11218                        if (DEBUG_PACKAGE_SCANNING) {
11219                            Log.d(TAG, "Examining " + pkg.codePath
11220                                    + " and requiring known paths " + known.codePathString
11221                                    + " & " + known.resourcePathString);
11222                        }
11223                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11224                                || !pkg.applicationInfo.getResourcePath().equals(
11225                                        known.resourcePathString)) {
11226                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11227                                    "Application package " + pkg.packageName
11228                                    + " found at " + pkg.applicationInfo.getCodePath()
11229                                    + " but expected at " + known.codePathString
11230                                    + "; ignoring.");
11231                        }
11232                    }
11233                }
11234            }
11235
11236            // Verify that this new package doesn't have any content providers
11237            // that conflict with existing packages.  Only do this if the
11238            // package isn't already installed, since we don't want to break
11239            // things that are installed.
11240            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11241                final int N = pkg.providers.size();
11242                int i;
11243                for (i=0; i<N; i++) {
11244                    PackageParser.Provider p = pkg.providers.get(i);
11245                    if (p.info.authority != null) {
11246                        String names[] = p.info.authority.split(";");
11247                        for (int j = 0; j < names.length; j++) {
11248                            if (mProvidersByAuthority.containsKey(names[j])) {
11249                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11250                                final String otherPackageName =
11251                                        ((other != null && other.getComponentName() != null) ?
11252                                                other.getComponentName().getPackageName() : "?");
11253                                throw new PackageManagerException(
11254                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11255                                        "Can't install because provider name " + names[j]
11256                                                + " (in package " + pkg.applicationInfo.packageName
11257                                                + ") is already used by " + otherPackageName);
11258                            }
11259                        }
11260                    }
11261                }
11262            }
11263        }
11264    }
11265
11266    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11267            int type, String declaringPackageName, int declaringVersionCode) {
11268        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11269        if (versionedLib == null) {
11270            versionedLib = new SparseArray<>();
11271            mSharedLibraries.put(name, versionedLib);
11272            if (type == SharedLibraryInfo.TYPE_STATIC) {
11273                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11274            }
11275        } else if (versionedLib.indexOfKey(version) >= 0) {
11276            return false;
11277        }
11278        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11279                version, type, declaringPackageName, declaringVersionCode);
11280        versionedLib.put(version, libEntry);
11281        return true;
11282    }
11283
11284    private boolean removeSharedLibraryLPw(String name, int version) {
11285        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11286        if (versionedLib == null) {
11287            return false;
11288        }
11289        final int libIdx = versionedLib.indexOfKey(version);
11290        if (libIdx < 0) {
11291            return false;
11292        }
11293        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11294        versionedLib.remove(version);
11295        if (versionedLib.size() <= 0) {
11296            mSharedLibraries.remove(name);
11297            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11298                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11299                        .getPackageName());
11300            }
11301        }
11302        return true;
11303    }
11304
11305    /**
11306     * Adds a scanned package to the system. When this method is finished, the package will
11307     * be available for query, resolution, etc...
11308     */
11309    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11310            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11311        final String pkgName = pkg.packageName;
11312        if (mCustomResolverComponentName != null &&
11313                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11314            setUpCustomResolverActivity(pkg);
11315        }
11316
11317        if (pkg.packageName.equals("android")) {
11318            synchronized (mPackages) {
11319                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11320                    // Set up information for our fall-back user intent resolution activity.
11321                    mPlatformPackage = pkg;
11322                    pkg.mVersionCode = mSdkVersion;
11323                    mAndroidApplication = pkg.applicationInfo;
11324                    if (!mResolverReplaced) {
11325                        mResolveActivity.applicationInfo = mAndroidApplication;
11326                        mResolveActivity.name = ResolverActivity.class.getName();
11327                        mResolveActivity.packageName = mAndroidApplication.packageName;
11328                        mResolveActivity.processName = "system:ui";
11329                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11330                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11331                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11332                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11333                        mResolveActivity.exported = true;
11334                        mResolveActivity.enabled = true;
11335                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11336                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11337                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11338                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11339                                | ActivityInfo.CONFIG_ORIENTATION
11340                                | ActivityInfo.CONFIG_KEYBOARD
11341                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11342                        mResolveInfo.activityInfo = mResolveActivity;
11343                        mResolveInfo.priority = 0;
11344                        mResolveInfo.preferredOrder = 0;
11345                        mResolveInfo.match = 0;
11346                        mResolveComponentName = new ComponentName(
11347                                mAndroidApplication.packageName, mResolveActivity.name);
11348                    }
11349                }
11350            }
11351        }
11352
11353        ArrayList<PackageParser.Package> clientLibPkgs = null;
11354        // writer
11355        synchronized (mPackages) {
11356            boolean hasStaticSharedLibs = false;
11357
11358            // Any app can add new static shared libraries
11359            if (pkg.staticSharedLibName != null) {
11360                // Static shared libs don't allow renaming as they have synthetic package
11361                // names to allow install of multiple versions, so use name from manifest.
11362                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11363                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11364                        pkg.manifestPackageName, pkg.mVersionCode)) {
11365                    hasStaticSharedLibs = true;
11366                } else {
11367                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11368                                + pkg.staticSharedLibName + " already exists; skipping");
11369                }
11370                // Static shared libs cannot be updated once installed since they
11371                // use synthetic package name which includes the version code, so
11372                // not need to update other packages's shared lib dependencies.
11373            }
11374
11375            if (!hasStaticSharedLibs
11376                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11377                // Only system apps can add new dynamic shared libraries.
11378                if (pkg.libraryNames != null) {
11379                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11380                        String name = pkg.libraryNames.get(i);
11381                        boolean allowed = false;
11382                        if (pkg.isUpdatedSystemApp()) {
11383                            // New library entries can only be added through the
11384                            // system image.  This is important to get rid of a lot
11385                            // of nasty edge cases: for example if we allowed a non-
11386                            // system update of the app to add a library, then uninstalling
11387                            // the update would make the library go away, and assumptions
11388                            // we made such as through app install filtering would now
11389                            // have allowed apps on the device which aren't compatible
11390                            // with it.  Better to just have the restriction here, be
11391                            // conservative, and create many fewer cases that can negatively
11392                            // impact the user experience.
11393                            final PackageSetting sysPs = mSettings
11394                                    .getDisabledSystemPkgLPr(pkg.packageName);
11395                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11396                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11397                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11398                                        allowed = true;
11399                                        break;
11400                                    }
11401                                }
11402                            }
11403                        } else {
11404                            allowed = true;
11405                        }
11406                        if (allowed) {
11407                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11408                                    SharedLibraryInfo.VERSION_UNDEFINED,
11409                                    SharedLibraryInfo.TYPE_DYNAMIC,
11410                                    pkg.packageName, pkg.mVersionCode)) {
11411                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11412                                        + name + " already exists; skipping");
11413                            }
11414                        } else {
11415                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11416                                    + name + " that is not declared on system image; skipping");
11417                        }
11418                    }
11419
11420                    if ((scanFlags & SCAN_BOOTING) == 0) {
11421                        // If we are not booting, we need to update any applications
11422                        // that are clients of our shared library.  If we are booting,
11423                        // this will all be done once the scan is complete.
11424                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11425                    }
11426                }
11427            }
11428        }
11429
11430        if ((scanFlags & SCAN_BOOTING) != 0) {
11431            // No apps can run during boot scan, so they don't need to be frozen
11432        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11433            // Caller asked to not kill app, so it's probably not frozen
11434        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11435            // Caller asked us to ignore frozen check for some reason; they
11436            // probably didn't know the package name
11437        } else {
11438            // We're doing major surgery on this package, so it better be frozen
11439            // right now to keep it from launching
11440            checkPackageFrozen(pkgName);
11441        }
11442
11443        // Also need to kill any apps that are dependent on the library.
11444        if (clientLibPkgs != null) {
11445            for (int i=0; i<clientLibPkgs.size(); i++) {
11446                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11447                killApplication(clientPkg.applicationInfo.packageName,
11448                        clientPkg.applicationInfo.uid, "update lib");
11449            }
11450        }
11451
11452        // writer
11453        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11454
11455        synchronized (mPackages) {
11456            // We don't expect installation to fail beyond this point
11457
11458            // Add the new setting to mSettings
11459            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11460            // Add the new setting to mPackages
11461            mPackages.put(pkg.applicationInfo.packageName, pkg);
11462            // Make sure we don't accidentally delete its data.
11463            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11464            while (iter.hasNext()) {
11465                PackageCleanItem item = iter.next();
11466                if (pkgName.equals(item.packageName)) {
11467                    iter.remove();
11468                }
11469            }
11470
11471            // Add the package's KeySets to the global KeySetManagerService
11472            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11473            ksms.addScannedPackageLPw(pkg);
11474
11475            int N = pkg.providers.size();
11476            StringBuilder r = null;
11477            int i;
11478            for (i=0; i<N; i++) {
11479                PackageParser.Provider p = pkg.providers.get(i);
11480                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11481                        p.info.processName);
11482                mProviders.addProvider(p);
11483                p.syncable = p.info.isSyncable;
11484                if (p.info.authority != null) {
11485                    String names[] = p.info.authority.split(";");
11486                    p.info.authority = null;
11487                    for (int j = 0; j < names.length; j++) {
11488                        if (j == 1 && p.syncable) {
11489                            // We only want the first authority for a provider to possibly be
11490                            // syncable, so if we already added this provider using a different
11491                            // authority clear the syncable flag. We copy the provider before
11492                            // changing it because the mProviders object contains a reference
11493                            // to a provider that we don't want to change.
11494                            // Only do this for the second authority since the resulting provider
11495                            // object can be the same for all future authorities for this provider.
11496                            p = new PackageParser.Provider(p);
11497                            p.syncable = false;
11498                        }
11499                        if (!mProvidersByAuthority.containsKey(names[j])) {
11500                            mProvidersByAuthority.put(names[j], p);
11501                            if (p.info.authority == null) {
11502                                p.info.authority = names[j];
11503                            } else {
11504                                p.info.authority = p.info.authority + ";" + names[j];
11505                            }
11506                            if (DEBUG_PACKAGE_SCANNING) {
11507                                if (chatty)
11508                                    Log.d(TAG, "Registered content provider: " + names[j]
11509                                            + ", className = " + p.info.name + ", isSyncable = "
11510                                            + p.info.isSyncable);
11511                            }
11512                        } else {
11513                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11514                            Slog.w(TAG, "Skipping provider name " + names[j] +
11515                                    " (in package " + pkg.applicationInfo.packageName +
11516                                    "): name already used by "
11517                                    + ((other != null && other.getComponentName() != null)
11518                                            ? other.getComponentName().getPackageName() : "?"));
11519                        }
11520                    }
11521                }
11522                if (chatty) {
11523                    if (r == null) {
11524                        r = new StringBuilder(256);
11525                    } else {
11526                        r.append(' ');
11527                    }
11528                    r.append(p.info.name);
11529                }
11530            }
11531            if (r != null) {
11532                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11533            }
11534
11535            N = pkg.services.size();
11536            r = null;
11537            for (i=0; i<N; i++) {
11538                PackageParser.Service s = pkg.services.get(i);
11539                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11540                        s.info.processName);
11541                mServices.addService(s);
11542                if (chatty) {
11543                    if (r == null) {
11544                        r = new StringBuilder(256);
11545                    } else {
11546                        r.append(' ');
11547                    }
11548                    r.append(s.info.name);
11549                }
11550            }
11551            if (r != null) {
11552                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11553            }
11554
11555            N = pkg.receivers.size();
11556            r = null;
11557            for (i=0; i<N; i++) {
11558                PackageParser.Activity a = pkg.receivers.get(i);
11559                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11560                        a.info.processName);
11561                mReceivers.addActivity(a, "receiver");
11562                if (chatty) {
11563                    if (r == null) {
11564                        r = new StringBuilder(256);
11565                    } else {
11566                        r.append(' ');
11567                    }
11568                    r.append(a.info.name);
11569                }
11570            }
11571            if (r != null) {
11572                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11573            }
11574
11575            N = pkg.activities.size();
11576            r = null;
11577            for (i=0; i<N; i++) {
11578                PackageParser.Activity a = pkg.activities.get(i);
11579                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11580                        a.info.processName);
11581                mActivities.addActivity(a, "activity");
11582                if (chatty) {
11583                    if (r == null) {
11584                        r = new StringBuilder(256);
11585                    } else {
11586                        r.append(' ');
11587                    }
11588                    r.append(a.info.name);
11589                }
11590            }
11591            if (r != null) {
11592                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11593            }
11594
11595            N = pkg.permissionGroups.size();
11596            r = null;
11597            for (i=0; i<N; i++) {
11598                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11599                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11600                final String curPackageName = cur == null ? null : cur.info.packageName;
11601                // Dont allow ephemeral apps to define new permission groups.
11602                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11603                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11604                            + pg.info.packageName
11605                            + " ignored: instant apps cannot define new permission groups.");
11606                    continue;
11607                }
11608                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11609                if (cur == null || isPackageUpdate) {
11610                    mPermissionGroups.put(pg.info.name, pg);
11611                    if (chatty) {
11612                        if (r == null) {
11613                            r = new StringBuilder(256);
11614                        } else {
11615                            r.append(' ');
11616                        }
11617                        if (isPackageUpdate) {
11618                            r.append("UPD:");
11619                        }
11620                        r.append(pg.info.name);
11621                    }
11622                } else {
11623                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11624                            + pg.info.packageName + " ignored: original from "
11625                            + cur.info.packageName);
11626                    if (chatty) {
11627                        if (r == null) {
11628                            r = new StringBuilder(256);
11629                        } else {
11630                            r.append(' ');
11631                        }
11632                        r.append("DUP:");
11633                        r.append(pg.info.name);
11634                    }
11635                }
11636            }
11637            if (r != null) {
11638                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11639            }
11640
11641            N = pkg.permissions.size();
11642            r = null;
11643            for (i=0; i<N; i++) {
11644                PackageParser.Permission p = pkg.permissions.get(i);
11645
11646                // Dont allow ephemeral apps to define new permissions.
11647                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11648                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11649                            + p.info.packageName
11650                            + " ignored: instant apps cannot define new permissions.");
11651                    continue;
11652                }
11653
11654                // Assume by default that we did not install this permission into the system.
11655                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11656
11657                // Now that permission groups have a special meaning, we ignore permission
11658                // groups for legacy apps to prevent unexpected behavior. In particular,
11659                // permissions for one app being granted to someone just because they happen
11660                // to be in a group defined by another app (before this had no implications).
11661                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11662                    p.group = mPermissionGroups.get(p.info.group);
11663                    // Warn for a permission in an unknown group.
11664                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11665                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11666                                + p.info.packageName + " in an unknown group " + p.info.group);
11667                    }
11668                }
11669
11670                ArrayMap<String, BasePermission> permissionMap =
11671                        p.tree ? mSettings.mPermissionTrees
11672                                : mSettings.mPermissions;
11673                BasePermission bp = permissionMap.get(p.info.name);
11674
11675                // Allow system apps to redefine non-system permissions
11676                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11677                    final boolean currentOwnerIsSystem = (bp.perm != null
11678                            && isSystemApp(bp.perm.owner));
11679                    if (isSystemApp(p.owner)) {
11680                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11681                            // It's a built-in permission and no owner, take ownership now
11682                            bp.packageSetting = pkgSetting;
11683                            bp.perm = p;
11684                            bp.uid = pkg.applicationInfo.uid;
11685                            bp.sourcePackage = p.info.packageName;
11686                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11687                        } else if (!currentOwnerIsSystem) {
11688                            String msg = "New decl " + p.owner + " of permission  "
11689                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11690                            reportSettingsProblem(Log.WARN, msg);
11691                            bp = null;
11692                        }
11693                    }
11694                }
11695
11696                if (bp == null) {
11697                    bp = new BasePermission(p.info.name, p.info.packageName,
11698                            BasePermission.TYPE_NORMAL);
11699                    permissionMap.put(p.info.name, bp);
11700                }
11701
11702                if (bp.perm == null) {
11703                    if (bp.sourcePackage == null
11704                            || bp.sourcePackage.equals(p.info.packageName)) {
11705                        BasePermission tree = findPermissionTreeLP(p.info.name);
11706                        if (tree == null
11707                                || tree.sourcePackage.equals(p.info.packageName)) {
11708                            bp.packageSetting = pkgSetting;
11709                            bp.perm = p;
11710                            bp.uid = pkg.applicationInfo.uid;
11711                            bp.sourcePackage = p.info.packageName;
11712                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11713                            if (chatty) {
11714                                if (r == null) {
11715                                    r = new StringBuilder(256);
11716                                } else {
11717                                    r.append(' ');
11718                                }
11719                                r.append(p.info.name);
11720                            }
11721                        } else {
11722                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11723                                    + p.info.packageName + " ignored: base tree "
11724                                    + tree.name + " is from package "
11725                                    + tree.sourcePackage);
11726                        }
11727                    } else {
11728                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11729                                + p.info.packageName + " ignored: original from "
11730                                + bp.sourcePackage);
11731                    }
11732                } else if (chatty) {
11733                    if (r == null) {
11734                        r = new StringBuilder(256);
11735                    } else {
11736                        r.append(' ');
11737                    }
11738                    r.append("DUP:");
11739                    r.append(p.info.name);
11740                }
11741                if (bp.perm == p) {
11742                    bp.protectionLevel = p.info.protectionLevel;
11743                }
11744            }
11745
11746            if (r != null) {
11747                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11748            }
11749
11750            N = pkg.instrumentation.size();
11751            r = null;
11752            for (i=0; i<N; i++) {
11753                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11754                a.info.packageName = pkg.applicationInfo.packageName;
11755                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11756                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11757                a.info.splitNames = pkg.splitNames;
11758                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11759                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11760                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11761                a.info.dataDir = pkg.applicationInfo.dataDir;
11762                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11763                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11764                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11765                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11766                mInstrumentation.put(a.getComponentName(), a);
11767                if (chatty) {
11768                    if (r == null) {
11769                        r = new StringBuilder(256);
11770                    } else {
11771                        r.append(' ');
11772                    }
11773                    r.append(a.info.name);
11774                }
11775            }
11776            if (r != null) {
11777                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11778            }
11779
11780            if (pkg.protectedBroadcasts != null) {
11781                N = pkg.protectedBroadcasts.size();
11782                synchronized (mProtectedBroadcasts) {
11783                    for (i = 0; i < N; i++) {
11784                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11785                    }
11786                }
11787            }
11788        }
11789
11790        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11791    }
11792
11793    /**
11794     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11795     * is derived purely on the basis of the contents of {@code scanFile} and
11796     * {@code cpuAbiOverride}.
11797     *
11798     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11799     */
11800    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11801                                 String cpuAbiOverride, boolean extractLibs,
11802                                 File appLib32InstallDir)
11803            throws PackageManagerException {
11804        // Give ourselves some initial paths; we'll come back for another
11805        // pass once we've determined ABI below.
11806        setNativeLibraryPaths(pkg, appLib32InstallDir);
11807
11808        // We would never need to extract libs for forward-locked and external packages,
11809        // since the container service will do it for us. We shouldn't attempt to
11810        // extract libs from system app when it was not updated.
11811        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11812                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11813            extractLibs = false;
11814        }
11815
11816        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11817        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11818
11819        NativeLibraryHelper.Handle handle = null;
11820        try {
11821            handle = NativeLibraryHelper.Handle.create(pkg);
11822            // TODO(multiArch): This can be null for apps that didn't go through the
11823            // usual installation process. We can calculate it again, like we
11824            // do during install time.
11825            //
11826            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11827            // unnecessary.
11828            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11829
11830            // Null out the abis so that they can be recalculated.
11831            pkg.applicationInfo.primaryCpuAbi = null;
11832            pkg.applicationInfo.secondaryCpuAbi = null;
11833            if (isMultiArch(pkg.applicationInfo)) {
11834                // Warn if we've set an abiOverride for multi-lib packages..
11835                // By definition, we need to copy both 32 and 64 bit libraries for
11836                // such packages.
11837                if (pkg.cpuAbiOverride != null
11838                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11839                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11840                }
11841
11842                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11843                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11844                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11845                    if (extractLibs) {
11846                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11847                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11848                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11849                                useIsaSpecificSubdirs);
11850                    } else {
11851                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11852                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11853                    }
11854                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11855                }
11856
11857                // Shared library native code should be in the APK zip aligned
11858                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11859                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11860                            "Shared library native lib extraction not supported");
11861                }
11862
11863                maybeThrowExceptionForMultiArchCopy(
11864                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11865
11866                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11867                    if (extractLibs) {
11868                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11869                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11870                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11871                                useIsaSpecificSubdirs);
11872                    } else {
11873                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11874                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11875                    }
11876                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11877                }
11878
11879                maybeThrowExceptionForMultiArchCopy(
11880                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11881
11882                if (abi64 >= 0) {
11883                    // Shared library native libs should be in the APK zip aligned
11884                    if (extractLibs && pkg.isLibrary()) {
11885                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11886                                "Shared library native lib extraction not supported");
11887                    }
11888                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11889                }
11890
11891                if (abi32 >= 0) {
11892                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11893                    if (abi64 >= 0) {
11894                        if (pkg.use32bitAbi) {
11895                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11896                            pkg.applicationInfo.primaryCpuAbi = abi;
11897                        } else {
11898                            pkg.applicationInfo.secondaryCpuAbi = abi;
11899                        }
11900                    } else {
11901                        pkg.applicationInfo.primaryCpuAbi = abi;
11902                    }
11903                }
11904            } else {
11905                String[] abiList = (cpuAbiOverride != null) ?
11906                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11907
11908                // Enable gross and lame hacks for apps that are built with old
11909                // SDK tools. We must scan their APKs for renderscript bitcode and
11910                // not launch them if it's present. Don't bother checking on devices
11911                // that don't have 64 bit support.
11912                boolean needsRenderScriptOverride = false;
11913                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11914                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11915                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11916                    needsRenderScriptOverride = true;
11917                }
11918
11919                final int copyRet;
11920                if (extractLibs) {
11921                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11922                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11923                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11924                } else {
11925                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11926                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11927                }
11928                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11929
11930                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11931                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11932                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11933                }
11934
11935                if (copyRet >= 0) {
11936                    // Shared libraries that have native libs must be multi-architecture
11937                    if (pkg.isLibrary()) {
11938                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11939                                "Shared library with native libs must be multiarch");
11940                    }
11941                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11942                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11943                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11944                } else if (needsRenderScriptOverride) {
11945                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11946                }
11947            }
11948        } catch (IOException ioe) {
11949            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11950        } finally {
11951            IoUtils.closeQuietly(handle);
11952        }
11953
11954        // Now that we've calculated the ABIs and determined if it's an internal app,
11955        // we will go ahead and populate the nativeLibraryPath.
11956        setNativeLibraryPaths(pkg, appLib32InstallDir);
11957    }
11958
11959    /**
11960     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11961     * i.e, so that all packages can be run inside a single process if required.
11962     *
11963     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11964     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11965     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11966     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11967     * updating a package that belongs to a shared user.
11968     *
11969     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11970     * adds unnecessary complexity.
11971     */
11972    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11973            PackageParser.Package scannedPackage) {
11974        String requiredInstructionSet = null;
11975        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11976            requiredInstructionSet = VMRuntime.getInstructionSet(
11977                     scannedPackage.applicationInfo.primaryCpuAbi);
11978        }
11979
11980        PackageSetting requirer = null;
11981        for (PackageSetting ps : packagesForUser) {
11982            // If packagesForUser contains scannedPackage, we skip it. This will happen
11983            // when scannedPackage is an update of an existing package. Without this check,
11984            // we will never be able to change the ABI of any package belonging to a shared
11985            // user, even if it's compatible with other packages.
11986            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11987                if (ps.primaryCpuAbiString == null) {
11988                    continue;
11989                }
11990
11991                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11992                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11993                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11994                    // this but there's not much we can do.
11995                    String errorMessage = "Instruction set mismatch, "
11996                            + ((requirer == null) ? "[caller]" : requirer)
11997                            + " requires " + requiredInstructionSet + " whereas " + ps
11998                            + " requires " + instructionSet;
11999                    Slog.w(TAG, errorMessage);
12000                }
12001
12002                if (requiredInstructionSet == null) {
12003                    requiredInstructionSet = instructionSet;
12004                    requirer = ps;
12005                }
12006            }
12007        }
12008
12009        if (requiredInstructionSet != null) {
12010            String adjustedAbi;
12011            if (requirer != null) {
12012                // requirer != null implies that either scannedPackage was null or that scannedPackage
12013                // did not require an ABI, in which case we have to adjust scannedPackage to match
12014                // the ABI of the set (which is the same as requirer's ABI)
12015                adjustedAbi = requirer.primaryCpuAbiString;
12016                if (scannedPackage != null) {
12017                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12018                }
12019            } else {
12020                // requirer == null implies that we're updating all ABIs in the set to
12021                // match scannedPackage.
12022                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12023            }
12024
12025            for (PackageSetting ps : packagesForUser) {
12026                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12027                    if (ps.primaryCpuAbiString != null) {
12028                        continue;
12029                    }
12030
12031                    ps.primaryCpuAbiString = adjustedAbi;
12032                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12033                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12034                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12035                        if (DEBUG_ABI_SELECTION) {
12036                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12037                                    + " (requirer="
12038                                    + (requirer != null ? requirer.pkg : "null")
12039                                    + ", scannedPackage="
12040                                    + (scannedPackage != null ? scannedPackage : "null")
12041                                    + ")");
12042                        }
12043                        try {
12044                            mInstaller.rmdex(ps.codePathString,
12045                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12046                        } catch (InstallerException ignored) {
12047                        }
12048                    }
12049                }
12050            }
12051        }
12052    }
12053
12054    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12055        synchronized (mPackages) {
12056            mResolverReplaced = true;
12057            // Set up information for custom user intent resolution activity.
12058            mResolveActivity.applicationInfo = pkg.applicationInfo;
12059            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12060            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12061            mResolveActivity.processName = pkg.applicationInfo.packageName;
12062            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12063            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12064                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12065            mResolveActivity.theme = 0;
12066            mResolveActivity.exported = true;
12067            mResolveActivity.enabled = true;
12068            mResolveInfo.activityInfo = mResolveActivity;
12069            mResolveInfo.priority = 0;
12070            mResolveInfo.preferredOrder = 0;
12071            mResolveInfo.match = 0;
12072            mResolveComponentName = mCustomResolverComponentName;
12073            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12074                    mResolveComponentName);
12075        }
12076    }
12077
12078    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12079        if (installerActivity == null) {
12080            if (DEBUG_EPHEMERAL) {
12081                Slog.d(TAG, "Clear ephemeral installer activity");
12082            }
12083            mInstantAppInstallerActivity = null;
12084            return;
12085        }
12086
12087        if (DEBUG_EPHEMERAL) {
12088            Slog.d(TAG, "Set ephemeral installer activity: "
12089                    + installerActivity.getComponentName());
12090        }
12091        // Set up information for ephemeral installer activity
12092        mInstantAppInstallerActivity = installerActivity;
12093        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12094                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12095        mInstantAppInstallerActivity.exported = true;
12096        mInstantAppInstallerActivity.enabled = true;
12097        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12098        mInstantAppInstallerInfo.priority = 0;
12099        mInstantAppInstallerInfo.preferredOrder = 1;
12100        mInstantAppInstallerInfo.isDefault = true;
12101        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12102                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12103    }
12104
12105    private static String calculateBundledApkRoot(final String codePathString) {
12106        final File codePath = new File(codePathString);
12107        final File codeRoot;
12108        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12109            codeRoot = Environment.getRootDirectory();
12110        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12111            codeRoot = Environment.getOemDirectory();
12112        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12113            codeRoot = Environment.getVendorDirectory();
12114        } else {
12115            // Unrecognized code path; take its top real segment as the apk root:
12116            // e.g. /something/app/blah.apk => /something
12117            try {
12118                File f = codePath.getCanonicalFile();
12119                File parent = f.getParentFile();    // non-null because codePath is a file
12120                File tmp;
12121                while ((tmp = parent.getParentFile()) != null) {
12122                    f = parent;
12123                    parent = tmp;
12124                }
12125                codeRoot = f;
12126                Slog.w(TAG, "Unrecognized code path "
12127                        + codePath + " - using " + codeRoot);
12128            } catch (IOException e) {
12129                // Can't canonicalize the code path -- shenanigans?
12130                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12131                return Environment.getRootDirectory().getPath();
12132            }
12133        }
12134        return codeRoot.getPath();
12135    }
12136
12137    /**
12138     * Derive and set the location of native libraries for the given package,
12139     * which varies depending on where and how the package was installed.
12140     */
12141    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12142        final ApplicationInfo info = pkg.applicationInfo;
12143        final String codePath = pkg.codePath;
12144        final File codeFile = new File(codePath);
12145        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12146        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12147
12148        info.nativeLibraryRootDir = null;
12149        info.nativeLibraryRootRequiresIsa = false;
12150        info.nativeLibraryDir = null;
12151        info.secondaryNativeLibraryDir = null;
12152
12153        if (isApkFile(codeFile)) {
12154            // Monolithic install
12155            if (bundledApp) {
12156                // If "/system/lib64/apkname" exists, assume that is the per-package
12157                // native library directory to use; otherwise use "/system/lib/apkname".
12158                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12159                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12160                        getPrimaryInstructionSet(info));
12161
12162                // This is a bundled system app so choose the path based on the ABI.
12163                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12164                // is just the default path.
12165                final String apkName = deriveCodePathName(codePath);
12166                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12167                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12168                        apkName).getAbsolutePath();
12169
12170                if (info.secondaryCpuAbi != null) {
12171                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12172                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12173                            secondaryLibDir, apkName).getAbsolutePath();
12174                }
12175            } else if (asecApp) {
12176                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12177                        .getAbsolutePath();
12178            } else {
12179                final String apkName = deriveCodePathName(codePath);
12180                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12181                        .getAbsolutePath();
12182            }
12183
12184            info.nativeLibraryRootRequiresIsa = false;
12185            info.nativeLibraryDir = info.nativeLibraryRootDir;
12186        } else {
12187            // Cluster install
12188            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12189            info.nativeLibraryRootRequiresIsa = true;
12190
12191            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12192                    getPrimaryInstructionSet(info)).getAbsolutePath();
12193
12194            if (info.secondaryCpuAbi != null) {
12195                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12196                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12197            }
12198        }
12199    }
12200
12201    /**
12202     * Calculate the abis and roots for a bundled app. These can uniquely
12203     * be determined from the contents of the system partition, i.e whether
12204     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12205     * of this information, and instead assume that the system was built
12206     * sensibly.
12207     */
12208    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12209                                           PackageSetting pkgSetting) {
12210        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12211
12212        // If "/system/lib64/apkname" exists, assume that is the per-package
12213        // native library directory to use; otherwise use "/system/lib/apkname".
12214        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12215        setBundledAppAbi(pkg, apkRoot, apkName);
12216        // pkgSetting might be null during rescan following uninstall of updates
12217        // to a bundled app, so accommodate that possibility.  The settings in
12218        // that case will be established later from the parsed package.
12219        //
12220        // If the settings aren't null, sync them up with what we've just derived.
12221        // note that apkRoot isn't stored in the package settings.
12222        if (pkgSetting != null) {
12223            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12224            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12225        }
12226    }
12227
12228    /**
12229     * Deduces the ABI of a bundled app and sets the relevant fields on the
12230     * parsed pkg object.
12231     *
12232     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12233     *        under which system libraries are installed.
12234     * @param apkName the name of the installed package.
12235     */
12236    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12237        final File codeFile = new File(pkg.codePath);
12238
12239        final boolean has64BitLibs;
12240        final boolean has32BitLibs;
12241        if (isApkFile(codeFile)) {
12242            // Monolithic install
12243            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12244            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12245        } else {
12246            // Cluster install
12247            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12248            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12249                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12250                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12251                has64BitLibs = (new File(rootDir, isa)).exists();
12252            } else {
12253                has64BitLibs = false;
12254            }
12255            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12256                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12257                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12258                has32BitLibs = (new File(rootDir, isa)).exists();
12259            } else {
12260                has32BitLibs = false;
12261            }
12262        }
12263
12264        if (has64BitLibs && !has32BitLibs) {
12265            // The package has 64 bit libs, but not 32 bit libs. Its primary
12266            // ABI should be 64 bit. We can safely assume here that the bundled
12267            // native libraries correspond to the most preferred ABI in the list.
12268
12269            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12270            pkg.applicationInfo.secondaryCpuAbi = null;
12271        } else if (has32BitLibs && !has64BitLibs) {
12272            // The package has 32 bit libs but not 64 bit libs. Its primary
12273            // ABI should be 32 bit.
12274
12275            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12276            pkg.applicationInfo.secondaryCpuAbi = null;
12277        } else if (has32BitLibs && has64BitLibs) {
12278            // The application has both 64 and 32 bit bundled libraries. We check
12279            // here that the app declares multiArch support, and warn if it doesn't.
12280            //
12281            // We will be lenient here and record both ABIs. The primary will be the
12282            // ABI that's higher on the list, i.e, a device that's configured to prefer
12283            // 64 bit apps will see a 64 bit primary ABI,
12284
12285            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12286                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12287            }
12288
12289            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12290                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12291                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12292            } else {
12293                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12294                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12295            }
12296        } else {
12297            pkg.applicationInfo.primaryCpuAbi = null;
12298            pkg.applicationInfo.secondaryCpuAbi = null;
12299        }
12300    }
12301
12302    private void killApplication(String pkgName, int appId, String reason) {
12303        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12304    }
12305
12306    private void killApplication(String pkgName, int appId, int userId, String reason) {
12307        // Request the ActivityManager to kill the process(only for existing packages)
12308        // so that we do not end up in a confused state while the user is still using the older
12309        // version of the application while the new one gets installed.
12310        final long token = Binder.clearCallingIdentity();
12311        try {
12312            IActivityManager am = ActivityManager.getService();
12313            if (am != null) {
12314                try {
12315                    am.killApplication(pkgName, appId, userId, reason);
12316                } catch (RemoteException e) {
12317                }
12318            }
12319        } finally {
12320            Binder.restoreCallingIdentity(token);
12321        }
12322    }
12323
12324    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12325        // Remove the parent package setting
12326        PackageSetting ps = (PackageSetting) pkg.mExtras;
12327        if (ps != null) {
12328            removePackageLI(ps, chatty);
12329        }
12330        // Remove the child package setting
12331        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12332        for (int i = 0; i < childCount; i++) {
12333            PackageParser.Package childPkg = pkg.childPackages.get(i);
12334            ps = (PackageSetting) childPkg.mExtras;
12335            if (ps != null) {
12336                removePackageLI(ps, chatty);
12337            }
12338        }
12339    }
12340
12341    void removePackageLI(PackageSetting ps, boolean chatty) {
12342        if (DEBUG_INSTALL) {
12343            if (chatty)
12344                Log.d(TAG, "Removing package " + ps.name);
12345        }
12346
12347        // writer
12348        synchronized (mPackages) {
12349            mPackages.remove(ps.name);
12350            final PackageParser.Package pkg = ps.pkg;
12351            if (pkg != null) {
12352                cleanPackageDataStructuresLILPw(pkg, chatty);
12353            }
12354        }
12355    }
12356
12357    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12358        if (DEBUG_INSTALL) {
12359            if (chatty)
12360                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12361        }
12362
12363        // writer
12364        synchronized (mPackages) {
12365            // Remove the parent package
12366            mPackages.remove(pkg.applicationInfo.packageName);
12367            cleanPackageDataStructuresLILPw(pkg, chatty);
12368
12369            // Remove the child packages
12370            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12371            for (int i = 0; i < childCount; i++) {
12372                PackageParser.Package childPkg = pkg.childPackages.get(i);
12373                mPackages.remove(childPkg.applicationInfo.packageName);
12374                cleanPackageDataStructuresLILPw(childPkg, chatty);
12375            }
12376        }
12377    }
12378
12379    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12380        int N = pkg.providers.size();
12381        StringBuilder r = null;
12382        int i;
12383        for (i=0; i<N; i++) {
12384            PackageParser.Provider p = pkg.providers.get(i);
12385            mProviders.removeProvider(p);
12386            if (p.info.authority == null) {
12387
12388                /* There was another ContentProvider with this authority when
12389                 * this app was installed so this authority is null,
12390                 * Ignore it as we don't have to unregister the provider.
12391                 */
12392                continue;
12393            }
12394            String names[] = p.info.authority.split(";");
12395            for (int j = 0; j < names.length; j++) {
12396                if (mProvidersByAuthority.get(names[j]) == p) {
12397                    mProvidersByAuthority.remove(names[j]);
12398                    if (DEBUG_REMOVE) {
12399                        if (chatty)
12400                            Log.d(TAG, "Unregistered content provider: " + names[j]
12401                                    + ", className = " + p.info.name + ", isSyncable = "
12402                                    + p.info.isSyncable);
12403                    }
12404                }
12405            }
12406            if (DEBUG_REMOVE && chatty) {
12407                if (r == null) {
12408                    r = new StringBuilder(256);
12409                } else {
12410                    r.append(' ');
12411                }
12412                r.append(p.info.name);
12413            }
12414        }
12415        if (r != null) {
12416            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12417        }
12418
12419        N = pkg.services.size();
12420        r = null;
12421        for (i=0; i<N; i++) {
12422            PackageParser.Service s = pkg.services.get(i);
12423            mServices.removeService(s);
12424            if (chatty) {
12425                if (r == null) {
12426                    r = new StringBuilder(256);
12427                } else {
12428                    r.append(' ');
12429                }
12430                r.append(s.info.name);
12431            }
12432        }
12433        if (r != null) {
12434            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12435        }
12436
12437        N = pkg.receivers.size();
12438        r = null;
12439        for (i=0; i<N; i++) {
12440            PackageParser.Activity a = pkg.receivers.get(i);
12441            mReceivers.removeActivity(a, "receiver");
12442            if (DEBUG_REMOVE && chatty) {
12443                if (r == null) {
12444                    r = new StringBuilder(256);
12445                } else {
12446                    r.append(' ');
12447                }
12448                r.append(a.info.name);
12449            }
12450        }
12451        if (r != null) {
12452            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12453        }
12454
12455        N = pkg.activities.size();
12456        r = null;
12457        for (i=0; i<N; i++) {
12458            PackageParser.Activity a = pkg.activities.get(i);
12459            mActivities.removeActivity(a, "activity");
12460            if (DEBUG_REMOVE && chatty) {
12461                if (r == null) {
12462                    r = new StringBuilder(256);
12463                } else {
12464                    r.append(' ');
12465                }
12466                r.append(a.info.name);
12467            }
12468        }
12469        if (r != null) {
12470            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12471        }
12472
12473        N = pkg.permissions.size();
12474        r = null;
12475        for (i=0; i<N; i++) {
12476            PackageParser.Permission p = pkg.permissions.get(i);
12477            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12478            if (bp == null) {
12479                bp = mSettings.mPermissionTrees.get(p.info.name);
12480            }
12481            if (bp != null && bp.perm == p) {
12482                bp.perm = null;
12483                if (DEBUG_REMOVE && chatty) {
12484                    if (r == null) {
12485                        r = new StringBuilder(256);
12486                    } else {
12487                        r.append(' ');
12488                    }
12489                    r.append(p.info.name);
12490                }
12491            }
12492            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12493                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12494                if (appOpPkgs != null) {
12495                    appOpPkgs.remove(pkg.packageName);
12496                }
12497            }
12498        }
12499        if (r != null) {
12500            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12501        }
12502
12503        N = pkg.requestedPermissions.size();
12504        r = null;
12505        for (i=0; i<N; i++) {
12506            String perm = pkg.requestedPermissions.get(i);
12507            BasePermission bp = mSettings.mPermissions.get(perm);
12508            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12509                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12510                if (appOpPkgs != null) {
12511                    appOpPkgs.remove(pkg.packageName);
12512                    if (appOpPkgs.isEmpty()) {
12513                        mAppOpPermissionPackages.remove(perm);
12514                    }
12515                }
12516            }
12517        }
12518        if (r != null) {
12519            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12520        }
12521
12522        N = pkg.instrumentation.size();
12523        r = null;
12524        for (i=0; i<N; i++) {
12525            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12526            mInstrumentation.remove(a.getComponentName());
12527            if (DEBUG_REMOVE && chatty) {
12528                if (r == null) {
12529                    r = new StringBuilder(256);
12530                } else {
12531                    r.append(' ');
12532                }
12533                r.append(a.info.name);
12534            }
12535        }
12536        if (r != null) {
12537            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12538        }
12539
12540        r = null;
12541        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12542            // Only system apps can hold shared libraries.
12543            if (pkg.libraryNames != null) {
12544                for (i = 0; i < pkg.libraryNames.size(); i++) {
12545                    String name = pkg.libraryNames.get(i);
12546                    if (removeSharedLibraryLPw(name, 0)) {
12547                        if (DEBUG_REMOVE && chatty) {
12548                            if (r == null) {
12549                                r = new StringBuilder(256);
12550                            } else {
12551                                r.append(' ');
12552                            }
12553                            r.append(name);
12554                        }
12555                    }
12556                }
12557            }
12558        }
12559
12560        r = null;
12561
12562        // Any package can hold static shared libraries.
12563        if (pkg.staticSharedLibName != null) {
12564            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12565                if (DEBUG_REMOVE && chatty) {
12566                    if (r == null) {
12567                        r = new StringBuilder(256);
12568                    } else {
12569                        r.append(' ');
12570                    }
12571                    r.append(pkg.staticSharedLibName);
12572                }
12573            }
12574        }
12575
12576        if (r != null) {
12577            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12578        }
12579    }
12580
12581    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12582        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12583            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12584                return true;
12585            }
12586        }
12587        return false;
12588    }
12589
12590    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12591    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12592    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12593
12594    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12595        // Update the parent permissions
12596        updatePermissionsLPw(pkg.packageName, pkg, flags);
12597        // Update the child permissions
12598        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12599        for (int i = 0; i < childCount; i++) {
12600            PackageParser.Package childPkg = pkg.childPackages.get(i);
12601            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12602        }
12603    }
12604
12605    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12606            int flags) {
12607        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12608        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12609    }
12610
12611    private void updatePermissionsLPw(String changingPkg,
12612            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12613        // Make sure there are no dangling permission trees.
12614        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12615        while (it.hasNext()) {
12616            final BasePermission bp = it.next();
12617            if (bp.packageSetting == null) {
12618                // We may not yet have parsed the package, so just see if
12619                // we still know about its settings.
12620                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12621            }
12622            if (bp.packageSetting == null) {
12623                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12624                        + " from package " + bp.sourcePackage);
12625                it.remove();
12626            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12627                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12628                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12629                            + " from package " + bp.sourcePackage);
12630                    flags |= UPDATE_PERMISSIONS_ALL;
12631                    it.remove();
12632                }
12633            }
12634        }
12635
12636        // Make sure all dynamic permissions have been assigned to a package,
12637        // and make sure there are no dangling permissions.
12638        it = mSettings.mPermissions.values().iterator();
12639        while (it.hasNext()) {
12640            final BasePermission bp = it.next();
12641            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12642                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12643                        + bp.name + " pkg=" + bp.sourcePackage
12644                        + " info=" + bp.pendingInfo);
12645                if (bp.packageSetting == null && bp.pendingInfo != null) {
12646                    final BasePermission tree = findPermissionTreeLP(bp.name);
12647                    if (tree != null && tree.perm != null) {
12648                        bp.packageSetting = tree.packageSetting;
12649                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12650                                new PermissionInfo(bp.pendingInfo));
12651                        bp.perm.info.packageName = tree.perm.info.packageName;
12652                        bp.perm.info.name = bp.name;
12653                        bp.uid = tree.uid;
12654                    }
12655                }
12656            }
12657            if (bp.packageSetting == null) {
12658                // We may not yet have parsed the package, so just see if
12659                // we still know about its settings.
12660                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12661            }
12662            if (bp.packageSetting == null) {
12663                Slog.w(TAG, "Removing dangling permission: " + bp.name
12664                        + " from package " + bp.sourcePackage);
12665                it.remove();
12666            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12667                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12668                    Slog.i(TAG, "Removing old permission: " + bp.name
12669                            + " from package " + bp.sourcePackage);
12670                    flags |= UPDATE_PERMISSIONS_ALL;
12671                    it.remove();
12672                }
12673            }
12674        }
12675
12676        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12677        // Now update the permissions for all packages, in particular
12678        // replace the granted permissions of the system packages.
12679        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12680            for (PackageParser.Package pkg : mPackages.values()) {
12681                if (pkg != pkgInfo) {
12682                    // Only replace for packages on requested volume
12683                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12684                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12685                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12686                    grantPermissionsLPw(pkg, replace, changingPkg);
12687                }
12688            }
12689        }
12690
12691        if (pkgInfo != null) {
12692            // Only replace for packages on requested volume
12693            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12694            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12695                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12696            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12697        }
12698        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12699    }
12700
12701    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12702            String packageOfInterest) {
12703        // IMPORTANT: There are two types of permissions: install and runtime.
12704        // Install time permissions are granted when the app is installed to
12705        // all device users and users added in the future. Runtime permissions
12706        // are granted at runtime explicitly to specific users. Normal and signature
12707        // protected permissions are install time permissions. Dangerous permissions
12708        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12709        // otherwise they are runtime permissions. This function does not manage
12710        // runtime permissions except for the case an app targeting Lollipop MR1
12711        // being upgraded to target a newer SDK, in which case dangerous permissions
12712        // are transformed from install time to runtime ones.
12713
12714        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12715        if (ps == null) {
12716            return;
12717        }
12718
12719        PermissionsState permissionsState = ps.getPermissionsState();
12720        PermissionsState origPermissions = permissionsState;
12721
12722        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12723
12724        boolean runtimePermissionsRevoked = false;
12725        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12726
12727        boolean changedInstallPermission = false;
12728
12729        if (replace) {
12730            ps.installPermissionsFixed = false;
12731            if (!ps.isSharedUser()) {
12732                origPermissions = new PermissionsState(permissionsState);
12733                permissionsState.reset();
12734            } else {
12735                // We need to know only about runtime permission changes since the
12736                // calling code always writes the install permissions state but
12737                // the runtime ones are written only if changed. The only cases of
12738                // changed runtime permissions here are promotion of an install to
12739                // runtime and revocation of a runtime from a shared user.
12740                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12741                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12742                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12743                    runtimePermissionsRevoked = true;
12744                }
12745            }
12746        }
12747
12748        permissionsState.setGlobalGids(mGlobalGids);
12749
12750        final int N = pkg.requestedPermissions.size();
12751        for (int i=0; i<N; i++) {
12752            final String name = pkg.requestedPermissions.get(i);
12753            final BasePermission bp = mSettings.mPermissions.get(name);
12754            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12755                    >= Build.VERSION_CODES.M;
12756
12757            if (DEBUG_INSTALL) {
12758                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12759            }
12760
12761            if (bp == null || bp.packageSetting == null) {
12762                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12763                    if (DEBUG_PERMISSIONS) {
12764                        Slog.i(TAG, "Unknown permission " + name
12765                                + " in package " + pkg.packageName);
12766                    }
12767                }
12768                continue;
12769            }
12770
12771
12772            // Limit ephemeral apps to ephemeral allowed permissions.
12773            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12774                if (DEBUG_PERMISSIONS) {
12775                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12776                            + pkg.packageName);
12777                }
12778                continue;
12779            }
12780
12781            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12782                if (DEBUG_PERMISSIONS) {
12783                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12784                            + pkg.packageName);
12785                }
12786                continue;
12787            }
12788
12789            final String perm = bp.name;
12790            boolean allowedSig = false;
12791            int grant = GRANT_DENIED;
12792
12793            // Keep track of app op permissions.
12794            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12795                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12796                if (pkgs == null) {
12797                    pkgs = new ArraySet<>();
12798                    mAppOpPermissionPackages.put(bp.name, pkgs);
12799                }
12800                pkgs.add(pkg.packageName);
12801            }
12802
12803            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12804            switch (level) {
12805                case PermissionInfo.PROTECTION_NORMAL: {
12806                    // For all apps normal permissions are install time ones.
12807                    grant = GRANT_INSTALL;
12808                } break;
12809
12810                case PermissionInfo.PROTECTION_DANGEROUS: {
12811                    // If a permission review is required for legacy apps we represent
12812                    // their permissions as always granted runtime ones since we need
12813                    // to keep the review required permission flag per user while an
12814                    // install permission's state is shared across all users.
12815                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12816                        // For legacy apps dangerous permissions are install time ones.
12817                        grant = GRANT_INSTALL;
12818                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12819                        // For legacy apps that became modern, install becomes runtime.
12820                        grant = GRANT_UPGRADE;
12821                    } else if (mPromoteSystemApps
12822                            && isSystemApp(ps)
12823                            && mExistingSystemPackages.contains(ps.name)) {
12824                        // For legacy system apps, install becomes runtime.
12825                        // We cannot check hasInstallPermission() for system apps since those
12826                        // permissions were granted implicitly and not persisted pre-M.
12827                        grant = GRANT_UPGRADE;
12828                    } else {
12829                        // For modern apps keep runtime permissions unchanged.
12830                        grant = GRANT_RUNTIME;
12831                    }
12832                } break;
12833
12834                case PermissionInfo.PROTECTION_SIGNATURE: {
12835                    // For all apps signature permissions are install time ones.
12836                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12837                    if (allowedSig) {
12838                        grant = GRANT_INSTALL;
12839                    }
12840                } break;
12841            }
12842
12843            if (DEBUG_PERMISSIONS) {
12844                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12845            }
12846
12847            if (grant != GRANT_DENIED) {
12848                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12849                    // If this is an existing, non-system package, then
12850                    // we can't add any new permissions to it.
12851                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12852                        // Except...  if this is a permission that was added
12853                        // to the platform (note: need to only do this when
12854                        // updating the platform).
12855                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12856                            grant = GRANT_DENIED;
12857                        }
12858                    }
12859                }
12860
12861                switch (grant) {
12862                    case GRANT_INSTALL: {
12863                        // Revoke this as runtime permission to handle the case of
12864                        // a runtime permission being downgraded to an install one.
12865                        // Also in permission review mode we keep dangerous permissions
12866                        // for legacy apps
12867                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12868                            if (origPermissions.getRuntimePermissionState(
12869                                    bp.name, userId) != null) {
12870                                // Revoke the runtime permission and clear the flags.
12871                                origPermissions.revokeRuntimePermission(bp, userId);
12872                                origPermissions.updatePermissionFlags(bp, userId,
12873                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12874                                // If we revoked a permission permission, we have to write.
12875                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12876                                        changedRuntimePermissionUserIds, userId);
12877                            }
12878                        }
12879                        // Grant an install permission.
12880                        if (permissionsState.grantInstallPermission(bp) !=
12881                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12882                            changedInstallPermission = true;
12883                        }
12884                    } break;
12885
12886                    case GRANT_RUNTIME: {
12887                        // Grant previously granted runtime permissions.
12888                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12889                            PermissionState permissionState = origPermissions
12890                                    .getRuntimePermissionState(bp.name, userId);
12891                            int flags = permissionState != null
12892                                    ? permissionState.getFlags() : 0;
12893                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12894                                // Don't propagate the permission in a permission review mode if
12895                                // the former was revoked, i.e. marked to not propagate on upgrade.
12896                                // Note that in a permission review mode install permissions are
12897                                // represented as constantly granted runtime ones since we need to
12898                                // keep a per user state associated with the permission. Also the
12899                                // revoke on upgrade flag is no longer applicable and is reset.
12900                                final boolean revokeOnUpgrade = (flags & PackageManager
12901                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12902                                if (revokeOnUpgrade) {
12903                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12904                                    // Since we changed the flags, we have to write.
12905                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12906                                            changedRuntimePermissionUserIds, userId);
12907                                }
12908                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12909                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12910                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12911                                        // If we cannot put the permission as it was,
12912                                        // we have to write.
12913                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12914                                                changedRuntimePermissionUserIds, userId);
12915                                    }
12916                                }
12917
12918                                // If the app supports runtime permissions no need for a review.
12919                                if (mPermissionReviewRequired
12920                                        && appSupportsRuntimePermissions
12921                                        && (flags & PackageManager
12922                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12923                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12924                                    // Since we changed the flags, we have to write.
12925                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12926                                            changedRuntimePermissionUserIds, userId);
12927                                }
12928                            } else if (mPermissionReviewRequired
12929                                    && !appSupportsRuntimePermissions) {
12930                                // For legacy apps that need a permission review, every new
12931                                // runtime permission is granted but it is pending a review.
12932                                // We also need to review only platform defined runtime
12933                                // permissions as these are the only ones the platform knows
12934                                // how to disable the API to simulate revocation as legacy
12935                                // apps don't expect to run with revoked permissions.
12936                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12937                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12938                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12939                                        // We changed the flags, hence have to write.
12940                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12941                                                changedRuntimePermissionUserIds, userId);
12942                                    }
12943                                }
12944                                if (permissionsState.grantRuntimePermission(bp, userId)
12945                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12946                                    // We changed the permission, hence have to write.
12947                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12948                                            changedRuntimePermissionUserIds, userId);
12949                                }
12950                            }
12951                            // Propagate the permission flags.
12952                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12953                        }
12954                    } break;
12955
12956                    case GRANT_UPGRADE: {
12957                        // Grant runtime permissions for a previously held install permission.
12958                        PermissionState permissionState = origPermissions
12959                                .getInstallPermissionState(bp.name);
12960                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12961
12962                        if (origPermissions.revokeInstallPermission(bp)
12963                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12964                            // We will be transferring the permission flags, so clear them.
12965                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12966                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12967                            changedInstallPermission = true;
12968                        }
12969
12970                        // If the permission is not to be promoted to runtime we ignore it and
12971                        // also its other flags as they are not applicable to install permissions.
12972                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12973                            for (int userId : currentUserIds) {
12974                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12975                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12976                                    // Transfer the permission flags.
12977                                    permissionsState.updatePermissionFlags(bp, userId,
12978                                            flags, flags);
12979                                    // If we granted the permission, we have to write.
12980                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12981                                            changedRuntimePermissionUserIds, userId);
12982                                }
12983                            }
12984                        }
12985                    } break;
12986
12987                    default: {
12988                        if (packageOfInterest == null
12989                                || packageOfInterest.equals(pkg.packageName)) {
12990                            if (DEBUG_PERMISSIONS) {
12991                                Slog.i(TAG, "Not granting permission " + perm
12992                                        + " to package " + pkg.packageName
12993                                        + " because it was previously installed without");
12994                            }
12995                        }
12996                    } break;
12997                }
12998            } else {
12999                if (permissionsState.revokeInstallPermission(bp) !=
13000                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13001                    // Also drop the permission flags.
13002                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13003                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13004                    changedInstallPermission = true;
13005                    Slog.i(TAG, "Un-granting permission " + perm
13006                            + " from package " + pkg.packageName
13007                            + " (protectionLevel=" + bp.protectionLevel
13008                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13009                            + ")");
13010                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13011                    // Don't print warning for app op permissions, since it is fine for them
13012                    // not to be granted, there is a UI for the user to decide.
13013                    if (DEBUG_PERMISSIONS
13014                            && (packageOfInterest == null
13015                                    || packageOfInterest.equals(pkg.packageName))) {
13016                        Slog.i(TAG, "Not granting permission " + perm
13017                                + " to package " + pkg.packageName
13018                                + " (protectionLevel=" + bp.protectionLevel
13019                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13020                                + ")");
13021                    }
13022                }
13023            }
13024        }
13025
13026        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13027                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13028            // This is the first that we have heard about this package, so the
13029            // permissions we have now selected are fixed until explicitly
13030            // changed.
13031            ps.installPermissionsFixed = true;
13032        }
13033
13034        // Persist the runtime permissions state for users with changes. If permissions
13035        // were revoked because no app in the shared user declares them we have to
13036        // write synchronously to avoid losing runtime permissions state.
13037        for (int userId : changedRuntimePermissionUserIds) {
13038            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13039        }
13040    }
13041
13042    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13043        boolean allowed = false;
13044        final int NP = PackageParser.NEW_PERMISSIONS.length;
13045        for (int ip=0; ip<NP; ip++) {
13046            final PackageParser.NewPermissionInfo npi
13047                    = PackageParser.NEW_PERMISSIONS[ip];
13048            if (npi.name.equals(perm)
13049                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13050                allowed = true;
13051                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13052                        + pkg.packageName);
13053                break;
13054            }
13055        }
13056        return allowed;
13057    }
13058
13059    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13060            BasePermission bp, PermissionsState origPermissions) {
13061        boolean privilegedPermission = (bp.protectionLevel
13062                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13063        boolean privappPermissionsDisable =
13064                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13065        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13066        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13067        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13068                && !platformPackage && platformPermission) {
13069            ArraySet<String> wlPermissions = SystemConfig.getInstance()
13070                    .getPrivAppPermissions(pkg.packageName);
13071            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
13072            if (!whitelisted) {
13073                Slog.w(TAG, "Privileged permission " + perm + " for package "
13074                        + pkg.packageName + " - not in privapp-permissions whitelist");
13075                // Only report violations for apps on system image
13076                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13077                    if (mPrivappPermissionsViolations == null) {
13078                        mPrivappPermissionsViolations = new ArraySet<>();
13079                    }
13080                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13081                }
13082                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13083                    return false;
13084                }
13085            }
13086        }
13087        boolean allowed = (compareSignatures(
13088                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13089                        == PackageManager.SIGNATURE_MATCH)
13090                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13091                        == PackageManager.SIGNATURE_MATCH);
13092        if (!allowed && privilegedPermission) {
13093            if (isSystemApp(pkg)) {
13094                // For updated system applications, a system permission
13095                // is granted only if it had been defined by the original application.
13096                if (pkg.isUpdatedSystemApp()) {
13097                    final PackageSetting sysPs = mSettings
13098                            .getDisabledSystemPkgLPr(pkg.packageName);
13099                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13100                        // If the original was granted this permission, we take
13101                        // that grant decision as read and propagate it to the
13102                        // update.
13103                        if (sysPs.isPrivileged()) {
13104                            allowed = true;
13105                        }
13106                    } else {
13107                        // The system apk may have been updated with an older
13108                        // version of the one on the data partition, but which
13109                        // granted a new system permission that it didn't have
13110                        // before.  In this case we do want to allow the app to
13111                        // now get the new permission if the ancestral apk is
13112                        // privileged to get it.
13113                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13114                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13115                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13116                                    allowed = true;
13117                                    break;
13118                                }
13119                            }
13120                        }
13121                        // Also if a privileged parent package on the system image or any of
13122                        // its children requested a privileged permission, the updated child
13123                        // packages can also get the permission.
13124                        if (pkg.parentPackage != null) {
13125                            final PackageSetting disabledSysParentPs = mSettings
13126                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13127                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13128                                    && disabledSysParentPs.isPrivileged()) {
13129                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13130                                    allowed = true;
13131                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13132                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13133                                    for (int i = 0; i < count; i++) {
13134                                        PackageParser.Package disabledSysChildPkg =
13135                                                disabledSysParentPs.pkg.childPackages.get(i);
13136                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13137                                                perm)) {
13138                                            allowed = true;
13139                                            break;
13140                                        }
13141                                    }
13142                                }
13143                            }
13144                        }
13145                    }
13146                } else {
13147                    allowed = isPrivilegedApp(pkg);
13148                }
13149            }
13150        }
13151        if (!allowed) {
13152            if (!allowed && (bp.protectionLevel
13153                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13154                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13155                // If this was a previously normal/dangerous permission that got moved
13156                // to a system permission as part of the runtime permission redesign, then
13157                // we still want to blindly grant it to old apps.
13158                allowed = true;
13159            }
13160            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13161                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13162                // If this permission is to be granted to the system installer and
13163                // this app is an installer, then it gets the permission.
13164                allowed = true;
13165            }
13166            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13167                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13168                // If this permission is to be granted to the system verifier and
13169                // this app is a verifier, then it gets the permission.
13170                allowed = true;
13171            }
13172            if (!allowed && (bp.protectionLevel
13173                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13174                    && isSystemApp(pkg)) {
13175                // Any pre-installed system app is allowed to get this permission.
13176                allowed = true;
13177            }
13178            if (!allowed && (bp.protectionLevel
13179                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13180                // For development permissions, a development permission
13181                // is granted only if it was already granted.
13182                allowed = origPermissions.hasInstallPermission(perm);
13183            }
13184            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13185                    && pkg.packageName.equals(mSetupWizardPackage)) {
13186                // If this permission is to be granted to the system setup wizard and
13187                // this app is a setup wizard, then it gets the permission.
13188                allowed = true;
13189            }
13190        }
13191        return allowed;
13192    }
13193
13194    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13195        final int permCount = pkg.requestedPermissions.size();
13196        for (int j = 0; j < permCount; j++) {
13197            String requestedPermission = pkg.requestedPermissions.get(j);
13198            if (permission.equals(requestedPermission)) {
13199                return true;
13200            }
13201        }
13202        return false;
13203    }
13204
13205    final class ActivityIntentResolver
13206            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13207        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13208                boolean defaultOnly, int userId) {
13209            if (!sUserManager.exists(userId)) return null;
13210            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13211            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13212        }
13213
13214        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13215                int userId) {
13216            if (!sUserManager.exists(userId)) return null;
13217            mFlags = flags;
13218            return super.queryIntent(intent, resolvedType,
13219                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13220                    userId);
13221        }
13222
13223        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13224                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13225            if (!sUserManager.exists(userId)) return null;
13226            if (packageActivities == null) {
13227                return null;
13228            }
13229            mFlags = flags;
13230            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13231            final int N = packageActivities.size();
13232            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13233                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13234
13235            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13236            for (int i = 0; i < N; ++i) {
13237                intentFilters = packageActivities.get(i).intents;
13238                if (intentFilters != null && intentFilters.size() > 0) {
13239                    PackageParser.ActivityIntentInfo[] array =
13240                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13241                    intentFilters.toArray(array);
13242                    listCut.add(array);
13243                }
13244            }
13245            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13246        }
13247
13248        /**
13249         * Finds a privileged activity that matches the specified activity names.
13250         */
13251        private PackageParser.Activity findMatchingActivity(
13252                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13253            for (PackageParser.Activity sysActivity : activityList) {
13254                if (sysActivity.info.name.equals(activityInfo.name)) {
13255                    return sysActivity;
13256                }
13257                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13258                    return sysActivity;
13259                }
13260                if (sysActivity.info.targetActivity != null) {
13261                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13262                        return sysActivity;
13263                    }
13264                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13265                        return sysActivity;
13266                    }
13267                }
13268            }
13269            return null;
13270        }
13271
13272        public class IterGenerator<E> {
13273            public Iterator<E> generate(ActivityIntentInfo info) {
13274                return null;
13275            }
13276        }
13277
13278        public class ActionIterGenerator extends IterGenerator<String> {
13279            @Override
13280            public Iterator<String> generate(ActivityIntentInfo info) {
13281                return info.actionsIterator();
13282            }
13283        }
13284
13285        public class CategoriesIterGenerator extends IterGenerator<String> {
13286            @Override
13287            public Iterator<String> generate(ActivityIntentInfo info) {
13288                return info.categoriesIterator();
13289            }
13290        }
13291
13292        public class SchemesIterGenerator extends IterGenerator<String> {
13293            @Override
13294            public Iterator<String> generate(ActivityIntentInfo info) {
13295                return info.schemesIterator();
13296            }
13297        }
13298
13299        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13300            @Override
13301            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13302                return info.authoritiesIterator();
13303            }
13304        }
13305
13306        /**
13307         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13308         * MODIFIED. Do not pass in a list that should not be changed.
13309         */
13310        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13311                IterGenerator<T> generator, Iterator<T> searchIterator) {
13312            // loop through the set of actions; every one must be found in the intent filter
13313            while (searchIterator.hasNext()) {
13314                // we must have at least one filter in the list to consider a match
13315                if (intentList.size() == 0) {
13316                    break;
13317                }
13318
13319                final T searchAction = searchIterator.next();
13320
13321                // loop through the set of intent filters
13322                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13323                while (intentIter.hasNext()) {
13324                    final ActivityIntentInfo intentInfo = intentIter.next();
13325                    boolean selectionFound = false;
13326
13327                    // loop through the intent filter's selection criteria; at least one
13328                    // of them must match the searched criteria
13329                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13330                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13331                        final T intentSelection = intentSelectionIter.next();
13332                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13333                            selectionFound = true;
13334                            break;
13335                        }
13336                    }
13337
13338                    // the selection criteria wasn't found in this filter's set; this filter
13339                    // is not a potential match
13340                    if (!selectionFound) {
13341                        intentIter.remove();
13342                    }
13343                }
13344            }
13345        }
13346
13347        private boolean isProtectedAction(ActivityIntentInfo filter) {
13348            final Iterator<String> actionsIter = filter.actionsIterator();
13349            while (actionsIter != null && actionsIter.hasNext()) {
13350                final String filterAction = actionsIter.next();
13351                if (PROTECTED_ACTIONS.contains(filterAction)) {
13352                    return true;
13353                }
13354            }
13355            return false;
13356        }
13357
13358        /**
13359         * Adjusts the priority of the given intent filter according to policy.
13360         * <p>
13361         * <ul>
13362         * <li>The priority for non privileged applications is capped to '0'</li>
13363         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13364         * <li>The priority for unbundled updates to privileged applications is capped to the
13365         *      priority defined on the system partition</li>
13366         * </ul>
13367         * <p>
13368         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13369         * allowed to obtain any priority on any action.
13370         */
13371        private void adjustPriority(
13372                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13373            // nothing to do; priority is fine as-is
13374            if (intent.getPriority() <= 0) {
13375                return;
13376            }
13377
13378            final ActivityInfo activityInfo = intent.activity.info;
13379            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13380
13381            final boolean privilegedApp =
13382                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13383            if (!privilegedApp) {
13384                // non-privileged applications can never define a priority >0
13385                if (DEBUG_FILTERS) {
13386                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13387                            + " package: " + applicationInfo.packageName
13388                            + " activity: " + intent.activity.className
13389                            + " origPrio: " + intent.getPriority());
13390                }
13391                intent.setPriority(0);
13392                return;
13393            }
13394
13395            if (systemActivities == null) {
13396                // the system package is not disabled; we're parsing the system partition
13397                if (isProtectedAction(intent)) {
13398                    if (mDeferProtectedFilters) {
13399                        // We can't deal with these just yet. No component should ever obtain a
13400                        // >0 priority for a protected actions, with ONE exception -- the setup
13401                        // wizard. The setup wizard, however, cannot be known until we're able to
13402                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13403                        // until all intent filters have been processed. Chicken, meet egg.
13404                        // Let the filter temporarily have a high priority and rectify the
13405                        // priorities after all system packages have been scanned.
13406                        mProtectedFilters.add(intent);
13407                        if (DEBUG_FILTERS) {
13408                            Slog.i(TAG, "Protected action; save for later;"
13409                                    + " package: " + applicationInfo.packageName
13410                                    + " activity: " + intent.activity.className
13411                                    + " origPrio: " + intent.getPriority());
13412                        }
13413                        return;
13414                    } else {
13415                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13416                            Slog.i(TAG, "No setup wizard;"
13417                                + " All protected intents capped to priority 0");
13418                        }
13419                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13420                            if (DEBUG_FILTERS) {
13421                                Slog.i(TAG, "Found setup wizard;"
13422                                    + " allow priority " + intent.getPriority() + ";"
13423                                    + " package: " + intent.activity.info.packageName
13424                                    + " activity: " + intent.activity.className
13425                                    + " priority: " + intent.getPriority());
13426                            }
13427                            // setup wizard gets whatever it wants
13428                            return;
13429                        }
13430                        if (DEBUG_FILTERS) {
13431                            Slog.i(TAG, "Protected action; cap priority to 0;"
13432                                    + " package: " + intent.activity.info.packageName
13433                                    + " activity: " + intent.activity.className
13434                                    + " origPrio: " + intent.getPriority());
13435                        }
13436                        intent.setPriority(0);
13437                        return;
13438                    }
13439                }
13440                // privileged apps on the system image get whatever priority they request
13441                return;
13442            }
13443
13444            // privileged app unbundled update ... try to find the same activity
13445            final PackageParser.Activity foundActivity =
13446                    findMatchingActivity(systemActivities, activityInfo);
13447            if (foundActivity == null) {
13448                // this is a new activity; it cannot obtain >0 priority
13449                if (DEBUG_FILTERS) {
13450                    Slog.i(TAG, "New activity; cap priority to 0;"
13451                            + " package: " + applicationInfo.packageName
13452                            + " activity: " + intent.activity.className
13453                            + " origPrio: " + intent.getPriority());
13454                }
13455                intent.setPriority(0);
13456                return;
13457            }
13458
13459            // found activity, now check for filter equivalence
13460
13461            // a shallow copy is enough; we modify the list, not its contents
13462            final List<ActivityIntentInfo> intentListCopy =
13463                    new ArrayList<>(foundActivity.intents);
13464            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13465
13466            // find matching action subsets
13467            final Iterator<String> actionsIterator = intent.actionsIterator();
13468            if (actionsIterator != null) {
13469                getIntentListSubset(
13470                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13471                if (intentListCopy.size() == 0) {
13472                    // no more intents to match; we're not equivalent
13473                    if (DEBUG_FILTERS) {
13474                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13475                                + " package: " + applicationInfo.packageName
13476                                + " activity: " + intent.activity.className
13477                                + " origPrio: " + intent.getPriority());
13478                    }
13479                    intent.setPriority(0);
13480                    return;
13481                }
13482            }
13483
13484            // find matching category subsets
13485            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13486            if (categoriesIterator != null) {
13487                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13488                        categoriesIterator);
13489                if (intentListCopy.size() == 0) {
13490                    // no more intents to match; we're not equivalent
13491                    if (DEBUG_FILTERS) {
13492                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13493                                + " package: " + applicationInfo.packageName
13494                                + " activity: " + intent.activity.className
13495                                + " origPrio: " + intent.getPriority());
13496                    }
13497                    intent.setPriority(0);
13498                    return;
13499                }
13500            }
13501
13502            // find matching schemes subsets
13503            final Iterator<String> schemesIterator = intent.schemesIterator();
13504            if (schemesIterator != null) {
13505                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13506                        schemesIterator);
13507                if (intentListCopy.size() == 0) {
13508                    // no more intents to match; we're not equivalent
13509                    if (DEBUG_FILTERS) {
13510                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13511                                + " package: " + applicationInfo.packageName
13512                                + " activity: " + intent.activity.className
13513                                + " origPrio: " + intent.getPriority());
13514                    }
13515                    intent.setPriority(0);
13516                    return;
13517                }
13518            }
13519
13520            // find matching authorities subsets
13521            final Iterator<IntentFilter.AuthorityEntry>
13522                    authoritiesIterator = intent.authoritiesIterator();
13523            if (authoritiesIterator != null) {
13524                getIntentListSubset(intentListCopy,
13525                        new AuthoritiesIterGenerator(),
13526                        authoritiesIterator);
13527                if (intentListCopy.size() == 0) {
13528                    // no more intents to match; we're not equivalent
13529                    if (DEBUG_FILTERS) {
13530                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13531                                + " package: " + applicationInfo.packageName
13532                                + " activity: " + intent.activity.className
13533                                + " origPrio: " + intent.getPriority());
13534                    }
13535                    intent.setPriority(0);
13536                    return;
13537                }
13538            }
13539
13540            // we found matching filter(s); app gets the max priority of all intents
13541            int cappedPriority = 0;
13542            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13543                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13544            }
13545            if (intent.getPriority() > cappedPriority) {
13546                if (DEBUG_FILTERS) {
13547                    Slog.i(TAG, "Found matching filter(s);"
13548                            + " cap priority to " + cappedPriority + ";"
13549                            + " package: " + applicationInfo.packageName
13550                            + " activity: " + intent.activity.className
13551                            + " origPrio: " + intent.getPriority());
13552                }
13553                intent.setPriority(cappedPriority);
13554                return;
13555            }
13556            // all this for nothing; the requested priority was <= what was on the system
13557        }
13558
13559        public final void addActivity(PackageParser.Activity a, String type) {
13560            mActivities.put(a.getComponentName(), a);
13561            if (DEBUG_SHOW_INFO)
13562                Log.v(
13563                TAG, "  " + type + " " +
13564                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13565            if (DEBUG_SHOW_INFO)
13566                Log.v(TAG, "    Class=" + a.info.name);
13567            final int NI = a.intents.size();
13568            for (int j=0; j<NI; j++) {
13569                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13570                if ("activity".equals(type)) {
13571                    final PackageSetting ps =
13572                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13573                    final List<PackageParser.Activity> systemActivities =
13574                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13575                    adjustPriority(systemActivities, intent);
13576                }
13577                if (DEBUG_SHOW_INFO) {
13578                    Log.v(TAG, "    IntentFilter:");
13579                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13580                }
13581                if (!intent.debugCheck()) {
13582                    Log.w(TAG, "==> For Activity " + a.info.name);
13583                }
13584                addFilter(intent);
13585            }
13586        }
13587
13588        public final void removeActivity(PackageParser.Activity a, String type) {
13589            mActivities.remove(a.getComponentName());
13590            if (DEBUG_SHOW_INFO) {
13591                Log.v(TAG, "  " + type + " "
13592                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13593                                : a.info.name) + ":");
13594                Log.v(TAG, "    Class=" + a.info.name);
13595            }
13596            final int NI = a.intents.size();
13597            for (int j=0; j<NI; j++) {
13598                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13599                if (DEBUG_SHOW_INFO) {
13600                    Log.v(TAG, "    IntentFilter:");
13601                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13602                }
13603                removeFilter(intent);
13604            }
13605        }
13606
13607        @Override
13608        protected boolean allowFilterResult(
13609                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13610            ActivityInfo filterAi = filter.activity.info;
13611            for (int i=dest.size()-1; i>=0; i--) {
13612                ActivityInfo destAi = dest.get(i).activityInfo;
13613                if (destAi.name == filterAi.name
13614                        && destAi.packageName == filterAi.packageName) {
13615                    return false;
13616                }
13617            }
13618            return true;
13619        }
13620
13621        @Override
13622        protected ActivityIntentInfo[] newArray(int size) {
13623            return new ActivityIntentInfo[size];
13624        }
13625
13626        @Override
13627        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13628            if (!sUserManager.exists(userId)) return true;
13629            PackageParser.Package p = filter.activity.owner;
13630            if (p != null) {
13631                PackageSetting ps = (PackageSetting)p.mExtras;
13632                if (ps != null) {
13633                    // System apps are never considered stopped for purposes of
13634                    // filtering, because there may be no way for the user to
13635                    // actually re-launch them.
13636                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13637                            && ps.getStopped(userId);
13638                }
13639            }
13640            return false;
13641        }
13642
13643        @Override
13644        protected boolean isPackageForFilter(String packageName,
13645                PackageParser.ActivityIntentInfo info) {
13646            return packageName.equals(info.activity.owner.packageName);
13647        }
13648
13649        @Override
13650        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13651                int match, int userId) {
13652            if (!sUserManager.exists(userId)) return null;
13653            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13654                return null;
13655            }
13656            final PackageParser.Activity activity = info.activity;
13657            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13658            if (ps == null) {
13659                return null;
13660            }
13661            final PackageUserState userState = ps.readUserState(userId);
13662            ActivityInfo ai =
13663                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13664            if (ai == null) {
13665                return null;
13666            }
13667            final boolean matchExplicitlyVisibleOnly =
13668                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13669            final boolean matchVisibleToInstantApp =
13670                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13671            final boolean componentVisible =
13672                    matchVisibleToInstantApp
13673                    && info.isVisibleToInstantApp()
13674                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13675            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13676            // throw out filters that aren't visible to ephemeral apps
13677            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13678                return null;
13679            }
13680            // throw out instant app filters if we're not explicitly requesting them
13681            if (!matchInstantApp && userState.instantApp) {
13682                return null;
13683            }
13684            // throw out instant app filters if updates are available; will trigger
13685            // instant app resolution
13686            if (userState.instantApp && ps.isUpdateAvailable()) {
13687                return null;
13688            }
13689            final ResolveInfo res = new ResolveInfo();
13690            res.activityInfo = ai;
13691            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13692                res.filter = info;
13693            }
13694            if (info != null) {
13695                res.handleAllWebDataURI = info.handleAllWebDataURI();
13696            }
13697            res.priority = info.getPriority();
13698            res.preferredOrder = activity.owner.mPreferredOrder;
13699            //System.out.println("Result: " + res.activityInfo.className +
13700            //                   " = " + res.priority);
13701            res.match = match;
13702            res.isDefault = info.hasDefault;
13703            res.labelRes = info.labelRes;
13704            res.nonLocalizedLabel = info.nonLocalizedLabel;
13705            if (userNeedsBadging(userId)) {
13706                res.noResourceId = true;
13707            } else {
13708                res.icon = info.icon;
13709            }
13710            res.iconResourceId = info.icon;
13711            res.system = res.activityInfo.applicationInfo.isSystemApp();
13712            res.isInstantAppAvailable = userState.instantApp;
13713            return res;
13714        }
13715
13716        @Override
13717        protected void sortResults(List<ResolveInfo> results) {
13718            Collections.sort(results, mResolvePrioritySorter);
13719        }
13720
13721        @Override
13722        protected void dumpFilter(PrintWriter out, String prefix,
13723                PackageParser.ActivityIntentInfo filter) {
13724            out.print(prefix); out.print(
13725                    Integer.toHexString(System.identityHashCode(filter.activity)));
13726                    out.print(' ');
13727                    filter.activity.printComponentShortName(out);
13728                    out.print(" filter ");
13729                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13730        }
13731
13732        @Override
13733        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13734            return filter.activity;
13735        }
13736
13737        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13738            PackageParser.Activity activity = (PackageParser.Activity)label;
13739            out.print(prefix); out.print(
13740                    Integer.toHexString(System.identityHashCode(activity)));
13741                    out.print(' ');
13742                    activity.printComponentShortName(out);
13743            if (count > 1) {
13744                out.print(" ("); out.print(count); out.print(" filters)");
13745            }
13746            out.println();
13747        }
13748
13749        // Keys are String (activity class name), values are Activity.
13750        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13751                = new ArrayMap<ComponentName, PackageParser.Activity>();
13752        private int mFlags;
13753    }
13754
13755    private final class ServiceIntentResolver
13756            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13757        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13758                boolean defaultOnly, int userId) {
13759            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13760            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13761        }
13762
13763        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13764                int userId) {
13765            if (!sUserManager.exists(userId)) return null;
13766            mFlags = flags;
13767            return super.queryIntent(intent, resolvedType,
13768                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13769                    userId);
13770        }
13771
13772        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13773                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13774            if (!sUserManager.exists(userId)) return null;
13775            if (packageServices == null) {
13776                return null;
13777            }
13778            mFlags = flags;
13779            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13780            final int N = packageServices.size();
13781            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13782                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13783
13784            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13785            for (int i = 0; i < N; ++i) {
13786                intentFilters = packageServices.get(i).intents;
13787                if (intentFilters != null && intentFilters.size() > 0) {
13788                    PackageParser.ServiceIntentInfo[] array =
13789                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13790                    intentFilters.toArray(array);
13791                    listCut.add(array);
13792                }
13793            }
13794            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13795        }
13796
13797        public final void addService(PackageParser.Service s) {
13798            mServices.put(s.getComponentName(), s);
13799            if (DEBUG_SHOW_INFO) {
13800                Log.v(TAG, "  "
13801                        + (s.info.nonLocalizedLabel != null
13802                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13803                Log.v(TAG, "    Class=" + s.info.name);
13804            }
13805            final int NI = s.intents.size();
13806            int j;
13807            for (j=0; j<NI; j++) {
13808                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13809                if (DEBUG_SHOW_INFO) {
13810                    Log.v(TAG, "    IntentFilter:");
13811                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13812                }
13813                if (!intent.debugCheck()) {
13814                    Log.w(TAG, "==> For Service " + s.info.name);
13815                }
13816                addFilter(intent);
13817            }
13818        }
13819
13820        public final void removeService(PackageParser.Service s) {
13821            mServices.remove(s.getComponentName());
13822            if (DEBUG_SHOW_INFO) {
13823                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13824                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13825                Log.v(TAG, "    Class=" + s.info.name);
13826            }
13827            final int NI = s.intents.size();
13828            int j;
13829            for (j=0; j<NI; j++) {
13830                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13831                if (DEBUG_SHOW_INFO) {
13832                    Log.v(TAG, "    IntentFilter:");
13833                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13834                }
13835                removeFilter(intent);
13836            }
13837        }
13838
13839        @Override
13840        protected boolean allowFilterResult(
13841                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13842            ServiceInfo filterSi = filter.service.info;
13843            for (int i=dest.size()-1; i>=0; i--) {
13844                ServiceInfo destAi = dest.get(i).serviceInfo;
13845                if (destAi.name == filterSi.name
13846                        && destAi.packageName == filterSi.packageName) {
13847                    return false;
13848                }
13849            }
13850            return true;
13851        }
13852
13853        @Override
13854        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13855            return new PackageParser.ServiceIntentInfo[size];
13856        }
13857
13858        @Override
13859        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13860            if (!sUserManager.exists(userId)) return true;
13861            PackageParser.Package p = filter.service.owner;
13862            if (p != null) {
13863                PackageSetting ps = (PackageSetting)p.mExtras;
13864                if (ps != null) {
13865                    // System apps are never considered stopped for purposes of
13866                    // filtering, because there may be no way for the user to
13867                    // actually re-launch them.
13868                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13869                            && ps.getStopped(userId);
13870                }
13871            }
13872            return false;
13873        }
13874
13875        @Override
13876        protected boolean isPackageForFilter(String packageName,
13877                PackageParser.ServiceIntentInfo info) {
13878            return packageName.equals(info.service.owner.packageName);
13879        }
13880
13881        @Override
13882        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13883                int match, int userId) {
13884            if (!sUserManager.exists(userId)) return null;
13885            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13886            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13887                return null;
13888            }
13889            final PackageParser.Service service = info.service;
13890            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13891            if (ps == null) {
13892                return null;
13893            }
13894            final PackageUserState userState = ps.readUserState(userId);
13895            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13896                    userState, userId);
13897            if (si == null) {
13898                return null;
13899            }
13900            final boolean matchVisibleToInstantApp =
13901                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13902            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13903            // throw out filters that aren't visible to ephemeral apps
13904            if (matchVisibleToInstantApp
13905                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13906                return null;
13907            }
13908            // throw out ephemeral filters if we're not explicitly requesting them
13909            if (!isInstantApp && userState.instantApp) {
13910                return null;
13911            }
13912            // throw out instant app filters if updates are available; will trigger
13913            // instant app resolution
13914            if (userState.instantApp && ps.isUpdateAvailable()) {
13915                return null;
13916            }
13917            final ResolveInfo res = new ResolveInfo();
13918            res.serviceInfo = si;
13919            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13920                res.filter = filter;
13921            }
13922            res.priority = info.getPriority();
13923            res.preferredOrder = service.owner.mPreferredOrder;
13924            res.match = match;
13925            res.isDefault = info.hasDefault;
13926            res.labelRes = info.labelRes;
13927            res.nonLocalizedLabel = info.nonLocalizedLabel;
13928            res.icon = info.icon;
13929            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13930            return res;
13931        }
13932
13933        @Override
13934        protected void sortResults(List<ResolveInfo> results) {
13935            Collections.sort(results, mResolvePrioritySorter);
13936        }
13937
13938        @Override
13939        protected void dumpFilter(PrintWriter out, String prefix,
13940                PackageParser.ServiceIntentInfo filter) {
13941            out.print(prefix); out.print(
13942                    Integer.toHexString(System.identityHashCode(filter.service)));
13943                    out.print(' ');
13944                    filter.service.printComponentShortName(out);
13945                    out.print(" filter ");
13946                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13947        }
13948
13949        @Override
13950        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13951            return filter.service;
13952        }
13953
13954        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13955            PackageParser.Service service = (PackageParser.Service)label;
13956            out.print(prefix); out.print(
13957                    Integer.toHexString(System.identityHashCode(service)));
13958                    out.print(' ');
13959                    service.printComponentShortName(out);
13960            if (count > 1) {
13961                out.print(" ("); out.print(count); out.print(" filters)");
13962            }
13963            out.println();
13964        }
13965
13966//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13967//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13968//            final List<ResolveInfo> retList = Lists.newArrayList();
13969//            while (i.hasNext()) {
13970//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13971//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13972//                    retList.add(resolveInfo);
13973//                }
13974//            }
13975//            return retList;
13976//        }
13977
13978        // Keys are String (activity class name), values are Activity.
13979        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13980                = new ArrayMap<ComponentName, PackageParser.Service>();
13981        private int mFlags;
13982    }
13983
13984    private final class ProviderIntentResolver
13985            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13986        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13987                boolean defaultOnly, int userId) {
13988            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13989            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13990        }
13991
13992        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13993                int userId) {
13994            if (!sUserManager.exists(userId))
13995                return null;
13996            mFlags = flags;
13997            return super.queryIntent(intent, resolvedType,
13998                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13999                    userId);
14000        }
14001
14002        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14003                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14004            if (!sUserManager.exists(userId))
14005                return null;
14006            if (packageProviders == null) {
14007                return null;
14008            }
14009            mFlags = flags;
14010            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14011            final int N = packageProviders.size();
14012            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14013                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14014
14015            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14016            for (int i = 0; i < N; ++i) {
14017                intentFilters = packageProviders.get(i).intents;
14018                if (intentFilters != null && intentFilters.size() > 0) {
14019                    PackageParser.ProviderIntentInfo[] array =
14020                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14021                    intentFilters.toArray(array);
14022                    listCut.add(array);
14023                }
14024            }
14025            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14026        }
14027
14028        public final void addProvider(PackageParser.Provider p) {
14029            if (mProviders.containsKey(p.getComponentName())) {
14030                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14031                return;
14032            }
14033
14034            mProviders.put(p.getComponentName(), p);
14035            if (DEBUG_SHOW_INFO) {
14036                Log.v(TAG, "  "
14037                        + (p.info.nonLocalizedLabel != null
14038                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14039                Log.v(TAG, "    Class=" + p.info.name);
14040            }
14041            final int NI = p.intents.size();
14042            int j;
14043            for (j = 0; j < NI; j++) {
14044                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14045                if (DEBUG_SHOW_INFO) {
14046                    Log.v(TAG, "    IntentFilter:");
14047                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14048                }
14049                if (!intent.debugCheck()) {
14050                    Log.w(TAG, "==> For Provider " + p.info.name);
14051                }
14052                addFilter(intent);
14053            }
14054        }
14055
14056        public final void removeProvider(PackageParser.Provider p) {
14057            mProviders.remove(p.getComponentName());
14058            if (DEBUG_SHOW_INFO) {
14059                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14060                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14061                Log.v(TAG, "    Class=" + p.info.name);
14062            }
14063            final int NI = p.intents.size();
14064            int j;
14065            for (j = 0; j < NI; j++) {
14066                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14067                if (DEBUG_SHOW_INFO) {
14068                    Log.v(TAG, "    IntentFilter:");
14069                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14070                }
14071                removeFilter(intent);
14072            }
14073        }
14074
14075        @Override
14076        protected boolean allowFilterResult(
14077                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14078            ProviderInfo filterPi = filter.provider.info;
14079            for (int i = dest.size() - 1; i >= 0; i--) {
14080                ProviderInfo destPi = dest.get(i).providerInfo;
14081                if (destPi.name == filterPi.name
14082                        && destPi.packageName == filterPi.packageName) {
14083                    return false;
14084                }
14085            }
14086            return true;
14087        }
14088
14089        @Override
14090        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14091            return new PackageParser.ProviderIntentInfo[size];
14092        }
14093
14094        @Override
14095        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14096            if (!sUserManager.exists(userId))
14097                return true;
14098            PackageParser.Package p = filter.provider.owner;
14099            if (p != null) {
14100                PackageSetting ps = (PackageSetting) p.mExtras;
14101                if (ps != null) {
14102                    // System apps are never considered stopped for purposes of
14103                    // filtering, because there may be no way for the user to
14104                    // actually re-launch them.
14105                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14106                            && ps.getStopped(userId);
14107                }
14108            }
14109            return false;
14110        }
14111
14112        @Override
14113        protected boolean isPackageForFilter(String packageName,
14114                PackageParser.ProviderIntentInfo info) {
14115            return packageName.equals(info.provider.owner.packageName);
14116        }
14117
14118        @Override
14119        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14120                int match, int userId) {
14121            if (!sUserManager.exists(userId))
14122                return null;
14123            final PackageParser.ProviderIntentInfo info = filter;
14124            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14125                return null;
14126            }
14127            final PackageParser.Provider provider = info.provider;
14128            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14129            if (ps == null) {
14130                return null;
14131            }
14132            final PackageUserState userState = ps.readUserState(userId);
14133            final boolean matchVisibleToInstantApp =
14134                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14135            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14136            // throw out filters that aren't visible to instant applications
14137            if (matchVisibleToInstantApp
14138                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14139                return null;
14140            }
14141            // throw out instant application filters if we're not explicitly requesting them
14142            if (!isInstantApp && userState.instantApp) {
14143                return null;
14144            }
14145            // throw out instant application filters if updates are available; will trigger
14146            // instant application resolution
14147            if (userState.instantApp && ps.isUpdateAvailable()) {
14148                return null;
14149            }
14150            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14151                    userState, userId);
14152            if (pi == null) {
14153                return null;
14154            }
14155            final ResolveInfo res = new ResolveInfo();
14156            res.providerInfo = pi;
14157            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14158                res.filter = filter;
14159            }
14160            res.priority = info.getPriority();
14161            res.preferredOrder = provider.owner.mPreferredOrder;
14162            res.match = match;
14163            res.isDefault = info.hasDefault;
14164            res.labelRes = info.labelRes;
14165            res.nonLocalizedLabel = info.nonLocalizedLabel;
14166            res.icon = info.icon;
14167            res.system = res.providerInfo.applicationInfo.isSystemApp();
14168            return res;
14169        }
14170
14171        @Override
14172        protected void sortResults(List<ResolveInfo> results) {
14173            Collections.sort(results, mResolvePrioritySorter);
14174        }
14175
14176        @Override
14177        protected void dumpFilter(PrintWriter out, String prefix,
14178                PackageParser.ProviderIntentInfo filter) {
14179            out.print(prefix);
14180            out.print(
14181                    Integer.toHexString(System.identityHashCode(filter.provider)));
14182            out.print(' ');
14183            filter.provider.printComponentShortName(out);
14184            out.print(" filter ");
14185            out.println(Integer.toHexString(System.identityHashCode(filter)));
14186        }
14187
14188        @Override
14189        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14190            return filter.provider;
14191        }
14192
14193        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14194            PackageParser.Provider provider = (PackageParser.Provider)label;
14195            out.print(prefix); out.print(
14196                    Integer.toHexString(System.identityHashCode(provider)));
14197                    out.print(' ');
14198                    provider.printComponentShortName(out);
14199            if (count > 1) {
14200                out.print(" ("); out.print(count); out.print(" filters)");
14201            }
14202            out.println();
14203        }
14204
14205        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14206                = new ArrayMap<ComponentName, PackageParser.Provider>();
14207        private int mFlags;
14208    }
14209
14210    static final class EphemeralIntentResolver
14211            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14212        /**
14213         * The result that has the highest defined order. Ordering applies on a
14214         * per-package basis. Mapping is from package name to Pair of order and
14215         * EphemeralResolveInfo.
14216         * <p>
14217         * NOTE: This is implemented as a field variable for convenience and efficiency.
14218         * By having a field variable, we're able to track filter ordering as soon as
14219         * a non-zero order is defined. Otherwise, multiple loops across the result set
14220         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14221         * this needs to be contained entirely within {@link #filterResults}.
14222         */
14223        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14224
14225        @Override
14226        protected AuxiliaryResolveInfo[] newArray(int size) {
14227            return new AuxiliaryResolveInfo[size];
14228        }
14229
14230        @Override
14231        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14232            return true;
14233        }
14234
14235        @Override
14236        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14237                int userId) {
14238            if (!sUserManager.exists(userId)) {
14239                return null;
14240            }
14241            final String packageName = responseObj.resolveInfo.getPackageName();
14242            final Integer order = responseObj.getOrder();
14243            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14244                    mOrderResult.get(packageName);
14245            // ordering is enabled and this item's order isn't high enough
14246            if (lastOrderResult != null && lastOrderResult.first >= order) {
14247                return null;
14248            }
14249            final InstantAppResolveInfo res = responseObj.resolveInfo;
14250            if (order > 0) {
14251                // non-zero order, enable ordering
14252                mOrderResult.put(packageName, new Pair<>(order, res));
14253            }
14254            return responseObj;
14255        }
14256
14257        @Override
14258        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14259            // only do work if ordering is enabled [most of the time it won't be]
14260            if (mOrderResult.size() == 0) {
14261                return;
14262            }
14263            int resultSize = results.size();
14264            for (int i = 0; i < resultSize; i++) {
14265                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14266                final String packageName = info.getPackageName();
14267                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14268                if (savedInfo == null) {
14269                    // package doesn't having ordering
14270                    continue;
14271                }
14272                if (savedInfo.second == info) {
14273                    // circled back to the highest ordered item; remove from order list
14274                    mOrderResult.remove(savedInfo);
14275                    if (mOrderResult.size() == 0) {
14276                        // no more ordered items
14277                        break;
14278                    }
14279                    continue;
14280                }
14281                // item has a worse order, remove it from the result list
14282                results.remove(i);
14283                resultSize--;
14284                i--;
14285            }
14286        }
14287    }
14288
14289    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14290            new Comparator<ResolveInfo>() {
14291        public int compare(ResolveInfo r1, ResolveInfo r2) {
14292            int v1 = r1.priority;
14293            int v2 = r2.priority;
14294            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14295            if (v1 != v2) {
14296                return (v1 > v2) ? -1 : 1;
14297            }
14298            v1 = r1.preferredOrder;
14299            v2 = r2.preferredOrder;
14300            if (v1 != v2) {
14301                return (v1 > v2) ? -1 : 1;
14302            }
14303            if (r1.isDefault != r2.isDefault) {
14304                return r1.isDefault ? -1 : 1;
14305            }
14306            v1 = r1.match;
14307            v2 = r2.match;
14308            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14309            if (v1 != v2) {
14310                return (v1 > v2) ? -1 : 1;
14311            }
14312            if (r1.system != r2.system) {
14313                return r1.system ? -1 : 1;
14314            }
14315            if (r1.activityInfo != null) {
14316                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14317            }
14318            if (r1.serviceInfo != null) {
14319                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14320            }
14321            if (r1.providerInfo != null) {
14322                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14323            }
14324            return 0;
14325        }
14326    };
14327
14328    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14329            new Comparator<ProviderInfo>() {
14330        public int compare(ProviderInfo p1, ProviderInfo p2) {
14331            final int v1 = p1.initOrder;
14332            final int v2 = p2.initOrder;
14333            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14334        }
14335    };
14336
14337    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14338            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14339            final int[] userIds) {
14340        mHandler.post(new Runnable() {
14341            @Override
14342            public void run() {
14343                try {
14344                    final IActivityManager am = ActivityManager.getService();
14345                    if (am == null) return;
14346                    final int[] resolvedUserIds;
14347                    if (userIds == null) {
14348                        resolvedUserIds = am.getRunningUserIds();
14349                    } else {
14350                        resolvedUserIds = userIds;
14351                    }
14352                    for (int id : resolvedUserIds) {
14353                        final Intent intent = new Intent(action,
14354                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14355                        if (extras != null) {
14356                            intent.putExtras(extras);
14357                        }
14358                        if (targetPkg != null) {
14359                            intent.setPackage(targetPkg);
14360                        }
14361                        // Modify the UID when posting to other users
14362                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14363                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14364                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14365                            intent.putExtra(Intent.EXTRA_UID, uid);
14366                        }
14367                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14368                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14369                        if (DEBUG_BROADCASTS) {
14370                            RuntimeException here = new RuntimeException("here");
14371                            here.fillInStackTrace();
14372                            Slog.d(TAG, "Sending to user " + id + ": "
14373                                    + intent.toShortString(false, true, false, false)
14374                                    + " " + intent.getExtras(), here);
14375                        }
14376                        am.broadcastIntent(null, intent, null, finishedReceiver,
14377                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14378                                null, finishedReceiver != null, false, id);
14379                    }
14380                } catch (RemoteException ex) {
14381                }
14382            }
14383        });
14384    }
14385
14386    /**
14387     * Check if the external storage media is available. This is true if there
14388     * is a mounted external storage medium or if the external storage is
14389     * emulated.
14390     */
14391    private boolean isExternalMediaAvailable() {
14392        return mMediaMounted || Environment.isExternalStorageEmulated();
14393    }
14394
14395    @Override
14396    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14397        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14398            return null;
14399        }
14400        // writer
14401        synchronized (mPackages) {
14402            if (!isExternalMediaAvailable()) {
14403                // If the external storage is no longer mounted at this point,
14404                // the caller may not have been able to delete all of this
14405                // packages files and can not delete any more.  Bail.
14406                return null;
14407            }
14408            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14409            if (lastPackage != null) {
14410                pkgs.remove(lastPackage);
14411            }
14412            if (pkgs.size() > 0) {
14413                return pkgs.get(0);
14414            }
14415        }
14416        return null;
14417    }
14418
14419    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14420        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14421                userId, andCode ? 1 : 0, packageName);
14422        if (mSystemReady) {
14423            msg.sendToTarget();
14424        } else {
14425            if (mPostSystemReadyMessages == null) {
14426                mPostSystemReadyMessages = new ArrayList<>();
14427            }
14428            mPostSystemReadyMessages.add(msg);
14429        }
14430    }
14431
14432    void startCleaningPackages() {
14433        // reader
14434        if (!isExternalMediaAvailable()) {
14435            return;
14436        }
14437        synchronized (mPackages) {
14438            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14439                return;
14440            }
14441        }
14442        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14443        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14444        IActivityManager am = ActivityManager.getService();
14445        if (am != null) {
14446            int dcsUid = -1;
14447            synchronized (mPackages) {
14448                if (!mDefaultContainerWhitelisted) {
14449                    mDefaultContainerWhitelisted = true;
14450                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14451                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14452                }
14453            }
14454            try {
14455                if (dcsUid > 0) {
14456                    am.backgroundWhitelistUid(dcsUid);
14457                }
14458                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14459                        UserHandle.USER_SYSTEM);
14460            } catch (RemoteException e) {
14461            }
14462        }
14463    }
14464
14465    @Override
14466    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14467            int installFlags, String installerPackageName, int userId) {
14468        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14469
14470        final int callingUid = Binder.getCallingUid();
14471        enforceCrossUserPermission(callingUid, userId,
14472                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14473
14474        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14475            try {
14476                if (observer != null) {
14477                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14478                }
14479            } catch (RemoteException re) {
14480            }
14481            return;
14482        }
14483
14484        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14485            installFlags |= PackageManager.INSTALL_FROM_ADB;
14486
14487        } else {
14488            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14489            // about installerPackageName.
14490
14491            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14492            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14493        }
14494
14495        UserHandle user;
14496        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14497            user = UserHandle.ALL;
14498        } else {
14499            user = new UserHandle(userId);
14500        }
14501
14502        // Only system components can circumvent runtime permissions when installing.
14503        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14504                && mContext.checkCallingOrSelfPermission(Manifest.permission
14505                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14506            throw new SecurityException("You need the "
14507                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14508                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14509        }
14510
14511        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14512                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14513            throw new IllegalArgumentException(
14514                    "New installs into ASEC containers no longer supported");
14515        }
14516
14517        final File originFile = new File(originPath);
14518        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14519
14520        final Message msg = mHandler.obtainMessage(INIT_COPY);
14521        final VerificationInfo verificationInfo = new VerificationInfo(
14522                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14523        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14524                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14525                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14526                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14527        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14528        msg.obj = params;
14529
14530        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14531                System.identityHashCode(msg.obj));
14532        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14533                System.identityHashCode(msg.obj));
14534
14535        mHandler.sendMessage(msg);
14536    }
14537
14538
14539    /**
14540     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14541     * it is acting on behalf on an enterprise or the user).
14542     *
14543     * Note that the ordering of the conditionals in this method is important. The checks we perform
14544     * are as follows, in this order:
14545     *
14546     * 1) If the install is being performed by a system app, we can trust the app to have set the
14547     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14548     *    what it is.
14549     * 2) If the install is being performed by a device or profile owner app, the install reason
14550     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14551     *    set the install reason correctly. If the app targets an older SDK version where install
14552     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14553     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14554     * 3) In all other cases, the install is being performed by a regular app that is neither part
14555     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14556     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14557     *    set to enterprise policy and if so, change it to unknown instead.
14558     */
14559    private int fixUpInstallReason(String installerPackageName, int installerUid,
14560            int installReason) {
14561        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14562                == PERMISSION_GRANTED) {
14563            // If the install is being performed by a system app, we trust that app to have set the
14564            // install reason correctly.
14565            return installReason;
14566        }
14567
14568        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14569            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14570        if (dpm != null) {
14571            ComponentName owner = null;
14572            try {
14573                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14574                if (owner == null) {
14575                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14576                }
14577            } catch (RemoteException e) {
14578            }
14579            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14580                // If the install is being performed by a device or profile owner, the install
14581                // reason should be enterprise policy.
14582                return PackageManager.INSTALL_REASON_POLICY;
14583            }
14584        }
14585
14586        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14587            // If the install is being performed by a regular app (i.e. neither system app nor
14588            // device or profile owner), we have no reason to believe that the app is acting on
14589            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14590            // change it to unknown instead.
14591            return PackageManager.INSTALL_REASON_UNKNOWN;
14592        }
14593
14594        // If the install is being performed by a regular app and the install reason was set to any
14595        // value but enterprise policy, leave the install reason unchanged.
14596        return installReason;
14597    }
14598
14599    void installStage(String packageName, File stagedDir, String stagedCid,
14600            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14601            String installerPackageName, int installerUid, UserHandle user,
14602            Certificate[][] certificates) {
14603        if (DEBUG_EPHEMERAL) {
14604            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14605                Slog.d(TAG, "Ephemeral install of " + packageName);
14606            }
14607        }
14608        final VerificationInfo verificationInfo = new VerificationInfo(
14609                sessionParams.originatingUri, sessionParams.referrerUri,
14610                sessionParams.originatingUid, installerUid);
14611
14612        final OriginInfo origin;
14613        if (stagedDir != null) {
14614            origin = OriginInfo.fromStagedFile(stagedDir);
14615        } else {
14616            origin = OriginInfo.fromStagedContainer(stagedCid);
14617        }
14618
14619        final Message msg = mHandler.obtainMessage(INIT_COPY);
14620        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14621                sessionParams.installReason);
14622        final InstallParams params = new InstallParams(origin, null, observer,
14623                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14624                verificationInfo, user, sessionParams.abiOverride,
14625                sessionParams.grantedRuntimePermissions, certificates, installReason);
14626        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14627        msg.obj = params;
14628
14629        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14630                System.identityHashCode(msg.obj));
14631        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14632                System.identityHashCode(msg.obj));
14633
14634        mHandler.sendMessage(msg);
14635    }
14636
14637    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14638            int userId) {
14639        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14640        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14641                false /*startReceiver*/, pkgSetting.appId, userId);
14642
14643        // Send a session commit broadcast
14644        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14645        info.installReason = pkgSetting.getInstallReason(userId);
14646        info.appPackageName = packageName;
14647        sendSessionCommitBroadcast(info, userId);
14648    }
14649
14650    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14651            boolean includeStopped, int appId, int... userIds) {
14652        if (ArrayUtils.isEmpty(userIds)) {
14653            return;
14654        }
14655        Bundle extras = new Bundle(1);
14656        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14657        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14658
14659        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14660                packageName, extras, 0, null, null, userIds);
14661        if (sendBootCompleted) {
14662            mHandler.post(() -> {
14663                        for (int userId : userIds) {
14664                            sendBootCompletedBroadcastToSystemApp(
14665                                    packageName, includeStopped, userId);
14666                        }
14667                    }
14668            );
14669        }
14670    }
14671
14672    /**
14673     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14674     * automatically without needing an explicit launch.
14675     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14676     */
14677    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14678            int userId) {
14679        // If user is not running, the app didn't miss any broadcast
14680        if (!mUserManagerInternal.isUserRunning(userId)) {
14681            return;
14682        }
14683        final IActivityManager am = ActivityManager.getService();
14684        try {
14685            // Deliver LOCKED_BOOT_COMPLETED first
14686            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14687                    .setPackage(packageName);
14688            if (includeStopped) {
14689                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14690            }
14691            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14692            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14693                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14694
14695            // Deliver BOOT_COMPLETED only if user is unlocked
14696            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14697                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14698                if (includeStopped) {
14699                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14700                }
14701                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14702                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14703            }
14704        } catch (RemoteException e) {
14705            throw e.rethrowFromSystemServer();
14706        }
14707    }
14708
14709    @Override
14710    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14711            int userId) {
14712        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14713        PackageSetting pkgSetting;
14714        final int callingUid = Binder.getCallingUid();
14715        enforceCrossUserPermission(callingUid, userId,
14716                true /* requireFullPermission */, true /* checkShell */,
14717                "setApplicationHiddenSetting for user " + userId);
14718
14719        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14720            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14721            return false;
14722        }
14723
14724        long callingId = Binder.clearCallingIdentity();
14725        try {
14726            boolean sendAdded = false;
14727            boolean sendRemoved = false;
14728            // writer
14729            synchronized (mPackages) {
14730                pkgSetting = mSettings.mPackages.get(packageName);
14731                if (pkgSetting == null) {
14732                    return false;
14733                }
14734                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14735                    return false;
14736                }
14737                // Do not allow "android" is being disabled
14738                if ("android".equals(packageName)) {
14739                    Slog.w(TAG, "Cannot hide package: android");
14740                    return false;
14741                }
14742                // Cannot hide static shared libs as they are considered
14743                // a part of the using app (emulating static linking). Also
14744                // static libs are installed always on internal storage.
14745                PackageParser.Package pkg = mPackages.get(packageName);
14746                if (pkg != null && pkg.staticSharedLibName != null) {
14747                    Slog.w(TAG, "Cannot hide package: " + packageName
14748                            + " providing static shared library: "
14749                            + pkg.staticSharedLibName);
14750                    return false;
14751                }
14752                // Only allow protected packages to hide themselves.
14753                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14754                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14755                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14756                    return false;
14757                }
14758
14759                if (pkgSetting.getHidden(userId) != hidden) {
14760                    pkgSetting.setHidden(hidden, userId);
14761                    mSettings.writePackageRestrictionsLPr(userId);
14762                    if (hidden) {
14763                        sendRemoved = true;
14764                    } else {
14765                        sendAdded = true;
14766                    }
14767                }
14768            }
14769            if (sendAdded) {
14770                sendPackageAddedForUser(packageName, pkgSetting, userId);
14771                return true;
14772            }
14773            if (sendRemoved) {
14774                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14775                        "hiding pkg");
14776                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14777                return true;
14778            }
14779        } finally {
14780            Binder.restoreCallingIdentity(callingId);
14781        }
14782        return false;
14783    }
14784
14785    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14786            int userId) {
14787        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14788        info.removedPackage = packageName;
14789        info.installerPackageName = pkgSetting.installerPackageName;
14790        info.removedUsers = new int[] {userId};
14791        info.broadcastUsers = new int[] {userId};
14792        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14793        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14794    }
14795
14796    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14797        if (pkgList.length > 0) {
14798            Bundle extras = new Bundle(1);
14799            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14800
14801            sendPackageBroadcast(
14802                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14803                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14804                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14805                    new int[] {userId});
14806        }
14807    }
14808
14809    /**
14810     * Returns true if application is not found or there was an error. Otherwise it returns
14811     * the hidden state of the package for the given user.
14812     */
14813    @Override
14814    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14815        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14816        final int callingUid = Binder.getCallingUid();
14817        enforceCrossUserPermission(callingUid, userId,
14818                true /* requireFullPermission */, false /* checkShell */,
14819                "getApplicationHidden for user " + userId);
14820        PackageSetting ps;
14821        long callingId = Binder.clearCallingIdentity();
14822        try {
14823            // writer
14824            synchronized (mPackages) {
14825                ps = mSettings.mPackages.get(packageName);
14826                if (ps == null) {
14827                    return true;
14828                }
14829                if (filterAppAccessLPr(ps, callingUid, userId)) {
14830                    return true;
14831                }
14832                return ps.getHidden(userId);
14833            }
14834        } finally {
14835            Binder.restoreCallingIdentity(callingId);
14836        }
14837    }
14838
14839    /**
14840     * @hide
14841     */
14842    @Override
14843    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14844            int installReason) {
14845        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14846                null);
14847        PackageSetting pkgSetting;
14848        final int callingUid = Binder.getCallingUid();
14849        enforceCrossUserPermission(callingUid, userId,
14850                true /* requireFullPermission */, true /* checkShell */,
14851                "installExistingPackage for user " + userId);
14852        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14853            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14854        }
14855
14856        long callingId = Binder.clearCallingIdentity();
14857        try {
14858            boolean installed = false;
14859            final boolean instantApp =
14860                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14861            final boolean fullApp =
14862                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14863
14864            // writer
14865            synchronized (mPackages) {
14866                pkgSetting = mSettings.mPackages.get(packageName);
14867                if (pkgSetting == null) {
14868                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14869                }
14870                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14871                    // only allow the existing package to be used if it's installed as a full
14872                    // application for at least one user
14873                    boolean installAllowed = false;
14874                    for (int checkUserId : sUserManager.getUserIds()) {
14875                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14876                        if (installAllowed) {
14877                            break;
14878                        }
14879                    }
14880                    if (!installAllowed) {
14881                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14882                    }
14883                }
14884                if (!pkgSetting.getInstalled(userId)) {
14885                    pkgSetting.setInstalled(true, userId);
14886                    pkgSetting.setHidden(false, userId);
14887                    pkgSetting.setInstallReason(installReason, userId);
14888                    mSettings.writePackageRestrictionsLPr(userId);
14889                    mSettings.writeKernelMappingLPr(pkgSetting);
14890                    installed = true;
14891                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14892                    // upgrade app from instant to full; we don't allow app downgrade
14893                    installed = true;
14894                }
14895                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14896            }
14897
14898            if (installed) {
14899                if (pkgSetting.pkg != null) {
14900                    synchronized (mInstallLock) {
14901                        // We don't need to freeze for a brand new install
14902                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14903                    }
14904                }
14905                sendPackageAddedForUser(packageName, pkgSetting, userId);
14906                synchronized (mPackages) {
14907                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14908                }
14909            }
14910        } finally {
14911            Binder.restoreCallingIdentity(callingId);
14912        }
14913
14914        return PackageManager.INSTALL_SUCCEEDED;
14915    }
14916
14917    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14918            boolean instantApp, boolean fullApp) {
14919        // no state specified; do nothing
14920        if (!instantApp && !fullApp) {
14921            return;
14922        }
14923        if (userId != UserHandle.USER_ALL) {
14924            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14925                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14926            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14927                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14928            }
14929        } else {
14930            for (int currentUserId : sUserManager.getUserIds()) {
14931                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14932                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14933                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14934                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14935                }
14936            }
14937        }
14938    }
14939
14940    boolean isUserRestricted(int userId, String restrictionKey) {
14941        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14942        if (restrictions.getBoolean(restrictionKey, false)) {
14943            Log.w(TAG, "User is restricted: " + restrictionKey);
14944            return true;
14945        }
14946        return false;
14947    }
14948
14949    @Override
14950    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14951            int userId) {
14952        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14953        final int callingUid = Binder.getCallingUid();
14954        enforceCrossUserPermission(callingUid, userId,
14955                true /* requireFullPermission */, true /* checkShell */,
14956                "setPackagesSuspended for user " + userId);
14957
14958        if (ArrayUtils.isEmpty(packageNames)) {
14959            return packageNames;
14960        }
14961
14962        // List of package names for whom the suspended state has changed.
14963        List<String> changedPackages = new ArrayList<>(packageNames.length);
14964        // List of package names for whom the suspended state is not set as requested in this
14965        // method.
14966        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14967        long callingId = Binder.clearCallingIdentity();
14968        try {
14969            for (int i = 0; i < packageNames.length; i++) {
14970                String packageName = packageNames[i];
14971                boolean changed = false;
14972                final int appId;
14973                synchronized (mPackages) {
14974                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14975                    if (pkgSetting == null
14976                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14977                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14978                                + "\". Skipping suspending/un-suspending.");
14979                        unactionedPackages.add(packageName);
14980                        continue;
14981                    }
14982                    appId = pkgSetting.appId;
14983                    if (pkgSetting.getSuspended(userId) != suspended) {
14984                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14985                            unactionedPackages.add(packageName);
14986                            continue;
14987                        }
14988                        pkgSetting.setSuspended(suspended, userId);
14989                        mSettings.writePackageRestrictionsLPr(userId);
14990                        changed = true;
14991                        changedPackages.add(packageName);
14992                    }
14993                }
14994
14995                if (changed && suspended) {
14996                    killApplication(packageName, UserHandle.getUid(userId, appId),
14997                            "suspending package");
14998                }
14999            }
15000        } finally {
15001            Binder.restoreCallingIdentity(callingId);
15002        }
15003
15004        if (!changedPackages.isEmpty()) {
15005            sendPackagesSuspendedForUser(changedPackages.toArray(
15006                    new String[changedPackages.size()]), userId, suspended);
15007        }
15008
15009        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15010    }
15011
15012    @Override
15013    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15014        final int callingUid = Binder.getCallingUid();
15015        enforceCrossUserPermission(callingUid, userId,
15016                true /* requireFullPermission */, false /* checkShell */,
15017                "isPackageSuspendedForUser for user " + userId);
15018        synchronized (mPackages) {
15019            final PackageSetting ps = mSettings.mPackages.get(packageName);
15020            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15021                throw new IllegalArgumentException("Unknown target package: " + packageName);
15022            }
15023            return ps.getSuspended(userId);
15024        }
15025    }
15026
15027    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15028        if (isPackageDeviceAdmin(packageName, userId)) {
15029            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15030                    + "\": has an active device admin");
15031            return false;
15032        }
15033
15034        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15035        if (packageName.equals(activeLauncherPackageName)) {
15036            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15037                    + "\": contains the active launcher");
15038            return false;
15039        }
15040
15041        if (packageName.equals(mRequiredInstallerPackage)) {
15042            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15043                    + "\": required for package installation");
15044            return false;
15045        }
15046
15047        if (packageName.equals(mRequiredUninstallerPackage)) {
15048            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15049                    + "\": required for package uninstallation");
15050            return false;
15051        }
15052
15053        if (packageName.equals(mRequiredVerifierPackage)) {
15054            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15055                    + "\": required for package verification");
15056            return false;
15057        }
15058
15059        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15060            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15061                    + "\": is the default dialer");
15062            return false;
15063        }
15064
15065        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15066            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15067                    + "\": protected package");
15068            return false;
15069        }
15070
15071        // Cannot suspend static shared libs as they are considered
15072        // a part of the using app (emulating static linking). Also
15073        // static libs are installed always on internal storage.
15074        PackageParser.Package pkg = mPackages.get(packageName);
15075        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15076            Slog.w(TAG, "Cannot suspend package: " + packageName
15077                    + " providing static shared library: "
15078                    + pkg.staticSharedLibName);
15079            return false;
15080        }
15081
15082        return true;
15083    }
15084
15085    private String getActiveLauncherPackageName(int userId) {
15086        Intent intent = new Intent(Intent.ACTION_MAIN);
15087        intent.addCategory(Intent.CATEGORY_HOME);
15088        ResolveInfo resolveInfo = resolveIntent(
15089                intent,
15090                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15091                PackageManager.MATCH_DEFAULT_ONLY,
15092                userId);
15093
15094        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15095    }
15096
15097    private String getDefaultDialerPackageName(int userId) {
15098        synchronized (mPackages) {
15099            return mSettings.getDefaultDialerPackageNameLPw(userId);
15100        }
15101    }
15102
15103    @Override
15104    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15105        mContext.enforceCallingOrSelfPermission(
15106                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15107                "Only package verification agents can verify applications");
15108
15109        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15110        final PackageVerificationResponse response = new PackageVerificationResponse(
15111                verificationCode, Binder.getCallingUid());
15112        msg.arg1 = id;
15113        msg.obj = response;
15114        mHandler.sendMessage(msg);
15115    }
15116
15117    @Override
15118    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15119            long millisecondsToDelay) {
15120        mContext.enforceCallingOrSelfPermission(
15121                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15122                "Only package verification agents can extend verification timeouts");
15123
15124        final PackageVerificationState state = mPendingVerification.get(id);
15125        final PackageVerificationResponse response = new PackageVerificationResponse(
15126                verificationCodeAtTimeout, Binder.getCallingUid());
15127
15128        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15129            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15130        }
15131        if (millisecondsToDelay < 0) {
15132            millisecondsToDelay = 0;
15133        }
15134        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15135                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15136            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15137        }
15138
15139        if ((state != null) && !state.timeoutExtended()) {
15140            state.extendTimeout();
15141
15142            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15143            msg.arg1 = id;
15144            msg.obj = response;
15145            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15146        }
15147    }
15148
15149    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15150            int verificationCode, UserHandle user) {
15151        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15152        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15153        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15154        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15155        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15156
15157        mContext.sendBroadcastAsUser(intent, user,
15158                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15159    }
15160
15161    private ComponentName matchComponentForVerifier(String packageName,
15162            List<ResolveInfo> receivers) {
15163        ActivityInfo targetReceiver = null;
15164
15165        final int NR = receivers.size();
15166        for (int i = 0; i < NR; i++) {
15167            final ResolveInfo info = receivers.get(i);
15168            if (info.activityInfo == null) {
15169                continue;
15170            }
15171
15172            if (packageName.equals(info.activityInfo.packageName)) {
15173                targetReceiver = info.activityInfo;
15174                break;
15175            }
15176        }
15177
15178        if (targetReceiver == null) {
15179            return null;
15180        }
15181
15182        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15183    }
15184
15185    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15186            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15187        if (pkgInfo.verifiers.length == 0) {
15188            return null;
15189        }
15190
15191        final int N = pkgInfo.verifiers.length;
15192        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15193        for (int i = 0; i < N; i++) {
15194            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15195
15196            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15197                    receivers);
15198            if (comp == null) {
15199                continue;
15200            }
15201
15202            final int verifierUid = getUidForVerifier(verifierInfo);
15203            if (verifierUid == -1) {
15204                continue;
15205            }
15206
15207            if (DEBUG_VERIFY) {
15208                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15209                        + " with the correct signature");
15210            }
15211            sufficientVerifiers.add(comp);
15212            verificationState.addSufficientVerifier(verifierUid);
15213        }
15214
15215        return sufficientVerifiers;
15216    }
15217
15218    private int getUidForVerifier(VerifierInfo verifierInfo) {
15219        synchronized (mPackages) {
15220            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15221            if (pkg == null) {
15222                return -1;
15223            } else if (pkg.mSignatures.length != 1) {
15224                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15225                        + " has more than one signature; ignoring");
15226                return -1;
15227            }
15228
15229            /*
15230             * If the public key of the package's signature does not match
15231             * our expected public key, then this is a different package and
15232             * we should skip.
15233             */
15234
15235            final byte[] expectedPublicKey;
15236            try {
15237                final Signature verifierSig = pkg.mSignatures[0];
15238                final PublicKey publicKey = verifierSig.getPublicKey();
15239                expectedPublicKey = publicKey.getEncoded();
15240            } catch (CertificateException e) {
15241                return -1;
15242            }
15243
15244            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15245
15246            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15247                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15248                        + " does not have the expected public key; ignoring");
15249                return -1;
15250            }
15251
15252            return pkg.applicationInfo.uid;
15253        }
15254    }
15255
15256    @Override
15257    public void finishPackageInstall(int token, boolean didLaunch) {
15258        enforceSystemOrRoot("Only the system is allowed to finish installs");
15259
15260        if (DEBUG_INSTALL) {
15261            Slog.v(TAG, "BM finishing package install for " + token);
15262        }
15263        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15264
15265        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15266        mHandler.sendMessage(msg);
15267    }
15268
15269    /**
15270     * Get the verification agent timeout.  Used for both the APK verifier and the
15271     * intent filter verifier.
15272     *
15273     * @return verification timeout in milliseconds
15274     */
15275    private long getVerificationTimeout() {
15276        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15277                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15278                DEFAULT_VERIFICATION_TIMEOUT);
15279    }
15280
15281    /**
15282     * Get the default verification agent response code.
15283     *
15284     * @return default verification response code
15285     */
15286    private int getDefaultVerificationResponse(UserHandle user) {
15287        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15288            return PackageManager.VERIFICATION_REJECT;
15289        }
15290        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15291                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15292                DEFAULT_VERIFICATION_RESPONSE);
15293    }
15294
15295    /**
15296     * Check whether or not package verification has been enabled.
15297     *
15298     * @return true if verification should be performed
15299     */
15300    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15301        if (!DEFAULT_VERIFY_ENABLE) {
15302            return false;
15303        }
15304
15305        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15306
15307        // Check if installing from ADB
15308        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15309            // Do not run verification in a test harness environment
15310            if (ActivityManager.isRunningInTestHarness()) {
15311                return false;
15312            }
15313            if (ensureVerifyAppsEnabled) {
15314                return true;
15315            }
15316            // Check if the developer does not want package verification for ADB installs
15317            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15318                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15319                return false;
15320            }
15321        } else {
15322            // only when not installed from ADB, skip verification for instant apps when
15323            // the installer and verifier are the same.
15324            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15325                if (mInstantAppInstallerActivity != null
15326                        && mInstantAppInstallerActivity.packageName.equals(
15327                                mRequiredVerifierPackage)) {
15328                    try {
15329                        mContext.getSystemService(AppOpsManager.class)
15330                                .checkPackage(installerUid, mRequiredVerifierPackage);
15331                        if (DEBUG_VERIFY) {
15332                            Slog.i(TAG, "disable verification for instant app");
15333                        }
15334                        return false;
15335                    } catch (SecurityException ignore) { }
15336                }
15337            }
15338        }
15339
15340        if (ensureVerifyAppsEnabled) {
15341            return true;
15342        }
15343
15344        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15345                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15346    }
15347
15348    @Override
15349    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15350            throws RemoteException {
15351        mContext.enforceCallingOrSelfPermission(
15352                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15353                "Only intentfilter verification agents can verify applications");
15354
15355        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15356        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15357                Binder.getCallingUid(), verificationCode, failedDomains);
15358        msg.arg1 = id;
15359        msg.obj = response;
15360        mHandler.sendMessage(msg);
15361    }
15362
15363    @Override
15364    public int getIntentVerificationStatus(String packageName, int userId) {
15365        final int callingUid = Binder.getCallingUid();
15366        if (UserHandle.getUserId(callingUid) != userId) {
15367            mContext.enforceCallingOrSelfPermission(
15368                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15369                    "getIntentVerificationStatus" + userId);
15370        }
15371        if (getInstantAppPackageName(callingUid) != null) {
15372            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15373        }
15374        synchronized (mPackages) {
15375            final PackageSetting ps = mSettings.mPackages.get(packageName);
15376            if (ps == null
15377                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15378                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15379            }
15380            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15381        }
15382    }
15383
15384    @Override
15385    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15386        mContext.enforceCallingOrSelfPermission(
15387                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15388
15389        boolean result = false;
15390        synchronized (mPackages) {
15391            final PackageSetting ps = mSettings.mPackages.get(packageName);
15392            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15393                return false;
15394            }
15395            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15396        }
15397        if (result) {
15398            scheduleWritePackageRestrictionsLocked(userId);
15399        }
15400        return result;
15401    }
15402
15403    @Override
15404    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15405            String packageName) {
15406        final int callingUid = Binder.getCallingUid();
15407        if (getInstantAppPackageName(callingUid) != null) {
15408            return ParceledListSlice.emptyList();
15409        }
15410        synchronized (mPackages) {
15411            final PackageSetting ps = mSettings.mPackages.get(packageName);
15412            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15413                return ParceledListSlice.emptyList();
15414            }
15415            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15416        }
15417    }
15418
15419    @Override
15420    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15421        if (TextUtils.isEmpty(packageName)) {
15422            return ParceledListSlice.emptyList();
15423        }
15424        final int callingUid = Binder.getCallingUid();
15425        final int callingUserId = UserHandle.getUserId(callingUid);
15426        synchronized (mPackages) {
15427            PackageParser.Package pkg = mPackages.get(packageName);
15428            if (pkg == null || pkg.activities == null) {
15429                return ParceledListSlice.emptyList();
15430            }
15431            if (pkg.mExtras == null) {
15432                return ParceledListSlice.emptyList();
15433            }
15434            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15435            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15436                return ParceledListSlice.emptyList();
15437            }
15438            final int count = pkg.activities.size();
15439            ArrayList<IntentFilter> result = new ArrayList<>();
15440            for (int n=0; n<count; n++) {
15441                PackageParser.Activity activity = pkg.activities.get(n);
15442                if (activity.intents != null && activity.intents.size() > 0) {
15443                    result.addAll(activity.intents);
15444                }
15445            }
15446            return new ParceledListSlice<>(result);
15447        }
15448    }
15449
15450    @Override
15451    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15452        mContext.enforceCallingOrSelfPermission(
15453                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15454        if (UserHandle.getCallingUserId() != userId) {
15455            mContext.enforceCallingOrSelfPermission(
15456                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15457        }
15458
15459        synchronized (mPackages) {
15460            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15461            if (packageName != null) {
15462                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15463                        packageName, userId);
15464            }
15465            return result;
15466        }
15467    }
15468
15469    @Override
15470    public String getDefaultBrowserPackageName(int userId) {
15471        if (UserHandle.getCallingUserId() != userId) {
15472            mContext.enforceCallingOrSelfPermission(
15473                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15474        }
15475        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15476            return null;
15477        }
15478        synchronized (mPackages) {
15479            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15480        }
15481    }
15482
15483    /**
15484     * Get the "allow unknown sources" setting.
15485     *
15486     * @return the current "allow unknown sources" setting
15487     */
15488    private int getUnknownSourcesSettings() {
15489        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15490                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15491                -1);
15492    }
15493
15494    @Override
15495    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15496        final int callingUid = Binder.getCallingUid();
15497        if (getInstantAppPackageName(callingUid) != null) {
15498            return;
15499        }
15500        // writer
15501        synchronized (mPackages) {
15502            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15503            if (targetPackageSetting == null
15504                    || filterAppAccessLPr(
15505                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15506                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15507            }
15508
15509            PackageSetting installerPackageSetting;
15510            if (installerPackageName != null) {
15511                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15512                if (installerPackageSetting == null) {
15513                    throw new IllegalArgumentException("Unknown installer package: "
15514                            + installerPackageName);
15515                }
15516            } else {
15517                installerPackageSetting = null;
15518            }
15519
15520            Signature[] callerSignature;
15521            Object obj = mSettings.getUserIdLPr(callingUid);
15522            if (obj != null) {
15523                if (obj instanceof SharedUserSetting) {
15524                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15525                } else if (obj instanceof PackageSetting) {
15526                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15527                } else {
15528                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15529                }
15530            } else {
15531                throw new SecurityException("Unknown calling UID: " + callingUid);
15532            }
15533
15534            // Verify: can't set installerPackageName to a package that is
15535            // not signed with the same cert as the caller.
15536            if (installerPackageSetting != null) {
15537                if (compareSignatures(callerSignature,
15538                        installerPackageSetting.signatures.mSignatures)
15539                        != PackageManager.SIGNATURE_MATCH) {
15540                    throw new SecurityException(
15541                            "Caller does not have same cert as new installer package "
15542                            + installerPackageName);
15543                }
15544            }
15545
15546            // Verify: if target already has an installer package, it must
15547            // be signed with the same cert as the caller.
15548            if (targetPackageSetting.installerPackageName != null) {
15549                PackageSetting setting = mSettings.mPackages.get(
15550                        targetPackageSetting.installerPackageName);
15551                // If the currently set package isn't valid, then it's always
15552                // okay to change it.
15553                if (setting != null) {
15554                    if (compareSignatures(callerSignature,
15555                            setting.signatures.mSignatures)
15556                            != PackageManager.SIGNATURE_MATCH) {
15557                        throw new SecurityException(
15558                                "Caller does not have same cert as old installer package "
15559                                + targetPackageSetting.installerPackageName);
15560                    }
15561                }
15562            }
15563
15564            // Okay!
15565            targetPackageSetting.installerPackageName = installerPackageName;
15566            if (installerPackageName != null) {
15567                mSettings.mInstallerPackages.add(installerPackageName);
15568            }
15569            scheduleWriteSettingsLocked();
15570        }
15571    }
15572
15573    @Override
15574    public void setApplicationCategoryHint(String packageName, int categoryHint,
15575            String callerPackageName) {
15576        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15577            throw new SecurityException("Instant applications don't have access to this method");
15578        }
15579        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15580                callerPackageName);
15581        synchronized (mPackages) {
15582            PackageSetting ps = mSettings.mPackages.get(packageName);
15583            if (ps == null) {
15584                throw new IllegalArgumentException("Unknown target package " + packageName);
15585            }
15586            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15587                throw new IllegalArgumentException("Unknown target package " + packageName);
15588            }
15589            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15590                throw new IllegalArgumentException("Calling package " + callerPackageName
15591                        + " is not installer for " + packageName);
15592            }
15593
15594            if (ps.categoryHint != categoryHint) {
15595                ps.categoryHint = categoryHint;
15596                scheduleWriteSettingsLocked();
15597            }
15598        }
15599    }
15600
15601    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15602        // Queue up an async operation since the package installation may take a little while.
15603        mHandler.post(new Runnable() {
15604            public void run() {
15605                mHandler.removeCallbacks(this);
15606                 // Result object to be returned
15607                PackageInstalledInfo res = new PackageInstalledInfo();
15608                res.setReturnCode(currentStatus);
15609                res.uid = -1;
15610                res.pkg = null;
15611                res.removedInfo = null;
15612                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15613                    args.doPreInstall(res.returnCode);
15614                    synchronized (mInstallLock) {
15615                        installPackageTracedLI(args, res);
15616                    }
15617                    args.doPostInstall(res.returnCode, res.uid);
15618                }
15619
15620                // A restore should be performed at this point if (a) the install
15621                // succeeded, (b) the operation is not an update, and (c) the new
15622                // package has not opted out of backup participation.
15623                final boolean update = res.removedInfo != null
15624                        && res.removedInfo.removedPackage != null;
15625                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15626                boolean doRestore = !update
15627                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15628
15629                // Set up the post-install work request bookkeeping.  This will be used
15630                // and cleaned up by the post-install event handling regardless of whether
15631                // there's a restore pass performed.  Token values are >= 1.
15632                int token;
15633                if (mNextInstallToken < 0) mNextInstallToken = 1;
15634                token = mNextInstallToken++;
15635
15636                PostInstallData data = new PostInstallData(args, res);
15637                mRunningInstalls.put(token, data);
15638                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15639
15640                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15641                    // Pass responsibility to the Backup Manager.  It will perform a
15642                    // restore if appropriate, then pass responsibility back to the
15643                    // Package Manager to run the post-install observer callbacks
15644                    // and broadcasts.
15645                    IBackupManager bm = IBackupManager.Stub.asInterface(
15646                            ServiceManager.getService(Context.BACKUP_SERVICE));
15647                    if (bm != null) {
15648                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15649                                + " to BM for possible restore");
15650                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15651                        try {
15652                            // TODO: http://b/22388012
15653                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15654                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15655                            } else {
15656                                doRestore = false;
15657                            }
15658                        } catch (RemoteException e) {
15659                            // can't happen; the backup manager is local
15660                        } catch (Exception e) {
15661                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15662                            doRestore = false;
15663                        }
15664                    } else {
15665                        Slog.e(TAG, "Backup Manager not found!");
15666                        doRestore = false;
15667                    }
15668                }
15669
15670                if (!doRestore) {
15671                    // No restore possible, or the Backup Manager was mysteriously not
15672                    // available -- just fire the post-install work request directly.
15673                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15674
15675                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15676
15677                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15678                    mHandler.sendMessage(msg);
15679                }
15680            }
15681        });
15682    }
15683
15684    /**
15685     * Callback from PackageSettings whenever an app is first transitioned out of the
15686     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15687     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15688     * here whether the app is the target of an ongoing install, and only send the
15689     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15690     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15691     * handling.
15692     */
15693    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15694        // Serialize this with the rest of the install-process message chain.  In the
15695        // restore-at-install case, this Runnable will necessarily run before the
15696        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15697        // are coherent.  In the non-restore case, the app has already completed install
15698        // and been launched through some other means, so it is not in a problematic
15699        // state for observers to see the FIRST_LAUNCH signal.
15700        mHandler.post(new Runnable() {
15701            @Override
15702            public void run() {
15703                for (int i = 0; i < mRunningInstalls.size(); i++) {
15704                    final PostInstallData data = mRunningInstalls.valueAt(i);
15705                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15706                        continue;
15707                    }
15708                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15709                        // right package; but is it for the right user?
15710                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15711                            if (userId == data.res.newUsers[uIndex]) {
15712                                if (DEBUG_BACKUP) {
15713                                    Slog.i(TAG, "Package " + pkgName
15714                                            + " being restored so deferring FIRST_LAUNCH");
15715                                }
15716                                return;
15717                            }
15718                        }
15719                    }
15720                }
15721                // didn't find it, so not being restored
15722                if (DEBUG_BACKUP) {
15723                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15724                }
15725                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15726            }
15727        });
15728    }
15729
15730    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15731        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15732                installerPkg, null, userIds);
15733    }
15734
15735    private abstract class HandlerParams {
15736        private static final int MAX_RETRIES = 4;
15737
15738        /**
15739         * Number of times startCopy() has been attempted and had a non-fatal
15740         * error.
15741         */
15742        private int mRetries = 0;
15743
15744        /** User handle for the user requesting the information or installation. */
15745        private final UserHandle mUser;
15746        String traceMethod;
15747        int traceCookie;
15748
15749        HandlerParams(UserHandle user) {
15750            mUser = user;
15751        }
15752
15753        UserHandle getUser() {
15754            return mUser;
15755        }
15756
15757        HandlerParams setTraceMethod(String traceMethod) {
15758            this.traceMethod = traceMethod;
15759            return this;
15760        }
15761
15762        HandlerParams setTraceCookie(int traceCookie) {
15763            this.traceCookie = traceCookie;
15764            return this;
15765        }
15766
15767        final boolean startCopy() {
15768            boolean res;
15769            try {
15770                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15771
15772                if (++mRetries > MAX_RETRIES) {
15773                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15774                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15775                    handleServiceError();
15776                    return false;
15777                } else {
15778                    handleStartCopy();
15779                    res = true;
15780                }
15781            } catch (RemoteException e) {
15782                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15783                mHandler.sendEmptyMessage(MCS_RECONNECT);
15784                res = false;
15785            }
15786            handleReturnCode();
15787            return res;
15788        }
15789
15790        final void serviceError() {
15791            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15792            handleServiceError();
15793            handleReturnCode();
15794        }
15795
15796        abstract void handleStartCopy() throws RemoteException;
15797        abstract void handleServiceError();
15798        abstract void handleReturnCode();
15799    }
15800
15801    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15802        for (File path : paths) {
15803            try {
15804                mcs.clearDirectory(path.getAbsolutePath());
15805            } catch (RemoteException e) {
15806            }
15807        }
15808    }
15809
15810    static class OriginInfo {
15811        /**
15812         * Location where install is coming from, before it has been
15813         * copied/renamed into place. This could be a single monolithic APK
15814         * file, or a cluster directory. This location may be untrusted.
15815         */
15816        final File file;
15817        final String cid;
15818
15819        /**
15820         * Flag indicating that {@link #file} or {@link #cid} has already been
15821         * staged, meaning downstream users don't need to defensively copy the
15822         * contents.
15823         */
15824        final boolean staged;
15825
15826        /**
15827         * Flag indicating that {@link #file} or {@link #cid} is an already
15828         * installed app that is being moved.
15829         */
15830        final boolean existing;
15831
15832        final String resolvedPath;
15833        final File resolvedFile;
15834
15835        static OriginInfo fromNothing() {
15836            return new OriginInfo(null, null, false, false);
15837        }
15838
15839        static OriginInfo fromUntrustedFile(File file) {
15840            return new OriginInfo(file, null, false, false);
15841        }
15842
15843        static OriginInfo fromExistingFile(File file) {
15844            return new OriginInfo(file, null, false, true);
15845        }
15846
15847        static OriginInfo fromStagedFile(File file) {
15848            return new OriginInfo(file, null, true, false);
15849        }
15850
15851        static OriginInfo fromStagedContainer(String cid) {
15852            return new OriginInfo(null, cid, true, false);
15853        }
15854
15855        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15856            this.file = file;
15857            this.cid = cid;
15858            this.staged = staged;
15859            this.existing = existing;
15860
15861            if (cid != null) {
15862                resolvedPath = PackageHelper.getSdDir(cid);
15863                resolvedFile = new File(resolvedPath);
15864            } else if (file != null) {
15865                resolvedPath = file.getAbsolutePath();
15866                resolvedFile = file;
15867            } else {
15868                resolvedPath = null;
15869                resolvedFile = null;
15870            }
15871        }
15872    }
15873
15874    static class MoveInfo {
15875        final int moveId;
15876        final String fromUuid;
15877        final String toUuid;
15878        final String packageName;
15879        final String dataAppName;
15880        final int appId;
15881        final String seinfo;
15882        final int targetSdkVersion;
15883
15884        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15885                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15886            this.moveId = moveId;
15887            this.fromUuid = fromUuid;
15888            this.toUuid = toUuid;
15889            this.packageName = packageName;
15890            this.dataAppName = dataAppName;
15891            this.appId = appId;
15892            this.seinfo = seinfo;
15893            this.targetSdkVersion = targetSdkVersion;
15894        }
15895    }
15896
15897    static class VerificationInfo {
15898        /** A constant used to indicate that a uid value is not present. */
15899        public static final int NO_UID = -1;
15900
15901        /** URI referencing where the package was downloaded from. */
15902        final Uri originatingUri;
15903
15904        /** HTTP referrer URI associated with the originatingURI. */
15905        final Uri referrer;
15906
15907        /** UID of the application that the install request originated from. */
15908        final int originatingUid;
15909
15910        /** UID of application requesting the install */
15911        final int installerUid;
15912
15913        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15914            this.originatingUri = originatingUri;
15915            this.referrer = referrer;
15916            this.originatingUid = originatingUid;
15917            this.installerUid = installerUid;
15918        }
15919    }
15920
15921    class InstallParams extends HandlerParams {
15922        final OriginInfo origin;
15923        final MoveInfo move;
15924        final IPackageInstallObserver2 observer;
15925        int installFlags;
15926        final String installerPackageName;
15927        final String volumeUuid;
15928        private InstallArgs mArgs;
15929        private int mRet;
15930        final String packageAbiOverride;
15931        final String[] grantedRuntimePermissions;
15932        final VerificationInfo verificationInfo;
15933        final Certificate[][] certificates;
15934        final int installReason;
15935
15936        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15937                int installFlags, String installerPackageName, String volumeUuid,
15938                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15939                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15940            super(user);
15941            this.origin = origin;
15942            this.move = move;
15943            this.observer = observer;
15944            this.installFlags = installFlags;
15945            this.installerPackageName = installerPackageName;
15946            this.volumeUuid = volumeUuid;
15947            this.verificationInfo = verificationInfo;
15948            this.packageAbiOverride = packageAbiOverride;
15949            this.grantedRuntimePermissions = grantedPermissions;
15950            this.certificates = certificates;
15951            this.installReason = installReason;
15952        }
15953
15954        @Override
15955        public String toString() {
15956            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15957                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15958        }
15959
15960        private int installLocationPolicy(PackageInfoLite pkgLite) {
15961            String packageName = pkgLite.packageName;
15962            int installLocation = pkgLite.installLocation;
15963            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15964            // reader
15965            synchronized (mPackages) {
15966                // Currently installed package which the new package is attempting to replace or
15967                // null if no such package is installed.
15968                PackageParser.Package installedPkg = mPackages.get(packageName);
15969                // Package which currently owns the data which the new package will own if installed.
15970                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15971                // will be null whereas dataOwnerPkg will contain information about the package
15972                // which was uninstalled while keeping its data.
15973                PackageParser.Package dataOwnerPkg = installedPkg;
15974                if (dataOwnerPkg  == null) {
15975                    PackageSetting ps = mSettings.mPackages.get(packageName);
15976                    if (ps != null) {
15977                        dataOwnerPkg = ps.pkg;
15978                    }
15979                }
15980
15981                if (dataOwnerPkg != null) {
15982                    // If installed, the package will get access to data left on the device by its
15983                    // predecessor. As a security measure, this is permited only if this is not a
15984                    // version downgrade or if the predecessor package is marked as debuggable and
15985                    // a downgrade is explicitly requested.
15986                    //
15987                    // On debuggable platform builds, downgrades are permitted even for
15988                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15989                    // not offer security guarantees and thus it's OK to disable some security
15990                    // mechanisms to make debugging/testing easier on those builds. However, even on
15991                    // debuggable builds downgrades of packages are permitted only if requested via
15992                    // installFlags. This is because we aim to keep the behavior of debuggable
15993                    // platform builds as close as possible to the behavior of non-debuggable
15994                    // platform builds.
15995                    final boolean downgradeRequested =
15996                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15997                    final boolean packageDebuggable =
15998                                (dataOwnerPkg.applicationInfo.flags
15999                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16000                    final boolean downgradePermitted =
16001                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16002                    if (!downgradePermitted) {
16003                        try {
16004                            checkDowngrade(dataOwnerPkg, pkgLite);
16005                        } catch (PackageManagerException e) {
16006                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16007                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16008                        }
16009                    }
16010                }
16011
16012                if (installedPkg != null) {
16013                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16014                        // Check for updated system application.
16015                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16016                            if (onSd) {
16017                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16018                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16019                            }
16020                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16021                        } else {
16022                            if (onSd) {
16023                                // Install flag overrides everything.
16024                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16025                            }
16026                            // If current upgrade specifies particular preference
16027                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16028                                // Application explicitly specified internal.
16029                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16030                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16031                                // App explictly prefers external. Let policy decide
16032                            } else {
16033                                // Prefer previous location
16034                                if (isExternal(installedPkg)) {
16035                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16036                                }
16037                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16038                            }
16039                        }
16040                    } else {
16041                        // Invalid install. Return error code
16042                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16043                    }
16044                }
16045            }
16046            // All the special cases have been taken care of.
16047            // Return result based on recommended install location.
16048            if (onSd) {
16049                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16050            }
16051            return pkgLite.recommendedInstallLocation;
16052        }
16053
16054        /*
16055         * Invoke remote method to get package information and install
16056         * location values. Override install location based on default
16057         * policy if needed and then create install arguments based
16058         * on the install location.
16059         */
16060        public void handleStartCopy() throws RemoteException {
16061            int ret = PackageManager.INSTALL_SUCCEEDED;
16062
16063            // If we're already staged, we've firmly committed to an install location
16064            if (origin.staged) {
16065                if (origin.file != null) {
16066                    installFlags |= PackageManager.INSTALL_INTERNAL;
16067                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16068                } else if (origin.cid != null) {
16069                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16070                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16071                } else {
16072                    throw new IllegalStateException("Invalid stage location");
16073                }
16074            }
16075
16076            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16077            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16078            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16079            PackageInfoLite pkgLite = null;
16080
16081            if (onInt && onSd) {
16082                // Check if both bits are set.
16083                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16084                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16085            } else if (onSd && ephemeral) {
16086                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16087                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16088            } else {
16089                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16090                        packageAbiOverride);
16091
16092                if (DEBUG_EPHEMERAL && ephemeral) {
16093                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16094                }
16095
16096                /*
16097                 * If we have too little free space, try to free cache
16098                 * before giving up.
16099                 */
16100                if (!origin.staged && pkgLite.recommendedInstallLocation
16101                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16102                    // TODO: focus freeing disk space on the target device
16103                    final StorageManager storage = StorageManager.from(mContext);
16104                    final long lowThreshold = storage.getStorageLowBytes(
16105                            Environment.getDataDirectory());
16106
16107                    final long sizeBytes = mContainerService.calculateInstalledSize(
16108                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16109
16110                    try {
16111                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16112                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16113                                installFlags, packageAbiOverride);
16114                    } catch (InstallerException e) {
16115                        Slog.w(TAG, "Failed to free cache", e);
16116                    }
16117
16118                    /*
16119                     * The cache free must have deleted the file we
16120                     * downloaded to install.
16121                     *
16122                     * TODO: fix the "freeCache" call to not delete
16123                     *       the file we care about.
16124                     */
16125                    if (pkgLite.recommendedInstallLocation
16126                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16127                        pkgLite.recommendedInstallLocation
16128                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16129                    }
16130                }
16131            }
16132
16133            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16134                int loc = pkgLite.recommendedInstallLocation;
16135                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16136                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16137                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16138                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16139                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16140                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16141                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16142                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16143                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16144                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16145                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16146                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16147                } else {
16148                    // Override with defaults if needed.
16149                    loc = installLocationPolicy(pkgLite);
16150                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16151                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16152                    } else if (!onSd && !onInt) {
16153                        // Override install location with flags
16154                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16155                            // Set the flag to install on external media.
16156                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16157                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16158                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16159                            if (DEBUG_EPHEMERAL) {
16160                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16161                            }
16162                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16163                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16164                                    |PackageManager.INSTALL_INTERNAL);
16165                        } else {
16166                            // Make sure the flag for installing on external
16167                            // media is unset
16168                            installFlags |= PackageManager.INSTALL_INTERNAL;
16169                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16170                        }
16171                    }
16172                }
16173            }
16174
16175            final InstallArgs args = createInstallArgs(this);
16176            mArgs = args;
16177
16178            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16179                // TODO: http://b/22976637
16180                // Apps installed for "all" users use the device owner to verify the app
16181                UserHandle verifierUser = getUser();
16182                if (verifierUser == UserHandle.ALL) {
16183                    verifierUser = UserHandle.SYSTEM;
16184                }
16185
16186                /*
16187                 * Determine if we have any installed package verifiers. If we
16188                 * do, then we'll defer to them to verify the packages.
16189                 */
16190                final int requiredUid = mRequiredVerifierPackage == null ? -1
16191                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16192                                verifierUser.getIdentifier());
16193                final int installerUid =
16194                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16195                if (!origin.existing && requiredUid != -1
16196                        && isVerificationEnabled(
16197                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16198                    final Intent verification = new Intent(
16199                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16200                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16201                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16202                            PACKAGE_MIME_TYPE);
16203                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16204
16205                    // Query all live verifiers based on current user state
16206                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16207                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
16208
16209                    if (DEBUG_VERIFY) {
16210                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16211                                + verification.toString() + " with " + pkgLite.verifiers.length
16212                                + " optional verifiers");
16213                    }
16214
16215                    final int verificationId = mPendingVerificationToken++;
16216
16217                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16218
16219                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16220                            installerPackageName);
16221
16222                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16223                            installFlags);
16224
16225                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16226                            pkgLite.packageName);
16227
16228                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16229                            pkgLite.versionCode);
16230
16231                    if (verificationInfo != null) {
16232                        if (verificationInfo.originatingUri != null) {
16233                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16234                                    verificationInfo.originatingUri);
16235                        }
16236                        if (verificationInfo.referrer != null) {
16237                            verification.putExtra(Intent.EXTRA_REFERRER,
16238                                    verificationInfo.referrer);
16239                        }
16240                        if (verificationInfo.originatingUid >= 0) {
16241                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16242                                    verificationInfo.originatingUid);
16243                        }
16244                        if (verificationInfo.installerUid >= 0) {
16245                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16246                                    verificationInfo.installerUid);
16247                        }
16248                    }
16249
16250                    final PackageVerificationState verificationState = new PackageVerificationState(
16251                            requiredUid, args);
16252
16253                    mPendingVerification.append(verificationId, verificationState);
16254
16255                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16256                            receivers, verificationState);
16257
16258                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16259                    final long idleDuration = getVerificationTimeout();
16260
16261                    /*
16262                     * If any sufficient verifiers were listed in the package
16263                     * manifest, attempt to ask them.
16264                     */
16265                    if (sufficientVerifiers != null) {
16266                        final int N = sufficientVerifiers.size();
16267                        if (N == 0) {
16268                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16269                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16270                        } else {
16271                            for (int i = 0; i < N; i++) {
16272                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16273                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16274                                        verifierComponent.getPackageName(), idleDuration,
16275                                        verifierUser.getIdentifier(), false, "package verifier");
16276
16277                                final Intent sufficientIntent = new Intent(verification);
16278                                sufficientIntent.setComponent(verifierComponent);
16279                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16280                            }
16281                        }
16282                    }
16283
16284                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16285                            mRequiredVerifierPackage, receivers);
16286                    if (ret == PackageManager.INSTALL_SUCCEEDED
16287                            && mRequiredVerifierPackage != null) {
16288                        Trace.asyncTraceBegin(
16289                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16290                        /*
16291                         * Send the intent to the required verification agent,
16292                         * but only start the verification timeout after the
16293                         * target BroadcastReceivers have run.
16294                         */
16295                        verification.setComponent(requiredVerifierComponent);
16296                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16297                                mRequiredVerifierPackage, idleDuration,
16298                                verifierUser.getIdentifier(), false, "package verifier");
16299                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16300                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16301                                new BroadcastReceiver() {
16302                                    @Override
16303                                    public void onReceive(Context context, Intent intent) {
16304                                        final Message msg = mHandler
16305                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16306                                        msg.arg1 = verificationId;
16307                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16308                                    }
16309                                }, null, 0, null, null);
16310
16311                        /*
16312                         * We don't want the copy to proceed until verification
16313                         * succeeds, so null out this field.
16314                         */
16315                        mArgs = null;
16316                    }
16317                } else {
16318                    /*
16319                     * No package verification is enabled, so immediately start
16320                     * the remote call to initiate copy using temporary file.
16321                     */
16322                    ret = args.copyApk(mContainerService, true);
16323                }
16324            }
16325
16326            mRet = ret;
16327        }
16328
16329        @Override
16330        void handleReturnCode() {
16331            // If mArgs is null, then MCS couldn't be reached. When it
16332            // reconnects, it will try again to install. At that point, this
16333            // will succeed.
16334            if (mArgs != null) {
16335                processPendingInstall(mArgs, mRet);
16336            }
16337        }
16338
16339        @Override
16340        void handleServiceError() {
16341            mArgs = createInstallArgs(this);
16342            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16343        }
16344
16345        public boolean isForwardLocked() {
16346            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16347        }
16348    }
16349
16350    /**
16351     * Used during creation of InstallArgs
16352     *
16353     * @param installFlags package installation flags
16354     * @return true if should be installed on external storage
16355     */
16356    private static boolean installOnExternalAsec(int installFlags) {
16357        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16358            return false;
16359        }
16360        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16361            return true;
16362        }
16363        return false;
16364    }
16365
16366    /**
16367     * Used during creation of InstallArgs
16368     *
16369     * @param installFlags package installation flags
16370     * @return true if should be installed as forward locked
16371     */
16372    private static boolean installForwardLocked(int installFlags) {
16373        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16374    }
16375
16376    private InstallArgs createInstallArgs(InstallParams params) {
16377        if (params.move != null) {
16378            return new MoveInstallArgs(params);
16379        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16380            return new AsecInstallArgs(params);
16381        } else {
16382            return new FileInstallArgs(params);
16383        }
16384    }
16385
16386    /**
16387     * Create args that describe an existing installed package. Typically used
16388     * when cleaning up old installs, or used as a move source.
16389     */
16390    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16391            String resourcePath, String[] instructionSets) {
16392        final boolean isInAsec;
16393        if (installOnExternalAsec(installFlags)) {
16394            /* Apps on SD card are always in ASEC containers. */
16395            isInAsec = true;
16396        } else if (installForwardLocked(installFlags)
16397                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16398            /*
16399             * Forward-locked apps are only in ASEC containers if they're the
16400             * new style
16401             */
16402            isInAsec = true;
16403        } else {
16404            isInAsec = false;
16405        }
16406
16407        if (isInAsec) {
16408            return new AsecInstallArgs(codePath, instructionSets,
16409                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16410        } else {
16411            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16412        }
16413    }
16414
16415    static abstract class InstallArgs {
16416        /** @see InstallParams#origin */
16417        final OriginInfo origin;
16418        /** @see InstallParams#move */
16419        final MoveInfo move;
16420
16421        final IPackageInstallObserver2 observer;
16422        // Always refers to PackageManager flags only
16423        final int installFlags;
16424        final String installerPackageName;
16425        final String volumeUuid;
16426        final UserHandle user;
16427        final String abiOverride;
16428        final String[] installGrantPermissions;
16429        /** If non-null, drop an async trace when the install completes */
16430        final String traceMethod;
16431        final int traceCookie;
16432        final Certificate[][] certificates;
16433        final int installReason;
16434
16435        // The list of instruction sets supported by this app. This is currently
16436        // only used during the rmdex() phase to clean up resources. We can get rid of this
16437        // if we move dex files under the common app path.
16438        /* nullable */ String[] instructionSets;
16439
16440        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16441                int installFlags, String installerPackageName, String volumeUuid,
16442                UserHandle user, String[] instructionSets,
16443                String abiOverride, String[] installGrantPermissions,
16444                String traceMethod, int traceCookie, Certificate[][] certificates,
16445                int installReason) {
16446            this.origin = origin;
16447            this.move = move;
16448            this.installFlags = installFlags;
16449            this.observer = observer;
16450            this.installerPackageName = installerPackageName;
16451            this.volumeUuid = volumeUuid;
16452            this.user = user;
16453            this.instructionSets = instructionSets;
16454            this.abiOverride = abiOverride;
16455            this.installGrantPermissions = installGrantPermissions;
16456            this.traceMethod = traceMethod;
16457            this.traceCookie = traceCookie;
16458            this.certificates = certificates;
16459            this.installReason = installReason;
16460        }
16461
16462        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16463        abstract int doPreInstall(int status);
16464
16465        /**
16466         * Rename package into final resting place. All paths on the given
16467         * scanned package should be updated to reflect the rename.
16468         */
16469        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16470        abstract int doPostInstall(int status, int uid);
16471
16472        /** @see PackageSettingBase#codePathString */
16473        abstract String getCodePath();
16474        /** @see PackageSettingBase#resourcePathString */
16475        abstract String getResourcePath();
16476
16477        // Need installer lock especially for dex file removal.
16478        abstract void cleanUpResourcesLI();
16479        abstract boolean doPostDeleteLI(boolean delete);
16480
16481        /**
16482         * Called before the source arguments are copied. This is used mostly
16483         * for MoveParams when it needs to read the source file to put it in the
16484         * destination.
16485         */
16486        int doPreCopy() {
16487            return PackageManager.INSTALL_SUCCEEDED;
16488        }
16489
16490        /**
16491         * Called after the source arguments are copied. This is used mostly for
16492         * MoveParams when it needs to read the source file to put it in the
16493         * destination.
16494         */
16495        int doPostCopy(int uid) {
16496            return PackageManager.INSTALL_SUCCEEDED;
16497        }
16498
16499        protected boolean isFwdLocked() {
16500            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16501        }
16502
16503        protected boolean isExternalAsec() {
16504            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16505        }
16506
16507        protected boolean isEphemeral() {
16508            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16509        }
16510
16511        UserHandle getUser() {
16512            return user;
16513        }
16514    }
16515
16516    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16517        if (!allCodePaths.isEmpty()) {
16518            if (instructionSets == null) {
16519                throw new IllegalStateException("instructionSet == null");
16520            }
16521            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16522            for (String codePath : allCodePaths) {
16523                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16524                    try {
16525                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16526                    } catch (InstallerException ignored) {
16527                    }
16528                }
16529            }
16530        }
16531    }
16532
16533    /**
16534     * Logic to handle installation of non-ASEC applications, including copying
16535     * and renaming logic.
16536     */
16537    class FileInstallArgs extends InstallArgs {
16538        private File codeFile;
16539        private File resourceFile;
16540
16541        // Example topology:
16542        // /data/app/com.example/base.apk
16543        // /data/app/com.example/split_foo.apk
16544        // /data/app/com.example/lib/arm/libfoo.so
16545        // /data/app/com.example/lib/arm64/libfoo.so
16546        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16547
16548        /** New install */
16549        FileInstallArgs(InstallParams params) {
16550            super(params.origin, params.move, params.observer, params.installFlags,
16551                    params.installerPackageName, params.volumeUuid,
16552                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16553                    params.grantedRuntimePermissions,
16554                    params.traceMethod, params.traceCookie, params.certificates,
16555                    params.installReason);
16556            if (isFwdLocked()) {
16557                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16558            }
16559        }
16560
16561        /** Existing install */
16562        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16563            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16564                    null, null, null, 0, null /*certificates*/,
16565                    PackageManager.INSTALL_REASON_UNKNOWN);
16566            this.codeFile = (codePath != null) ? new File(codePath) : null;
16567            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16568        }
16569
16570        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16571            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16572            try {
16573                return doCopyApk(imcs, temp);
16574            } finally {
16575                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16576            }
16577        }
16578
16579        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16580            if (origin.staged) {
16581                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16582                codeFile = origin.file;
16583                resourceFile = origin.file;
16584                return PackageManager.INSTALL_SUCCEEDED;
16585            }
16586
16587            try {
16588                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16589                final File tempDir =
16590                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16591                codeFile = tempDir;
16592                resourceFile = tempDir;
16593            } catch (IOException e) {
16594                Slog.w(TAG, "Failed to create copy file: " + e);
16595                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16596            }
16597
16598            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16599                @Override
16600                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16601                    if (!FileUtils.isValidExtFilename(name)) {
16602                        throw new IllegalArgumentException("Invalid filename: " + name);
16603                    }
16604                    try {
16605                        final File file = new File(codeFile, name);
16606                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16607                                O_RDWR | O_CREAT, 0644);
16608                        Os.chmod(file.getAbsolutePath(), 0644);
16609                        return new ParcelFileDescriptor(fd);
16610                    } catch (ErrnoException e) {
16611                        throw new RemoteException("Failed to open: " + e.getMessage());
16612                    }
16613                }
16614            };
16615
16616            int ret = PackageManager.INSTALL_SUCCEEDED;
16617            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16618            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16619                Slog.e(TAG, "Failed to copy package");
16620                return ret;
16621            }
16622
16623            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16624            NativeLibraryHelper.Handle handle = null;
16625            try {
16626                handle = NativeLibraryHelper.Handle.create(codeFile);
16627                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16628                        abiOverride);
16629            } catch (IOException e) {
16630                Slog.e(TAG, "Copying native libraries failed", e);
16631                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16632            } finally {
16633                IoUtils.closeQuietly(handle);
16634            }
16635
16636            return ret;
16637        }
16638
16639        int doPreInstall(int status) {
16640            if (status != PackageManager.INSTALL_SUCCEEDED) {
16641                cleanUp();
16642            }
16643            return status;
16644        }
16645
16646        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16647            if (status != PackageManager.INSTALL_SUCCEEDED) {
16648                cleanUp();
16649                return false;
16650            }
16651
16652            final File targetDir = codeFile.getParentFile();
16653            final File beforeCodeFile = codeFile;
16654            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16655
16656            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16657            try {
16658                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16659            } catch (ErrnoException e) {
16660                Slog.w(TAG, "Failed to rename", e);
16661                return false;
16662            }
16663
16664            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16665                Slog.w(TAG, "Failed to restorecon");
16666                return false;
16667            }
16668
16669            // Reflect the rename internally
16670            codeFile = afterCodeFile;
16671            resourceFile = afterCodeFile;
16672
16673            // Reflect the rename in scanned details
16674            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16675            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16676                    afterCodeFile, pkg.baseCodePath));
16677            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16678                    afterCodeFile, pkg.splitCodePaths));
16679
16680            // Reflect the rename in app info
16681            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16682            pkg.setApplicationInfoCodePath(pkg.codePath);
16683            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16684            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16685            pkg.setApplicationInfoResourcePath(pkg.codePath);
16686            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16687            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16688
16689            return true;
16690        }
16691
16692        int doPostInstall(int status, int uid) {
16693            if (status != PackageManager.INSTALL_SUCCEEDED) {
16694                cleanUp();
16695            }
16696            return status;
16697        }
16698
16699        @Override
16700        String getCodePath() {
16701            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16702        }
16703
16704        @Override
16705        String getResourcePath() {
16706            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16707        }
16708
16709        private boolean cleanUp() {
16710            if (codeFile == null || !codeFile.exists()) {
16711                return false;
16712            }
16713
16714            removeCodePathLI(codeFile);
16715
16716            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16717                resourceFile.delete();
16718            }
16719
16720            return true;
16721        }
16722
16723        void cleanUpResourcesLI() {
16724            // Try enumerating all code paths before deleting
16725            List<String> allCodePaths = Collections.EMPTY_LIST;
16726            if (codeFile != null && codeFile.exists()) {
16727                try {
16728                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16729                    allCodePaths = pkg.getAllCodePaths();
16730                } catch (PackageParserException e) {
16731                    // Ignored; we tried our best
16732                }
16733            }
16734
16735            cleanUp();
16736            removeDexFiles(allCodePaths, instructionSets);
16737        }
16738
16739        boolean doPostDeleteLI(boolean delete) {
16740            // XXX err, shouldn't we respect the delete flag?
16741            cleanUpResourcesLI();
16742            return true;
16743        }
16744    }
16745
16746    private boolean isAsecExternal(String cid) {
16747        final String asecPath = PackageHelper.getSdFilesystem(cid);
16748        return !asecPath.startsWith(mAsecInternalPath);
16749    }
16750
16751    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16752            PackageManagerException {
16753        if (copyRet < 0) {
16754            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16755                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16756                throw new PackageManagerException(copyRet, message);
16757            }
16758        }
16759    }
16760
16761    /**
16762     * Extract the StorageManagerService "container ID" from the full code path of an
16763     * .apk.
16764     */
16765    static String cidFromCodePath(String fullCodePath) {
16766        int eidx = fullCodePath.lastIndexOf("/");
16767        String subStr1 = fullCodePath.substring(0, eidx);
16768        int sidx = subStr1.lastIndexOf("/");
16769        return subStr1.substring(sidx+1, eidx);
16770    }
16771
16772    /**
16773     * Logic to handle installation of ASEC applications, including copying and
16774     * renaming logic.
16775     */
16776    class AsecInstallArgs extends InstallArgs {
16777        static final String RES_FILE_NAME = "pkg.apk";
16778        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16779
16780        String cid;
16781        String packagePath;
16782        String resourcePath;
16783
16784        /** New install */
16785        AsecInstallArgs(InstallParams params) {
16786            super(params.origin, params.move, params.observer, params.installFlags,
16787                    params.installerPackageName, params.volumeUuid,
16788                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16789                    params.grantedRuntimePermissions,
16790                    params.traceMethod, params.traceCookie, params.certificates,
16791                    params.installReason);
16792        }
16793
16794        /** Existing install */
16795        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16796                        boolean isExternal, boolean isForwardLocked) {
16797            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16798                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16799                    instructionSets, null, null, null, 0, null /*certificates*/,
16800                    PackageManager.INSTALL_REASON_UNKNOWN);
16801            // Hackily pretend we're still looking at a full code path
16802            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16803                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16804            }
16805
16806            // Extract cid from fullCodePath
16807            int eidx = fullCodePath.lastIndexOf("/");
16808            String subStr1 = fullCodePath.substring(0, eidx);
16809            int sidx = subStr1.lastIndexOf("/");
16810            cid = subStr1.substring(sidx+1, eidx);
16811            setMountPath(subStr1);
16812        }
16813
16814        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16815            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16816                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16817                    instructionSets, null, null, null, 0, null /*certificates*/,
16818                    PackageManager.INSTALL_REASON_UNKNOWN);
16819            this.cid = cid;
16820            setMountPath(PackageHelper.getSdDir(cid));
16821        }
16822
16823        void createCopyFile() {
16824            cid = mInstallerService.allocateExternalStageCidLegacy();
16825        }
16826
16827        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16828            if (origin.staged && origin.cid != null) {
16829                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16830                cid = origin.cid;
16831                setMountPath(PackageHelper.getSdDir(cid));
16832                return PackageManager.INSTALL_SUCCEEDED;
16833            }
16834
16835            if (temp) {
16836                createCopyFile();
16837            } else {
16838                /*
16839                 * Pre-emptively destroy the container since it's destroyed if
16840                 * copying fails due to it existing anyway.
16841                 */
16842                PackageHelper.destroySdDir(cid);
16843            }
16844
16845            final String newMountPath = imcs.copyPackageToContainer(
16846                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16847                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16848
16849            if (newMountPath != null) {
16850                setMountPath(newMountPath);
16851                return PackageManager.INSTALL_SUCCEEDED;
16852            } else {
16853                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16854            }
16855        }
16856
16857        @Override
16858        String getCodePath() {
16859            return packagePath;
16860        }
16861
16862        @Override
16863        String getResourcePath() {
16864            return resourcePath;
16865        }
16866
16867        int doPreInstall(int status) {
16868            if (status != PackageManager.INSTALL_SUCCEEDED) {
16869                // Destroy container
16870                PackageHelper.destroySdDir(cid);
16871            } else {
16872                boolean mounted = PackageHelper.isContainerMounted(cid);
16873                if (!mounted) {
16874                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16875                            Process.SYSTEM_UID);
16876                    if (newMountPath != null) {
16877                        setMountPath(newMountPath);
16878                    } else {
16879                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16880                    }
16881                }
16882            }
16883            return status;
16884        }
16885
16886        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16887            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16888            String newMountPath = null;
16889            if (PackageHelper.isContainerMounted(cid)) {
16890                // Unmount the container
16891                if (!PackageHelper.unMountSdDir(cid)) {
16892                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16893                    return false;
16894                }
16895            }
16896            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16897                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16898                        " which might be stale. Will try to clean up.");
16899                // Clean up the stale container and proceed to recreate.
16900                if (!PackageHelper.destroySdDir(newCacheId)) {
16901                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16902                    return false;
16903                }
16904                // Successfully cleaned up stale container. Try to rename again.
16905                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16906                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16907                            + " inspite of cleaning it up.");
16908                    return false;
16909                }
16910            }
16911            if (!PackageHelper.isContainerMounted(newCacheId)) {
16912                Slog.w(TAG, "Mounting container " + newCacheId);
16913                newMountPath = PackageHelper.mountSdDir(newCacheId,
16914                        getEncryptKey(), Process.SYSTEM_UID);
16915            } else {
16916                newMountPath = PackageHelper.getSdDir(newCacheId);
16917            }
16918            if (newMountPath == null) {
16919                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16920                return false;
16921            }
16922            Log.i(TAG, "Succesfully renamed " + cid +
16923                    " to " + newCacheId +
16924                    " at new path: " + newMountPath);
16925            cid = newCacheId;
16926
16927            final File beforeCodeFile = new File(packagePath);
16928            setMountPath(newMountPath);
16929            final File afterCodeFile = new File(packagePath);
16930
16931            // Reflect the rename in scanned details
16932            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16933            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16934                    afterCodeFile, pkg.baseCodePath));
16935            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16936                    afterCodeFile, pkg.splitCodePaths));
16937
16938            // Reflect the rename in app info
16939            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16940            pkg.setApplicationInfoCodePath(pkg.codePath);
16941            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16942            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16943            pkg.setApplicationInfoResourcePath(pkg.codePath);
16944            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16945            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16946
16947            return true;
16948        }
16949
16950        private void setMountPath(String mountPath) {
16951            final File mountFile = new File(mountPath);
16952
16953            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16954            if (monolithicFile.exists()) {
16955                packagePath = monolithicFile.getAbsolutePath();
16956                if (isFwdLocked()) {
16957                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16958                } else {
16959                    resourcePath = packagePath;
16960                }
16961            } else {
16962                packagePath = mountFile.getAbsolutePath();
16963                resourcePath = packagePath;
16964            }
16965        }
16966
16967        int doPostInstall(int status, int uid) {
16968            if (status != PackageManager.INSTALL_SUCCEEDED) {
16969                cleanUp();
16970            } else {
16971                final int groupOwner;
16972                final String protectedFile;
16973                if (isFwdLocked()) {
16974                    groupOwner = UserHandle.getSharedAppGid(uid);
16975                    protectedFile = RES_FILE_NAME;
16976                } else {
16977                    groupOwner = -1;
16978                    protectedFile = null;
16979                }
16980
16981                if (uid < Process.FIRST_APPLICATION_UID
16982                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16983                    Slog.e(TAG, "Failed to finalize " + cid);
16984                    PackageHelper.destroySdDir(cid);
16985                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16986                }
16987
16988                boolean mounted = PackageHelper.isContainerMounted(cid);
16989                if (!mounted) {
16990                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16991                }
16992            }
16993            return status;
16994        }
16995
16996        private void cleanUp() {
16997            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16998
16999            // Destroy secure container
17000            PackageHelper.destroySdDir(cid);
17001        }
17002
17003        private List<String> getAllCodePaths() {
17004            final File codeFile = new File(getCodePath());
17005            if (codeFile != null && codeFile.exists()) {
17006                try {
17007                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17008                    return pkg.getAllCodePaths();
17009                } catch (PackageParserException e) {
17010                    // Ignored; we tried our best
17011                }
17012            }
17013            return Collections.EMPTY_LIST;
17014        }
17015
17016        void cleanUpResourcesLI() {
17017            // Enumerate all code paths before deleting
17018            cleanUpResourcesLI(getAllCodePaths());
17019        }
17020
17021        private void cleanUpResourcesLI(List<String> allCodePaths) {
17022            cleanUp();
17023            removeDexFiles(allCodePaths, instructionSets);
17024        }
17025
17026        String getPackageName() {
17027            return getAsecPackageName(cid);
17028        }
17029
17030        boolean doPostDeleteLI(boolean delete) {
17031            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17032            final List<String> allCodePaths = getAllCodePaths();
17033            boolean mounted = PackageHelper.isContainerMounted(cid);
17034            if (mounted) {
17035                // Unmount first
17036                if (PackageHelper.unMountSdDir(cid)) {
17037                    mounted = false;
17038                }
17039            }
17040            if (!mounted && delete) {
17041                cleanUpResourcesLI(allCodePaths);
17042            }
17043            return !mounted;
17044        }
17045
17046        @Override
17047        int doPreCopy() {
17048            if (isFwdLocked()) {
17049                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17050                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17051                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17052                }
17053            }
17054
17055            return PackageManager.INSTALL_SUCCEEDED;
17056        }
17057
17058        @Override
17059        int doPostCopy(int uid) {
17060            if (isFwdLocked()) {
17061                if (uid < Process.FIRST_APPLICATION_UID
17062                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17063                                RES_FILE_NAME)) {
17064                    Slog.e(TAG, "Failed to finalize " + cid);
17065                    PackageHelper.destroySdDir(cid);
17066                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17067                }
17068            }
17069
17070            return PackageManager.INSTALL_SUCCEEDED;
17071        }
17072    }
17073
17074    /**
17075     * Logic to handle movement of existing installed applications.
17076     */
17077    class MoveInstallArgs extends InstallArgs {
17078        private File codeFile;
17079        private File resourceFile;
17080
17081        /** New install */
17082        MoveInstallArgs(InstallParams params) {
17083            super(params.origin, params.move, params.observer, params.installFlags,
17084                    params.installerPackageName, params.volumeUuid,
17085                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17086                    params.grantedRuntimePermissions,
17087                    params.traceMethod, params.traceCookie, params.certificates,
17088                    params.installReason);
17089        }
17090
17091        int copyApk(IMediaContainerService imcs, boolean temp) {
17092            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17093                    + move.fromUuid + " to " + move.toUuid);
17094            synchronized (mInstaller) {
17095                try {
17096                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17097                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17098                } catch (InstallerException e) {
17099                    Slog.w(TAG, "Failed to move app", e);
17100                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17101                }
17102            }
17103
17104            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17105            resourceFile = codeFile;
17106            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17107
17108            return PackageManager.INSTALL_SUCCEEDED;
17109        }
17110
17111        int doPreInstall(int status) {
17112            if (status != PackageManager.INSTALL_SUCCEEDED) {
17113                cleanUp(move.toUuid);
17114            }
17115            return status;
17116        }
17117
17118        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17119            if (status != PackageManager.INSTALL_SUCCEEDED) {
17120                cleanUp(move.toUuid);
17121                return false;
17122            }
17123
17124            // Reflect the move in app info
17125            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17126            pkg.setApplicationInfoCodePath(pkg.codePath);
17127            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17128            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17129            pkg.setApplicationInfoResourcePath(pkg.codePath);
17130            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17131            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17132
17133            return true;
17134        }
17135
17136        int doPostInstall(int status, int uid) {
17137            if (status == PackageManager.INSTALL_SUCCEEDED) {
17138                cleanUp(move.fromUuid);
17139            } else {
17140                cleanUp(move.toUuid);
17141            }
17142            return status;
17143        }
17144
17145        @Override
17146        String getCodePath() {
17147            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17148        }
17149
17150        @Override
17151        String getResourcePath() {
17152            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17153        }
17154
17155        private boolean cleanUp(String volumeUuid) {
17156            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17157                    move.dataAppName);
17158            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17159            final int[] userIds = sUserManager.getUserIds();
17160            synchronized (mInstallLock) {
17161                // Clean up both app data and code
17162                // All package moves are frozen until finished
17163                for (int userId : userIds) {
17164                    try {
17165                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17166                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17167                    } catch (InstallerException e) {
17168                        Slog.w(TAG, String.valueOf(e));
17169                    }
17170                }
17171                removeCodePathLI(codeFile);
17172            }
17173            return true;
17174        }
17175
17176        void cleanUpResourcesLI() {
17177            throw new UnsupportedOperationException();
17178        }
17179
17180        boolean doPostDeleteLI(boolean delete) {
17181            throw new UnsupportedOperationException();
17182        }
17183    }
17184
17185    static String getAsecPackageName(String packageCid) {
17186        int idx = packageCid.lastIndexOf("-");
17187        if (idx == -1) {
17188            return packageCid;
17189        }
17190        return packageCid.substring(0, idx);
17191    }
17192
17193    // Utility method used to create code paths based on package name and available index.
17194    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17195        String idxStr = "";
17196        int idx = 1;
17197        // Fall back to default value of idx=1 if prefix is not
17198        // part of oldCodePath
17199        if (oldCodePath != null) {
17200            String subStr = oldCodePath;
17201            // Drop the suffix right away
17202            if (suffix != null && subStr.endsWith(suffix)) {
17203                subStr = subStr.substring(0, subStr.length() - suffix.length());
17204            }
17205            // If oldCodePath already contains prefix find out the
17206            // ending index to either increment or decrement.
17207            int sidx = subStr.lastIndexOf(prefix);
17208            if (sidx != -1) {
17209                subStr = subStr.substring(sidx + prefix.length());
17210                if (subStr != null) {
17211                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17212                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17213                    }
17214                    try {
17215                        idx = Integer.parseInt(subStr);
17216                        if (idx <= 1) {
17217                            idx++;
17218                        } else {
17219                            idx--;
17220                        }
17221                    } catch(NumberFormatException e) {
17222                    }
17223                }
17224            }
17225        }
17226        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17227        return prefix + idxStr;
17228    }
17229
17230    private File getNextCodePath(File targetDir, String packageName) {
17231        File result;
17232        SecureRandom random = new SecureRandom();
17233        byte[] bytes = new byte[16];
17234        do {
17235            random.nextBytes(bytes);
17236            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17237            result = new File(targetDir, packageName + "-" + suffix);
17238        } while (result.exists());
17239        return result;
17240    }
17241
17242    // Utility method that returns the relative package path with respect
17243    // to the installation directory. Like say for /data/data/com.test-1.apk
17244    // string com.test-1 is returned.
17245    static String deriveCodePathName(String codePath) {
17246        if (codePath == null) {
17247            return null;
17248        }
17249        final File codeFile = new File(codePath);
17250        final String name = codeFile.getName();
17251        if (codeFile.isDirectory()) {
17252            return name;
17253        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17254            final int lastDot = name.lastIndexOf('.');
17255            return name.substring(0, lastDot);
17256        } else {
17257            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17258            return null;
17259        }
17260    }
17261
17262    static class PackageInstalledInfo {
17263        String name;
17264        int uid;
17265        // The set of users that originally had this package installed.
17266        int[] origUsers;
17267        // The set of users that now have this package installed.
17268        int[] newUsers;
17269        PackageParser.Package pkg;
17270        int returnCode;
17271        String returnMsg;
17272        PackageRemovedInfo removedInfo;
17273        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17274
17275        public void setError(int code, String msg) {
17276            setReturnCode(code);
17277            setReturnMessage(msg);
17278            Slog.w(TAG, msg);
17279        }
17280
17281        public void setError(String msg, PackageParserException e) {
17282            setReturnCode(e.error);
17283            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17284            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17285            for (int i = 0; i < childCount; i++) {
17286                addedChildPackages.valueAt(i).setError(msg, e);
17287            }
17288            Slog.w(TAG, msg, e);
17289        }
17290
17291        public void setError(String msg, PackageManagerException e) {
17292            returnCode = e.error;
17293            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17294            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17295            for (int i = 0; i < childCount; i++) {
17296                addedChildPackages.valueAt(i).setError(msg, e);
17297            }
17298            Slog.w(TAG, msg, e);
17299        }
17300
17301        public void setReturnCode(int returnCode) {
17302            this.returnCode = returnCode;
17303            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17304            for (int i = 0; i < childCount; i++) {
17305                addedChildPackages.valueAt(i).returnCode = returnCode;
17306            }
17307        }
17308
17309        private void setReturnMessage(String returnMsg) {
17310            this.returnMsg = returnMsg;
17311            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17312            for (int i = 0; i < childCount; i++) {
17313                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17314            }
17315        }
17316
17317        // In some error cases we want to convey more info back to the observer
17318        String origPackage;
17319        String origPermission;
17320    }
17321
17322    /*
17323     * Install a non-existing package.
17324     */
17325    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17326            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17327            PackageInstalledInfo res, int installReason) {
17328        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17329
17330        // Remember this for later, in case we need to rollback this install
17331        String pkgName = pkg.packageName;
17332
17333        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17334
17335        synchronized(mPackages) {
17336            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17337            if (renamedPackage != null) {
17338                // A package with the same name is already installed, though
17339                // it has been renamed to an older name.  The package we
17340                // are trying to install should be installed as an update to
17341                // the existing one, but that has not been requested, so bail.
17342                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17343                        + " without first uninstalling package running as "
17344                        + renamedPackage);
17345                return;
17346            }
17347            if (mPackages.containsKey(pkgName)) {
17348                // Don't allow installation over an existing package with the same name.
17349                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17350                        + " without first uninstalling.");
17351                return;
17352            }
17353        }
17354
17355        try {
17356            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17357                    System.currentTimeMillis(), user);
17358
17359            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17360
17361            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17362                prepareAppDataAfterInstallLIF(newPackage);
17363
17364            } else {
17365                // Remove package from internal structures, but keep around any
17366                // data that might have already existed
17367                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17368                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17369            }
17370        } catch (PackageManagerException e) {
17371            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17372        }
17373
17374        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17375    }
17376
17377    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17378        // Can't rotate keys during boot or if sharedUser.
17379        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17380                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17381            return false;
17382        }
17383        // app is using upgradeKeySets; make sure all are valid
17384        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17385        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17386        for (int i = 0; i < upgradeKeySets.length; i++) {
17387            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17388                Slog.wtf(TAG, "Package "
17389                         + (oldPs.name != null ? oldPs.name : "<null>")
17390                         + " contains upgrade-key-set reference to unknown key-set: "
17391                         + upgradeKeySets[i]
17392                         + " reverting to signatures check.");
17393                return false;
17394            }
17395        }
17396        return true;
17397    }
17398
17399    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17400        // Upgrade keysets are being used.  Determine if new package has a superset of the
17401        // required keys.
17402        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17403        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17404        for (int i = 0; i < upgradeKeySets.length; i++) {
17405            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17406            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17407                return true;
17408            }
17409        }
17410        return false;
17411    }
17412
17413    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17414        try (DigestInputStream digestStream =
17415                new DigestInputStream(new FileInputStream(file), digest)) {
17416            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17417        }
17418    }
17419
17420    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17421            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17422            int installReason) {
17423        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17424
17425        final PackageParser.Package oldPackage;
17426        final PackageSetting ps;
17427        final String pkgName = pkg.packageName;
17428        final int[] allUsers;
17429        final int[] installedUsers;
17430
17431        synchronized(mPackages) {
17432            oldPackage = mPackages.get(pkgName);
17433            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17434
17435            // don't allow upgrade to target a release SDK from a pre-release SDK
17436            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17437                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17438            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17439                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17440            if (oldTargetsPreRelease
17441                    && !newTargetsPreRelease
17442                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17443                Slog.w(TAG, "Can't install package targeting released sdk");
17444                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17445                return;
17446            }
17447
17448            ps = mSettings.mPackages.get(pkgName);
17449
17450            // verify signatures are valid
17451            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17452                if (!checkUpgradeKeySetLP(ps, pkg)) {
17453                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17454                            "New package not signed by keys specified by upgrade-keysets: "
17455                                    + pkgName);
17456                    return;
17457                }
17458            } else {
17459                // default to original signature matching
17460                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17461                        != PackageManager.SIGNATURE_MATCH) {
17462                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17463                            "New package has a different signature: " + pkgName);
17464                    return;
17465                }
17466            }
17467
17468            // don't allow a system upgrade unless the upgrade hash matches
17469            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17470                byte[] digestBytes = null;
17471                try {
17472                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17473                    updateDigest(digest, new File(pkg.baseCodePath));
17474                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17475                        for (String path : pkg.splitCodePaths) {
17476                            updateDigest(digest, new File(path));
17477                        }
17478                    }
17479                    digestBytes = digest.digest();
17480                } catch (NoSuchAlgorithmException | IOException e) {
17481                    res.setError(INSTALL_FAILED_INVALID_APK,
17482                            "Could not compute hash: " + pkgName);
17483                    return;
17484                }
17485                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17486                    res.setError(INSTALL_FAILED_INVALID_APK,
17487                            "New package fails restrict-update check: " + pkgName);
17488                    return;
17489                }
17490                // retain upgrade restriction
17491                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17492            }
17493
17494            // Check for shared user id changes
17495            String invalidPackageName =
17496                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17497            if (invalidPackageName != null) {
17498                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17499                        "Package " + invalidPackageName + " tried to change user "
17500                                + oldPackage.mSharedUserId);
17501                return;
17502            }
17503
17504            // In case of rollback, remember per-user/profile install state
17505            allUsers = sUserManager.getUserIds();
17506            installedUsers = ps.queryInstalledUsers(allUsers, true);
17507
17508            // don't allow an upgrade from full to ephemeral
17509            if (isInstantApp) {
17510                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17511                    for (int currentUser : allUsers) {
17512                        if (!ps.getInstantApp(currentUser)) {
17513                            // can't downgrade from full to instant
17514                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17515                                    + " for user: " + currentUser);
17516                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17517                            return;
17518                        }
17519                    }
17520                } else if (!ps.getInstantApp(user.getIdentifier())) {
17521                    // can't downgrade from full to instant
17522                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17523                            + " for user: " + user.getIdentifier());
17524                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17525                    return;
17526                }
17527            }
17528        }
17529
17530        // Update what is removed
17531        res.removedInfo = new PackageRemovedInfo(this);
17532        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17533        res.removedInfo.removedPackage = oldPackage.packageName;
17534        res.removedInfo.installerPackageName = ps.installerPackageName;
17535        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17536        res.removedInfo.isUpdate = true;
17537        res.removedInfo.origUsers = installedUsers;
17538        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17539        for (int i = 0; i < installedUsers.length; i++) {
17540            final int userId = installedUsers[i];
17541            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17542        }
17543
17544        final int childCount = (oldPackage.childPackages != null)
17545                ? oldPackage.childPackages.size() : 0;
17546        for (int i = 0; i < childCount; i++) {
17547            boolean childPackageUpdated = false;
17548            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17549            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17550            if (res.addedChildPackages != null) {
17551                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17552                if (childRes != null) {
17553                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17554                    childRes.removedInfo.removedPackage = childPkg.packageName;
17555                    if (childPs != null) {
17556                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17557                    }
17558                    childRes.removedInfo.isUpdate = true;
17559                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17560                    childPackageUpdated = true;
17561                }
17562            }
17563            if (!childPackageUpdated) {
17564                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17565                childRemovedRes.removedPackage = childPkg.packageName;
17566                if (childPs != null) {
17567                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17568                }
17569                childRemovedRes.isUpdate = false;
17570                childRemovedRes.dataRemoved = true;
17571                synchronized (mPackages) {
17572                    if (childPs != null) {
17573                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17574                    }
17575                }
17576                if (res.removedInfo.removedChildPackages == null) {
17577                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17578                }
17579                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17580            }
17581        }
17582
17583        boolean sysPkg = (isSystemApp(oldPackage));
17584        if (sysPkg) {
17585            // Set the system/privileged flags as needed
17586            final boolean privileged =
17587                    (oldPackage.applicationInfo.privateFlags
17588                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17589            final int systemPolicyFlags = policyFlags
17590                    | PackageParser.PARSE_IS_SYSTEM
17591                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17592
17593            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17594                    user, allUsers, installerPackageName, res, installReason);
17595        } else {
17596            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17597                    user, allUsers, installerPackageName, res, installReason);
17598        }
17599    }
17600
17601    @Override
17602    public List<String> getPreviousCodePaths(String packageName) {
17603        final int callingUid = Binder.getCallingUid();
17604        final List<String> result = new ArrayList<>();
17605        if (getInstantAppPackageName(callingUid) != null) {
17606            return result;
17607        }
17608        final PackageSetting ps = mSettings.mPackages.get(packageName);
17609        if (ps != null
17610                && ps.oldCodePaths != null
17611                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17612            result.addAll(ps.oldCodePaths);
17613        }
17614        return result;
17615    }
17616
17617    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17618            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17619            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17620            int installReason) {
17621        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17622                + deletedPackage);
17623
17624        String pkgName = deletedPackage.packageName;
17625        boolean deletedPkg = true;
17626        boolean addedPkg = false;
17627        boolean updatedSettings = false;
17628        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17629        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17630                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17631
17632        final long origUpdateTime = (pkg.mExtras != null)
17633                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17634
17635        // First delete the existing package while retaining the data directory
17636        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17637                res.removedInfo, true, pkg)) {
17638            // If the existing package wasn't successfully deleted
17639            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17640            deletedPkg = false;
17641        } else {
17642            // Successfully deleted the old package; proceed with replace.
17643
17644            // If deleted package lived in a container, give users a chance to
17645            // relinquish resources before killing.
17646            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17647                if (DEBUG_INSTALL) {
17648                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17649                }
17650                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17651                final ArrayList<String> pkgList = new ArrayList<String>(1);
17652                pkgList.add(deletedPackage.applicationInfo.packageName);
17653                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17654            }
17655
17656            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17657                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17658            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17659
17660            try {
17661                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17662                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17663                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17664                        installReason);
17665
17666                // Update the in-memory copy of the previous code paths.
17667                PackageSetting ps = mSettings.mPackages.get(pkgName);
17668                if (!killApp) {
17669                    if (ps.oldCodePaths == null) {
17670                        ps.oldCodePaths = new ArraySet<>();
17671                    }
17672                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17673                    if (deletedPackage.splitCodePaths != null) {
17674                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17675                    }
17676                } else {
17677                    ps.oldCodePaths = null;
17678                }
17679                if (ps.childPackageNames != null) {
17680                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17681                        final String childPkgName = ps.childPackageNames.get(i);
17682                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17683                        childPs.oldCodePaths = ps.oldCodePaths;
17684                    }
17685                }
17686                // set instant app status, but, only if it's explicitly specified
17687                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17688                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17689                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17690                prepareAppDataAfterInstallLIF(newPackage);
17691                addedPkg = true;
17692                mDexManager.notifyPackageUpdated(newPackage.packageName,
17693                        newPackage.baseCodePath, newPackage.splitCodePaths);
17694            } catch (PackageManagerException e) {
17695                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17696            }
17697        }
17698
17699        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17700            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17701
17702            // Revert all internal state mutations and added folders for the failed install
17703            if (addedPkg) {
17704                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17705                        res.removedInfo, true, null);
17706            }
17707
17708            // Restore the old package
17709            if (deletedPkg) {
17710                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17711                File restoreFile = new File(deletedPackage.codePath);
17712                // Parse old package
17713                boolean oldExternal = isExternal(deletedPackage);
17714                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17715                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17716                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17717                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17718                try {
17719                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17720                            null);
17721                } catch (PackageManagerException e) {
17722                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17723                            + e.getMessage());
17724                    return;
17725                }
17726
17727                synchronized (mPackages) {
17728                    // Ensure the installer package name up to date
17729                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17730
17731                    // Update permissions for restored package
17732                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17733
17734                    mSettings.writeLPr();
17735                }
17736
17737                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17738            }
17739        } else {
17740            synchronized (mPackages) {
17741                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17742                if (ps != null) {
17743                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17744                    if (res.removedInfo.removedChildPackages != null) {
17745                        final int childCount = res.removedInfo.removedChildPackages.size();
17746                        // Iterate in reverse as we may modify the collection
17747                        for (int i = childCount - 1; i >= 0; i--) {
17748                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17749                            if (res.addedChildPackages.containsKey(childPackageName)) {
17750                                res.removedInfo.removedChildPackages.removeAt(i);
17751                            } else {
17752                                PackageRemovedInfo childInfo = res.removedInfo
17753                                        .removedChildPackages.valueAt(i);
17754                                childInfo.removedForAllUsers = mPackages.get(
17755                                        childInfo.removedPackage) == null;
17756                            }
17757                        }
17758                    }
17759                }
17760            }
17761        }
17762    }
17763
17764    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17765            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17766            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17767            int installReason) {
17768        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17769                + ", old=" + deletedPackage);
17770
17771        final boolean disabledSystem;
17772
17773        // Remove existing system package
17774        removePackageLI(deletedPackage, true);
17775
17776        synchronized (mPackages) {
17777            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17778        }
17779        if (!disabledSystem) {
17780            // We didn't need to disable the .apk as a current system package,
17781            // which means we are replacing another update that is already
17782            // installed.  We need to make sure to delete the older one's .apk.
17783            res.removedInfo.args = createInstallArgsForExisting(0,
17784                    deletedPackage.applicationInfo.getCodePath(),
17785                    deletedPackage.applicationInfo.getResourcePath(),
17786                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17787        } else {
17788            res.removedInfo.args = null;
17789        }
17790
17791        // Successfully disabled the old package. Now proceed with re-installation
17792        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17793                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17794        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17795
17796        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17797        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17798                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17799
17800        PackageParser.Package newPackage = null;
17801        try {
17802            // Add the package to the internal data structures
17803            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17804
17805            // Set the update and install times
17806            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17807            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17808                    System.currentTimeMillis());
17809
17810            // Update the package dynamic state if succeeded
17811            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17812                // Now that the install succeeded make sure we remove data
17813                // directories for any child package the update removed.
17814                final int deletedChildCount = (deletedPackage.childPackages != null)
17815                        ? deletedPackage.childPackages.size() : 0;
17816                final int newChildCount = (newPackage.childPackages != null)
17817                        ? newPackage.childPackages.size() : 0;
17818                for (int i = 0; i < deletedChildCount; i++) {
17819                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17820                    boolean childPackageDeleted = true;
17821                    for (int j = 0; j < newChildCount; j++) {
17822                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17823                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17824                            childPackageDeleted = false;
17825                            break;
17826                        }
17827                    }
17828                    if (childPackageDeleted) {
17829                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17830                                deletedChildPkg.packageName);
17831                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17832                            PackageRemovedInfo removedChildRes = res.removedInfo
17833                                    .removedChildPackages.get(deletedChildPkg.packageName);
17834                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17835                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17836                        }
17837                    }
17838                }
17839
17840                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17841                        installReason);
17842                prepareAppDataAfterInstallLIF(newPackage);
17843
17844                mDexManager.notifyPackageUpdated(newPackage.packageName,
17845                            newPackage.baseCodePath, newPackage.splitCodePaths);
17846            }
17847        } catch (PackageManagerException e) {
17848            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17849            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17850        }
17851
17852        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17853            // Re installation failed. Restore old information
17854            // Remove new pkg information
17855            if (newPackage != null) {
17856                removeInstalledPackageLI(newPackage, true);
17857            }
17858            // Add back the old system package
17859            try {
17860                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17861            } catch (PackageManagerException e) {
17862                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17863            }
17864
17865            synchronized (mPackages) {
17866                if (disabledSystem) {
17867                    enableSystemPackageLPw(deletedPackage);
17868                }
17869
17870                // Ensure the installer package name up to date
17871                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17872
17873                // Update permissions for restored package
17874                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17875
17876                mSettings.writeLPr();
17877            }
17878
17879            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17880                    + " after failed upgrade");
17881        }
17882    }
17883
17884    /**
17885     * Checks whether the parent or any of the child packages have a change shared
17886     * user. For a package to be a valid update the shred users of the parent and
17887     * the children should match. We may later support changing child shared users.
17888     * @param oldPkg The updated package.
17889     * @param newPkg The update package.
17890     * @return The shared user that change between the versions.
17891     */
17892    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17893            PackageParser.Package newPkg) {
17894        // Check parent shared user
17895        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17896            return newPkg.packageName;
17897        }
17898        // Check child shared users
17899        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17900        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17901        for (int i = 0; i < newChildCount; i++) {
17902            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17903            // If this child was present, did it have the same shared user?
17904            for (int j = 0; j < oldChildCount; j++) {
17905                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17906                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17907                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17908                    return newChildPkg.packageName;
17909                }
17910            }
17911        }
17912        return null;
17913    }
17914
17915    private void removeNativeBinariesLI(PackageSetting ps) {
17916        // Remove the lib path for the parent package
17917        if (ps != null) {
17918            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17919            // Remove the lib path for the child packages
17920            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17921            for (int i = 0; i < childCount; i++) {
17922                PackageSetting childPs = null;
17923                synchronized (mPackages) {
17924                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17925                }
17926                if (childPs != null) {
17927                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17928                            .legacyNativeLibraryPathString);
17929                }
17930            }
17931        }
17932    }
17933
17934    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17935        // Enable the parent package
17936        mSettings.enableSystemPackageLPw(pkg.packageName);
17937        // Enable the child packages
17938        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17939        for (int i = 0; i < childCount; i++) {
17940            PackageParser.Package childPkg = pkg.childPackages.get(i);
17941            mSettings.enableSystemPackageLPw(childPkg.packageName);
17942        }
17943    }
17944
17945    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17946            PackageParser.Package newPkg) {
17947        // Disable the parent package (parent always replaced)
17948        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17949        // Disable the child packages
17950        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17951        for (int i = 0; i < childCount; i++) {
17952            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17953            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17954            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17955        }
17956        return disabled;
17957    }
17958
17959    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17960            String installerPackageName) {
17961        // Enable the parent package
17962        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17963        // Enable the child packages
17964        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17965        for (int i = 0; i < childCount; i++) {
17966            PackageParser.Package childPkg = pkg.childPackages.get(i);
17967            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17968        }
17969    }
17970
17971    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17972        // Collect all used permissions in the UID
17973        ArraySet<String> usedPermissions = new ArraySet<>();
17974        final int packageCount = su.packages.size();
17975        for (int i = 0; i < packageCount; i++) {
17976            PackageSetting ps = su.packages.valueAt(i);
17977            if (ps.pkg == null) {
17978                continue;
17979            }
17980            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17981            for (int j = 0; j < requestedPermCount; j++) {
17982                String permission = ps.pkg.requestedPermissions.get(j);
17983                BasePermission bp = mSettings.mPermissions.get(permission);
17984                if (bp != null) {
17985                    usedPermissions.add(permission);
17986                }
17987            }
17988        }
17989
17990        PermissionsState permissionsState = su.getPermissionsState();
17991        // Prune install permissions
17992        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17993        final int installPermCount = installPermStates.size();
17994        for (int i = installPermCount - 1; i >= 0;  i--) {
17995            PermissionState permissionState = installPermStates.get(i);
17996            if (!usedPermissions.contains(permissionState.getName())) {
17997                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17998                if (bp != null) {
17999                    permissionsState.revokeInstallPermission(bp);
18000                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18001                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18002                }
18003            }
18004        }
18005
18006        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18007
18008        // Prune runtime permissions
18009        for (int userId : allUserIds) {
18010            List<PermissionState> runtimePermStates = permissionsState
18011                    .getRuntimePermissionStates(userId);
18012            final int runtimePermCount = runtimePermStates.size();
18013            for (int i = runtimePermCount - 1; i >= 0; i--) {
18014                PermissionState permissionState = runtimePermStates.get(i);
18015                if (!usedPermissions.contains(permissionState.getName())) {
18016                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18017                    if (bp != null) {
18018                        permissionsState.revokeRuntimePermission(bp, userId);
18019                        permissionsState.updatePermissionFlags(bp, userId,
18020                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18021                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18022                                runtimePermissionChangedUserIds, userId);
18023                    }
18024                }
18025            }
18026        }
18027
18028        return runtimePermissionChangedUserIds;
18029    }
18030
18031    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18032            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18033        // Update the parent package setting
18034        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18035                res, user, installReason);
18036        // Update the child packages setting
18037        final int childCount = (newPackage.childPackages != null)
18038                ? newPackage.childPackages.size() : 0;
18039        for (int i = 0; i < childCount; i++) {
18040            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18041            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18042            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18043                    childRes.origUsers, childRes, user, installReason);
18044        }
18045    }
18046
18047    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18048            String installerPackageName, int[] allUsers, int[] installedForUsers,
18049            PackageInstalledInfo res, UserHandle user, int installReason) {
18050        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18051
18052        String pkgName = newPackage.packageName;
18053        synchronized (mPackages) {
18054            //write settings. the installStatus will be incomplete at this stage.
18055            //note that the new package setting would have already been
18056            //added to mPackages. It hasn't been persisted yet.
18057            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18058            // TODO: Remove this write? It's also written at the end of this method
18059            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18060            mSettings.writeLPr();
18061            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18062        }
18063
18064        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18065        synchronized (mPackages) {
18066            updatePermissionsLPw(newPackage.packageName, newPackage,
18067                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18068                            ? UPDATE_PERMISSIONS_ALL : 0));
18069            // For system-bundled packages, we assume that installing an upgraded version
18070            // of the package implies that the user actually wants to run that new code,
18071            // so we enable the package.
18072            PackageSetting ps = mSettings.mPackages.get(pkgName);
18073            final int userId = user.getIdentifier();
18074            if (ps != null) {
18075                if (isSystemApp(newPackage)) {
18076                    if (DEBUG_INSTALL) {
18077                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18078                    }
18079                    // Enable system package for requested users
18080                    if (res.origUsers != null) {
18081                        for (int origUserId : res.origUsers) {
18082                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18083                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18084                                        origUserId, installerPackageName);
18085                            }
18086                        }
18087                    }
18088                    // Also convey the prior install/uninstall state
18089                    if (allUsers != null && installedForUsers != null) {
18090                        for (int currentUserId : allUsers) {
18091                            final boolean installed = ArrayUtils.contains(
18092                                    installedForUsers, currentUserId);
18093                            if (DEBUG_INSTALL) {
18094                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18095                            }
18096                            ps.setInstalled(installed, currentUserId);
18097                        }
18098                        // these install state changes will be persisted in the
18099                        // upcoming call to mSettings.writeLPr().
18100                    }
18101                }
18102                // It's implied that when a user requests installation, they want the app to be
18103                // installed and enabled.
18104                if (userId != UserHandle.USER_ALL) {
18105                    ps.setInstalled(true, userId);
18106                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18107                }
18108
18109                // When replacing an existing package, preserve the original install reason for all
18110                // users that had the package installed before.
18111                final Set<Integer> previousUserIds = new ArraySet<>();
18112                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18113                    final int installReasonCount = res.removedInfo.installReasons.size();
18114                    for (int i = 0; i < installReasonCount; i++) {
18115                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18116                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18117                        ps.setInstallReason(previousInstallReason, previousUserId);
18118                        previousUserIds.add(previousUserId);
18119                    }
18120                }
18121
18122                // Set install reason for users that are having the package newly installed.
18123                if (userId == UserHandle.USER_ALL) {
18124                    for (int currentUserId : sUserManager.getUserIds()) {
18125                        if (!previousUserIds.contains(currentUserId)) {
18126                            ps.setInstallReason(installReason, currentUserId);
18127                        }
18128                    }
18129                } else if (!previousUserIds.contains(userId)) {
18130                    ps.setInstallReason(installReason, userId);
18131                }
18132                mSettings.writeKernelMappingLPr(ps);
18133            }
18134            res.name = pkgName;
18135            res.uid = newPackage.applicationInfo.uid;
18136            res.pkg = newPackage;
18137            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18138            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18139            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18140            //to update install status
18141            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18142            mSettings.writeLPr();
18143            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18144        }
18145
18146        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18147    }
18148
18149    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18150        try {
18151            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18152            installPackageLI(args, res);
18153        } finally {
18154            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18155        }
18156    }
18157
18158    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18159        final int installFlags = args.installFlags;
18160        final String installerPackageName = args.installerPackageName;
18161        final String volumeUuid = args.volumeUuid;
18162        final File tmpPackageFile = new File(args.getCodePath());
18163        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18164        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18165                || (args.volumeUuid != null));
18166        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18167        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18168        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18169        boolean replace = false;
18170        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18171        if (args.move != null) {
18172            // moving a complete application; perform an initial scan on the new install location
18173            scanFlags |= SCAN_INITIAL;
18174        }
18175        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18176            scanFlags |= SCAN_DONT_KILL_APP;
18177        }
18178        if (instantApp) {
18179            scanFlags |= SCAN_AS_INSTANT_APP;
18180        }
18181        if (fullApp) {
18182            scanFlags |= SCAN_AS_FULL_APP;
18183        }
18184
18185        // Result object to be returned
18186        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18187
18188        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18189
18190        // Sanity check
18191        if (instantApp && (forwardLocked || onExternal)) {
18192            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18193                    + " external=" + onExternal);
18194            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18195            return;
18196        }
18197
18198        // Retrieve PackageSettings and parse package
18199        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18200                | PackageParser.PARSE_ENFORCE_CODE
18201                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18202                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18203                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18204                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18205        PackageParser pp = new PackageParser();
18206        pp.setSeparateProcesses(mSeparateProcesses);
18207        pp.setDisplayMetrics(mMetrics);
18208        pp.setCallback(mPackageParserCallback);
18209
18210        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18211        final PackageParser.Package pkg;
18212        try {
18213            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18214        } catch (PackageParserException e) {
18215            res.setError("Failed parse during installPackageLI", e);
18216            return;
18217        } finally {
18218            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18219        }
18220
18221        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18222        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18223            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18224            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18225                    "Instant app package must target O");
18226            return;
18227        }
18228        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18229            Slog.w(TAG, "Instant app package " + pkg.packageName
18230                    + " does not target targetSandboxVersion 2");
18231            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18232                    "Instant app package must use targetSanboxVersion 2");
18233            return;
18234        }
18235
18236        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18237            // Static shared libraries have synthetic package names
18238            renameStaticSharedLibraryPackage(pkg);
18239
18240            // No static shared libs on external storage
18241            if (onExternal) {
18242                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18243                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18244                        "Packages declaring static-shared libs cannot be updated");
18245                return;
18246            }
18247        }
18248
18249        // If we are installing a clustered package add results for the children
18250        if (pkg.childPackages != null) {
18251            synchronized (mPackages) {
18252                final int childCount = pkg.childPackages.size();
18253                for (int i = 0; i < childCount; i++) {
18254                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18255                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18256                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18257                    childRes.pkg = childPkg;
18258                    childRes.name = childPkg.packageName;
18259                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18260                    if (childPs != null) {
18261                        childRes.origUsers = childPs.queryInstalledUsers(
18262                                sUserManager.getUserIds(), true);
18263                    }
18264                    if ((mPackages.containsKey(childPkg.packageName))) {
18265                        childRes.removedInfo = new PackageRemovedInfo(this);
18266                        childRes.removedInfo.removedPackage = childPkg.packageName;
18267                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18268                    }
18269                    if (res.addedChildPackages == null) {
18270                        res.addedChildPackages = new ArrayMap<>();
18271                    }
18272                    res.addedChildPackages.put(childPkg.packageName, childRes);
18273                }
18274            }
18275        }
18276
18277        // If package doesn't declare API override, mark that we have an install
18278        // time CPU ABI override.
18279        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18280            pkg.cpuAbiOverride = args.abiOverride;
18281        }
18282
18283        String pkgName = res.name = pkg.packageName;
18284        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18285            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18286                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18287                return;
18288            }
18289        }
18290
18291        try {
18292            // either use what we've been given or parse directly from the APK
18293            if (args.certificates != null) {
18294                try {
18295                    PackageParser.populateCertificates(pkg, args.certificates);
18296                } catch (PackageParserException e) {
18297                    // there was something wrong with the certificates we were given;
18298                    // try to pull them from the APK
18299                    PackageParser.collectCertificates(pkg, parseFlags);
18300                }
18301            } else {
18302                PackageParser.collectCertificates(pkg, parseFlags);
18303            }
18304        } catch (PackageParserException e) {
18305            res.setError("Failed collect during installPackageLI", e);
18306            return;
18307        }
18308
18309        // Get rid of all references to package scan path via parser.
18310        pp = null;
18311        String oldCodePath = null;
18312        boolean systemApp = false;
18313        synchronized (mPackages) {
18314            // Check if installing already existing package
18315            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18316                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18317                if (pkg.mOriginalPackages != null
18318                        && pkg.mOriginalPackages.contains(oldName)
18319                        && mPackages.containsKey(oldName)) {
18320                    // This package is derived from an original package,
18321                    // and this device has been updating from that original
18322                    // name.  We must continue using the original name, so
18323                    // rename the new package here.
18324                    pkg.setPackageName(oldName);
18325                    pkgName = pkg.packageName;
18326                    replace = true;
18327                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18328                            + oldName + " pkgName=" + pkgName);
18329                } else if (mPackages.containsKey(pkgName)) {
18330                    // This package, under its official name, already exists
18331                    // on the device; we should replace it.
18332                    replace = true;
18333                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18334                }
18335
18336                // Child packages are installed through the parent package
18337                if (pkg.parentPackage != null) {
18338                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18339                            "Package " + pkg.packageName + " is child of package "
18340                                    + pkg.parentPackage.parentPackage + ". Child packages "
18341                                    + "can be updated only through the parent package.");
18342                    return;
18343                }
18344
18345                if (replace) {
18346                    // Prevent apps opting out from runtime permissions
18347                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18348                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18349                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18350                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18351                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18352                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18353                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18354                                        + " doesn't support runtime permissions but the old"
18355                                        + " target SDK " + oldTargetSdk + " does.");
18356                        return;
18357                    }
18358                    // Prevent apps from downgrading their targetSandbox.
18359                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18360                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18361                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18362                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18363                                "Package " + pkg.packageName + " new target sandbox "
18364                                + newTargetSandbox + " is incompatible with the previous value of"
18365                                + oldTargetSandbox + ".");
18366                        return;
18367                    }
18368
18369                    // Prevent installing of child packages
18370                    if (oldPackage.parentPackage != null) {
18371                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18372                                "Package " + pkg.packageName + " is child of package "
18373                                        + oldPackage.parentPackage + ". Child packages "
18374                                        + "can be updated only through the parent package.");
18375                        return;
18376                    }
18377                }
18378            }
18379
18380            PackageSetting ps = mSettings.mPackages.get(pkgName);
18381            if (ps != null) {
18382                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18383
18384                // Static shared libs have same package with different versions where
18385                // we internally use a synthetic package name to allow multiple versions
18386                // of the same package, therefore we need to compare signatures against
18387                // the package setting for the latest library version.
18388                PackageSetting signatureCheckPs = ps;
18389                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18390                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18391                    if (libraryEntry != null) {
18392                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18393                    }
18394                }
18395
18396                // Quick sanity check that we're signed correctly if updating;
18397                // we'll check this again later when scanning, but we want to
18398                // bail early here before tripping over redefined permissions.
18399                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18400                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18401                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18402                                + pkg.packageName + " upgrade keys do not match the "
18403                                + "previously installed version");
18404                        return;
18405                    }
18406                } else {
18407                    try {
18408                        verifySignaturesLP(signatureCheckPs, pkg);
18409                    } catch (PackageManagerException e) {
18410                        res.setError(e.error, e.getMessage());
18411                        return;
18412                    }
18413                }
18414
18415                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18416                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18417                    systemApp = (ps.pkg.applicationInfo.flags &
18418                            ApplicationInfo.FLAG_SYSTEM) != 0;
18419                }
18420                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18421            }
18422
18423            int N = pkg.permissions.size();
18424            for (int i = N-1; i >= 0; i--) {
18425                PackageParser.Permission perm = pkg.permissions.get(i);
18426                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18427
18428                // Don't allow anyone but the system to define ephemeral permissions.
18429                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18430                        && !systemApp) {
18431                    Slog.w(TAG, "Non-System package " + pkg.packageName
18432                            + " attempting to delcare ephemeral permission "
18433                            + perm.info.name + "; Removing ephemeral.");
18434                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18435                }
18436                // Check whether the newly-scanned package wants to define an already-defined perm
18437                if (bp != null) {
18438                    // If the defining package is signed with our cert, it's okay.  This
18439                    // also includes the "updating the same package" case, of course.
18440                    // "updating same package" could also involve key-rotation.
18441                    final boolean sigsOk;
18442                    if (bp.sourcePackage.equals(pkg.packageName)
18443                            && (bp.packageSetting instanceof PackageSetting)
18444                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18445                                    scanFlags))) {
18446                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18447                    } else {
18448                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18449                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18450                    }
18451                    if (!sigsOk) {
18452                        // If the owning package is the system itself, we log but allow
18453                        // install to proceed; we fail the install on all other permission
18454                        // redefinitions.
18455                        if (!bp.sourcePackage.equals("android")) {
18456                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18457                                    + pkg.packageName + " attempting to redeclare permission "
18458                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18459                            res.origPermission = perm.info.name;
18460                            res.origPackage = bp.sourcePackage;
18461                            return;
18462                        } else {
18463                            Slog.w(TAG, "Package " + pkg.packageName
18464                                    + " attempting to redeclare system permission "
18465                                    + perm.info.name + "; ignoring new declaration");
18466                            pkg.permissions.remove(i);
18467                        }
18468                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18469                        // Prevent apps to change protection level to dangerous from any other
18470                        // type as this would allow a privilege escalation where an app adds a
18471                        // normal/signature permission in other app's group and later redefines
18472                        // it as dangerous leading to the group auto-grant.
18473                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18474                                == PermissionInfo.PROTECTION_DANGEROUS) {
18475                            if (bp != null && !bp.isRuntime()) {
18476                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18477                                        + "non-runtime permission " + perm.info.name
18478                                        + " to runtime; keeping old protection level");
18479                                perm.info.protectionLevel = bp.protectionLevel;
18480                            }
18481                        }
18482                    }
18483                }
18484            }
18485        }
18486
18487        if (systemApp) {
18488            if (onExternal) {
18489                // Abort update; system app can't be replaced with app on sdcard
18490                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18491                        "Cannot install updates to system apps on sdcard");
18492                return;
18493            } else if (instantApp) {
18494                // Abort update; system app can't be replaced with an instant app
18495                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18496                        "Cannot update a system app with an instant app");
18497                return;
18498            }
18499        }
18500
18501        if (args.move != null) {
18502            // We did an in-place move, so dex is ready to roll
18503            scanFlags |= SCAN_NO_DEX;
18504            scanFlags |= SCAN_MOVE;
18505
18506            synchronized (mPackages) {
18507                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18508                if (ps == null) {
18509                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18510                            "Missing settings for moved package " + pkgName);
18511                }
18512
18513                // We moved the entire application as-is, so bring over the
18514                // previously derived ABI information.
18515                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18516                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18517            }
18518
18519        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18520            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18521            scanFlags |= SCAN_NO_DEX;
18522
18523            try {
18524                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18525                    args.abiOverride : pkg.cpuAbiOverride);
18526                final boolean extractNativeLibs = !pkg.isLibrary();
18527                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18528                        extractNativeLibs, mAppLib32InstallDir);
18529            } catch (PackageManagerException pme) {
18530                Slog.e(TAG, "Error deriving application ABI", pme);
18531                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18532                return;
18533            }
18534
18535            // Shared libraries for the package need to be updated.
18536            synchronized (mPackages) {
18537                try {
18538                    updateSharedLibrariesLPr(pkg, null);
18539                } catch (PackageManagerException e) {
18540                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18541                }
18542            }
18543
18544            // dexopt can take some time to complete, so, for instant apps, we skip this
18545            // step during installation. Instead, we'll take extra time the first time the
18546            // instant app starts. It's preferred to do it this way to provide continuous
18547            // progress to the user instead of mysteriously blocking somewhere in the
18548            // middle of running an instant app. The default behaviour can be overridden
18549            // via gservices.
18550            if (!instantApp || Global.getInt(
18551                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18552                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18553                // Do not run PackageDexOptimizer through the local performDexOpt
18554                // method because `pkg` may not be in `mPackages` yet.
18555                //
18556                // Also, don't fail application installs if the dexopt step fails.
18557                DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18558                        REASON_INSTALL,
18559                        DexoptOptions.DEXOPT_BOOT_COMPLETE);
18560                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18561                        null /* instructionSets */,
18562                        getOrCreateCompilerPackageStats(pkg),
18563                        mDexManager.isUsedByOtherApps(pkg.packageName),
18564                        dexoptOptions);
18565                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18566            }
18567
18568            // Notify BackgroundDexOptService that the package has been changed.
18569            // If this is an update of a package which used to fail to compile,
18570            // BDOS will remove it from its blacklist.
18571            // TODO: Layering violation
18572            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18573        }
18574
18575        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18576            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18577            return;
18578        }
18579
18580        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18581
18582        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18583                "installPackageLI")) {
18584            if (replace) {
18585                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18586                    // Static libs have a synthetic package name containing the version
18587                    // and cannot be updated as an update would get a new package name,
18588                    // unless this is the exact same version code which is useful for
18589                    // development.
18590                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18591                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18592                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18593                                + "static-shared libs cannot be updated");
18594                        return;
18595                    }
18596                }
18597                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18598                        installerPackageName, res, args.installReason);
18599            } else {
18600                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18601                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18602            }
18603        }
18604
18605        synchronized (mPackages) {
18606            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18607            if (ps != null) {
18608                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18609                ps.setUpdateAvailable(false /*updateAvailable*/);
18610            }
18611
18612            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18613            for (int i = 0; i < childCount; i++) {
18614                PackageParser.Package childPkg = pkg.childPackages.get(i);
18615                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18616                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18617                if (childPs != null) {
18618                    childRes.newUsers = childPs.queryInstalledUsers(
18619                            sUserManager.getUserIds(), true);
18620                }
18621            }
18622
18623            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18624                updateSequenceNumberLP(ps, res.newUsers);
18625                updateInstantAppInstallerLocked(pkgName);
18626            }
18627        }
18628    }
18629
18630    private void startIntentFilterVerifications(int userId, boolean replacing,
18631            PackageParser.Package pkg) {
18632        if (mIntentFilterVerifierComponent == null) {
18633            Slog.w(TAG, "No IntentFilter verification will not be done as "
18634                    + "there is no IntentFilterVerifier available!");
18635            return;
18636        }
18637
18638        final int verifierUid = getPackageUid(
18639                mIntentFilterVerifierComponent.getPackageName(),
18640                MATCH_DEBUG_TRIAGED_MISSING,
18641                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18642
18643        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18644        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18645        mHandler.sendMessage(msg);
18646
18647        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18648        for (int i = 0; i < childCount; i++) {
18649            PackageParser.Package childPkg = pkg.childPackages.get(i);
18650            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18651            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18652            mHandler.sendMessage(msg);
18653        }
18654    }
18655
18656    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18657            PackageParser.Package pkg) {
18658        int size = pkg.activities.size();
18659        if (size == 0) {
18660            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18661                    "No activity, so no need to verify any IntentFilter!");
18662            return;
18663        }
18664
18665        final boolean hasDomainURLs = hasDomainURLs(pkg);
18666        if (!hasDomainURLs) {
18667            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18668                    "No domain URLs, so no need to verify any IntentFilter!");
18669            return;
18670        }
18671
18672        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18673                + " if any IntentFilter from the " + size
18674                + " Activities needs verification ...");
18675
18676        int count = 0;
18677        final String packageName = pkg.packageName;
18678
18679        synchronized (mPackages) {
18680            // If this is a new install and we see that we've already run verification for this
18681            // package, we have nothing to do: it means the state was restored from backup.
18682            if (!replacing) {
18683                IntentFilterVerificationInfo ivi =
18684                        mSettings.getIntentFilterVerificationLPr(packageName);
18685                if (ivi != null) {
18686                    if (DEBUG_DOMAIN_VERIFICATION) {
18687                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18688                                + ivi.getStatusString());
18689                    }
18690                    return;
18691                }
18692            }
18693
18694            // If any filters need to be verified, then all need to be.
18695            boolean needToVerify = false;
18696            for (PackageParser.Activity a : pkg.activities) {
18697                for (ActivityIntentInfo filter : a.intents) {
18698                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18699                        if (DEBUG_DOMAIN_VERIFICATION) {
18700                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18701                        }
18702                        needToVerify = true;
18703                        break;
18704                    }
18705                }
18706            }
18707
18708            if (needToVerify) {
18709                final int verificationId = mIntentFilterVerificationToken++;
18710                for (PackageParser.Activity a : pkg.activities) {
18711                    for (ActivityIntentInfo filter : a.intents) {
18712                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18713                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18714                                    "Verification needed for IntentFilter:" + filter.toString());
18715                            mIntentFilterVerifier.addOneIntentFilterVerification(
18716                                    verifierUid, userId, verificationId, filter, packageName);
18717                            count++;
18718                        }
18719                    }
18720                }
18721            }
18722        }
18723
18724        if (count > 0) {
18725            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18726                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18727                    +  " for userId:" + userId);
18728            mIntentFilterVerifier.startVerifications(userId);
18729        } else {
18730            if (DEBUG_DOMAIN_VERIFICATION) {
18731                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18732            }
18733        }
18734    }
18735
18736    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18737        final ComponentName cn  = filter.activity.getComponentName();
18738        final String packageName = cn.getPackageName();
18739
18740        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18741                packageName);
18742        if (ivi == null) {
18743            return true;
18744        }
18745        int status = ivi.getStatus();
18746        switch (status) {
18747            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18748            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18749                return true;
18750
18751            default:
18752                // Nothing to do
18753                return false;
18754        }
18755    }
18756
18757    private static boolean isMultiArch(ApplicationInfo info) {
18758        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18759    }
18760
18761    private static boolean isExternal(PackageParser.Package pkg) {
18762        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18763    }
18764
18765    private static boolean isExternal(PackageSetting ps) {
18766        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18767    }
18768
18769    private static boolean isSystemApp(PackageParser.Package pkg) {
18770        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18771    }
18772
18773    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18774        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18775    }
18776
18777    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18778        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18779    }
18780
18781    private static boolean isSystemApp(PackageSetting ps) {
18782        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18783    }
18784
18785    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18786        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18787    }
18788
18789    private int packageFlagsToInstallFlags(PackageSetting ps) {
18790        int installFlags = 0;
18791        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18792            // This existing package was an external ASEC install when we have
18793            // the external flag without a UUID
18794            installFlags |= PackageManager.INSTALL_EXTERNAL;
18795        }
18796        if (ps.isForwardLocked()) {
18797            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18798        }
18799        return installFlags;
18800    }
18801
18802    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18803        if (isExternal(pkg)) {
18804            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18805                return StorageManager.UUID_PRIMARY_PHYSICAL;
18806            } else {
18807                return pkg.volumeUuid;
18808            }
18809        } else {
18810            return StorageManager.UUID_PRIVATE_INTERNAL;
18811        }
18812    }
18813
18814    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18815        if (isExternal(pkg)) {
18816            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18817                return mSettings.getExternalVersion();
18818            } else {
18819                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18820            }
18821        } else {
18822            return mSettings.getInternalVersion();
18823        }
18824    }
18825
18826    private void deleteTempPackageFiles() {
18827        final FilenameFilter filter = new FilenameFilter() {
18828            public boolean accept(File dir, String name) {
18829                return name.startsWith("vmdl") && name.endsWith(".tmp");
18830            }
18831        };
18832        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18833            file.delete();
18834        }
18835    }
18836
18837    @Override
18838    public void deletePackageAsUser(String packageName, int versionCode,
18839            IPackageDeleteObserver observer, int userId, int flags) {
18840        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18841                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18842    }
18843
18844    @Override
18845    public void deletePackageVersioned(VersionedPackage versionedPackage,
18846            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18847        final int callingUid = Binder.getCallingUid();
18848        mContext.enforceCallingOrSelfPermission(
18849                android.Manifest.permission.DELETE_PACKAGES, null);
18850        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18851        Preconditions.checkNotNull(versionedPackage);
18852        Preconditions.checkNotNull(observer);
18853        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18854                PackageManager.VERSION_CODE_HIGHEST,
18855                Integer.MAX_VALUE, "versionCode must be >= -1");
18856
18857        final String packageName = versionedPackage.getPackageName();
18858        final int versionCode = versionedPackage.getVersionCode();
18859        final String internalPackageName;
18860        synchronized (mPackages) {
18861            // Normalize package name to handle renamed packages and static libs
18862            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18863                    versionedPackage.getVersionCode());
18864        }
18865
18866        final int uid = Binder.getCallingUid();
18867        if (!isOrphaned(internalPackageName)
18868                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18869            try {
18870                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18871                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18872                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18873                observer.onUserActionRequired(intent);
18874            } catch (RemoteException re) {
18875            }
18876            return;
18877        }
18878        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18879        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18880        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18881            mContext.enforceCallingOrSelfPermission(
18882                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18883                    "deletePackage for user " + userId);
18884        }
18885
18886        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18887            try {
18888                observer.onPackageDeleted(packageName,
18889                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18890            } catch (RemoteException re) {
18891            }
18892            return;
18893        }
18894
18895        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18896            try {
18897                observer.onPackageDeleted(packageName,
18898                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18899            } catch (RemoteException re) {
18900            }
18901            return;
18902        }
18903
18904        if (DEBUG_REMOVE) {
18905            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18906                    + " deleteAllUsers: " + deleteAllUsers + " version="
18907                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18908                    ? "VERSION_CODE_HIGHEST" : versionCode));
18909        }
18910        // Queue up an async operation since the package deletion may take a little while.
18911        mHandler.post(new Runnable() {
18912            public void run() {
18913                mHandler.removeCallbacks(this);
18914                int returnCode;
18915                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18916                boolean doDeletePackage = true;
18917                if (ps != null) {
18918                    final boolean targetIsInstantApp =
18919                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18920                    doDeletePackage = !targetIsInstantApp
18921                            || canViewInstantApps;
18922                }
18923                if (doDeletePackage) {
18924                    if (!deleteAllUsers) {
18925                        returnCode = deletePackageX(internalPackageName, versionCode,
18926                                userId, deleteFlags);
18927                    } else {
18928                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18929                                internalPackageName, users);
18930                        // If nobody is blocking uninstall, proceed with delete for all users
18931                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18932                            returnCode = deletePackageX(internalPackageName, versionCode,
18933                                    userId, deleteFlags);
18934                        } else {
18935                            // Otherwise uninstall individually for users with blockUninstalls=false
18936                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18937                            for (int userId : users) {
18938                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18939                                    returnCode = deletePackageX(internalPackageName, versionCode,
18940                                            userId, userFlags);
18941                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18942                                        Slog.w(TAG, "Package delete failed for user " + userId
18943                                                + ", returnCode " + returnCode);
18944                                    }
18945                                }
18946                            }
18947                            // The app has only been marked uninstalled for certain users.
18948                            // We still need to report that delete was blocked
18949                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18950                        }
18951                    }
18952                } else {
18953                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18954                }
18955                try {
18956                    observer.onPackageDeleted(packageName, returnCode, null);
18957                } catch (RemoteException e) {
18958                    Log.i(TAG, "Observer no longer exists.");
18959                } //end catch
18960            } //end run
18961        });
18962    }
18963
18964    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18965        if (pkg.staticSharedLibName != null) {
18966            return pkg.manifestPackageName;
18967        }
18968        return pkg.packageName;
18969    }
18970
18971    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18972        // Handle renamed packages
18973        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18974        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18975
18976        // Is this a static library?
18977        SparseArray<SharedLibraryEntry> versionedLib =
18978                mStaticLibsByDeclaringPackage.get(packageName);
18979        if (versionedLib == null || versionedLib.size() <= 0) {
18980            return packageName;
18981        }
18982
18983        // Figure out which lib versions the caller can see
18984        SparseIntArray versionsCallerCanSee = null;
18985        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18986        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18987                && callingAppId != Process.ROOT_UID) {
18988            versionsCallerCanSee = new SparseIntArray();
18989            String libName = versionedLib.valueAt(0).info.getName();
18990            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18991            if (uidPackages != null) {
18992                for (String uidPackage : uidPackages) {
18993                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18994                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18995                    if (libIdx >= 0) {
18996                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18997                        versionsCallerCanSee.append(libVersion, libVersion);
18998                    }
18999                }
19000            }
19001        }
19002
19003        // Caller can see nothing - done
19004        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19005            return packageName;
19006        }
19007
19008        // Find the version the caller can see and the app version code
19009        SharedLibraryEntry highestVersion = null;
19010        final int versionCount = versionedLib.size();
19011        for (int i = 0; i < versionCount; i++) {
19012            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19013            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19014                    libEntry.info.getVersion()) < 0) {
19015                continue;
19016            }
19017            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19018            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19019                if (libVersionCode == versionCode) {
19020                    return libEntry.apk;
19021                }
19022            } else if (highestVersion == null) {
19023                highestVersion = libEntry;
19024            } else if (libVersionCode  > highestVersion.info
19025                    .getDeclaringPackage().getVersionCode()) {
19026                highestVersion = libEntry;
19027            }
19028        }
19029
19030        if (highestVersion != null) {
19031            return highestVersion.apk;
19032        }
19033
19034        return packageName;
19035    }
19036
19037    boolean isCallerVerifier(int callingUid) {
19038        final int callingUserId = UserHandle.getUserId(callingUid);
19039        return mRequiredVerifierPackage != null &&
19040                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19041    }
19042
19043    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19044        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19045              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19046            return true;
19047        }
19048        final int callingUserId = UserHandle.getUserId(callingUid);
19049        // If the caller installed the pkgName, then allow it to silently uninstall.
19050        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19051            return true;
19052        }
19053
19054        // Allow package verifier to silently uninstall.
19055        if (mRequiredVerifierPackage != null &&
19056                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19057            return true;
19058        }
19059
19060        // Allow package uninstaller to silently uninstall.
19061        if (mRequiredUninstallerPackage != null &&
19062                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19063            return true;
19064        }
19065
19066        // Allow storage manager to silently uninstall.
19067        if (mStorageManagerPackage != null &&
19068                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19069            return true;
19070        }
19071
19072        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19073        // uninstall for device owner provisioning.
19074        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19075                == PERMISSION_GRANTED) {
19076            return true;
19077        }
19078
19079        return false;
19080    }
19081
19082    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19083        int[] result = EMPTY_INT_ARRAY;
19084        for (int userId : userIds) {
19085            if (getBlockUninstallForUser(packageName, userId)) {
19086                result = ArrayUtils.appendInt(result, userId);
19087            }
19088        }
19089        return result;
19090    }
19091
19092    @Override
19093    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19094        final int callingUid = Binder.getCallingUid();
19095        if (getInstantAppPackageName(callingUid) != null
19096                && !isCallerSameApp(packageName, callingUid)) {
19097            return false;
19098        }
19099        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19100    }
19101
19102    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19103        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19104                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19105        try {
19106            if (dpm != null) {
19107                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19108                        /* callingUserOnly =*/ false);
19109                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19110                        : deviceOwnerComponentName.getPackageName();
19111                // Does the package contains the device owner?
19112                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19113                // this check is probably not needed, since DO should be registered as a device
19114                // admin on some user too. (Original bug for this: b/17657954)
19115                if (packageName.equals(deviceOwnerPackageName)) {
19116                    return true;
19117                }
19118                // Does it contain a device admin for any user?
19119                int[] users;
19120                if (userId == UserHandle.USER_ALL) {
19121                    users = sUserManager.getUserIds();
19122                } else {
19123                    users = new int[]{userId};
19124                }
19125                for (int i = 0; i < users.length; ++i) {
19126                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19127                        return true;
19128                    }
19129                }
19130            }
19131        } catch (RemoteException e) {
19132        }
19133        return false;
19134    }
19135
19136    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19137        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19138    }
19139
19140    /**
19141     *  This method is an internal method that could be get invoked either
19142     *  to delete an installed package or to clean up a failed installation.
19143     *  After deleting an installed package, a broadcast is sent to notify any
19144     *  listeners that the package has been removed. For cleaning up a failed
19145     *  installation, the broadcast is not necessary since the package's
19146     *  installation wouldn't have sent the initial broadcast either
19147     *  The key steps in deleting a package are
19148     *  deleting the package information in internal structures like mPackages,
19149     *  deleting the packages base directories through installd
19150     *  updating mSettings to reflect current status
19151     *  persisting settings for later use
19152     *  sending a broadcast if necessary
19153     */
19154    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19155        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19156        final boolean res;
19157
19158        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19159                ? UserHandle.USER_ALL : userId;
19160
19161        if (isPackageDeviceAdmin(packageName, removeUser)) {
19162            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19163            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19164        }
19165
19166        PackageSetting uninstalledPs = null;
19167        PackageParser.Package pkg = null;
19168
19169        // for the uninstall-updates case and restricted profiles, remember the per-
19170        // user handle installed state
19171        int[] allUsers;
19172        synchronized (mPackages) {
19173            uninstalledPs = mSettings.mPackages.get(packageName);
19174            if (uninstalledPs == null) {
19175                Slog.w(TAG, "Not removing non-existent package " + packageName);
19176                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19177            }
19178
19179            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19180                    && uninstalledPs.versionCode != versionCode) {
19181                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19182                        + uninstalledPs.versionCode + " != " + versionCode);
19183                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19184            }
19185
19186            // Static shared libs can be declared by any package, so let us not
19187            // allow removing a package if it provides a lib others depend on.
19188            pkg = mPackages.get(packageName);
19189
19190            allUsers = sUserManager.getUserIds();
19191
19192            if (pkg != null && pkg.staticSharedLibName != null) {
19193                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19194                        pkg.staticSharedLibVersion);
19195                if (libEntry != null) {
19196                    for (int currUserId : allUsers) {
19197                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19198                            continue;
19199                        }
19200                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19201                                libEntry.info, 0, currUserId);
19202                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19203                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19204                                    + " hosting lib " + libEntry.info.getName() + " version "
19205                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19206                                    + " for user " + currUserId);
19207                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19208                        }
19209                    }
19210                }
19211            }
19212
19213            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19214        }
19215
19216        final int freezeUser;
19217        if (isUpdatedSystemApp(uninstalledPs)
19218                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19219            // We're downgrading a system app, which will apply to all users, so
19220            // freeze them all during the downgrade
19221            freezeUser = UserHandle.USER_ALL;
19222        } else {
19223            freezeUser = removeUser;
19224        }
19225
19226        synchronized (mInstallLock) {
19227            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19228            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19229                    deleteFlags, "deletePackageX")) {
19230                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19231                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19232            }
19233            synchronized (mPackages) {
19234                if (res) {
19235                    if (pkg != null) {
19236                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19237                    }
19238                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19239                    updateInstantAppInstallerLocked(packageName);
19240                }
19241            }
19242        }
19243
19244        if (res) {
19245            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19246            info.sendPackageRemovedBroadcasts(killApp);
19247            info.sendSystemPackageUpdatedBroadcasts();
19248            info.sendSystemPackageAppearedBroadcasts();
19249        }
19250        // Force a gc here.
19251        Runtime.getRuntime().gc();
19252        // Delete the resources here after sending the broadcast to let
19253        // other processes clean up before deleting resources.
19254        if (info.args != null) {
19255            synchronized (mInstallLock) {
19256                info.args.doPostDeleteLI(true);
19257            }
19258        }
19259
19260        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19261    }
19262
19263    static class PackageRemovedInfo {
19264        final PackageSender packageSender;
19265        String removedPackage;
19266        String installerPackageName;
19267        int uid = -1;
19268        int removedAppId = -1;
19269        int[] origUsers;
19270        int[] removedUsers = null;
19271        int[] broadcastUsers = null;
19272        SparseArray<Integer> installReasons;
19273        boolean isRemovedPackageSystemUpdate = false;
19274        boolean isUpdate;
19275        boolean dataRemoved;
19276        boolean removedForAllUsers;
19277        boolean isStaticSharedLib;
19278        // Clean up resources deleted packages.
19279        InstallArgs args = null;
19280        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19281        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19282
19283        PackageRemovedInfo(PackageSender packageSender) {
19284            this.packageSender = packageSender;
19285        }
19286
19287        void sendPackageRemovedBroadcasts(boolean killApp) {
19288            sendPackageRemovedBroadcastInternal(killApp);
19289            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19290            for (int i = 0; i < childCount; i++) {
19291                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19292                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19293            }
19294        }
19295
19296        void sendSystemPackageUpdatedBroadcasts() {
19297            if (isRemovedPackageSystemUpdate) {
19298                sendSystemPackageUpdatedBroadcastsInternal();
19299                final int childCount = (removedChildPackages != null)
19300                        ? removedChildPackages.size() : 0;
19301                for (int i = 0; i < childCount; i++) {
19302                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19303                    if (childInfo.isRemovedPackageSystemUpdate) {
19304                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19305                    }
19306                }
19307            }
19308        }
19309
19310        void sendSystemPackageAppearedBroadcasts() {
19311            final int packageCount = (appearedChildPackages != null)
19312                    ? appearedChildPackages.size() : 0;
19313            for (int i = 0; i < packageCount; i++) {
19314                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19315                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19316                    true /*sendBootCompleted*/, false /*startReceiver*/,
19317                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19318            }
19319        }
19320
19321        private void sendSystemPackageUpdatedBroadcastsInternal() {
19322            Bundle extras = new Bundle(2);
19323            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19324            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19325            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19326                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19327            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19328                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19329            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19330                null, null, 0, removedPackage, null, null);
19331            if (installerPackageName != null) {
19332                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19333                        removedPackage, extras, 0 /*flags*/,
19334                        installerPackageName, null, null);
19335                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19336                        removedPackage, extras, 0 /*flags*/,
19337                        installerPackageName, null, null);
19338            }
19339        }
19340
19341        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19342            // Don't send static shared library removal broadcasts as these
19343            // libs are visible only the the apps that depend on them an one
19344            // cannot remove the library if it has a dependency.
19345            if (isStaticSharedLib) {
19346                return;
19347            }
19348            Bundle extras = new Bundle(2);
19349            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19350            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19351            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19352            if (isUpdate || isRemovedPackageSystemUpdate) {
19353                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19354            }
19355            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19356            if (removedPackage != null) {
19357                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19358                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19359                if (installerPackageName != null) {
19360                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19361                            removedPackage, extras, 0 /*flags*/,
19362                            installerPackageName, null, broadcastUsers);
19363                }
19364                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19365                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19366                        removedPackage, extras,
19367                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19368                        null, null, broadcastUsers);
19369                }
19370            }
19371            if (removedAppId >= 0) {
19372                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19373                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19374                    null, null, broadcastUsers);
19375            }
19376        }
19377
19378        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19379            removedUsers = userIds;
19380            if (removedUsers == null) {
19381                broadcastUsers = null;
19382                return;
19383            }
19384
19385            broadcastUsers = EMPTY_INT_ARRAY;
19386            for (int i = userIds.length - 1; i >= 0; --i) {
19387                final int userId = userIds[i];
19388                if (deletedPackageSetting.getInstantApp(userId)) {
19389                    continue;
19390                }
19391                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19392            }
19393        }
19394    }
19395
19396    /*
19397     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19398     * flag is not set, the data directory is removed as well.
19399     * make sure this flag is set for partially installed apps. If not its meaningless to
19400     * delete a partially installed application.
19401     */
19402    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19403            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19404        String packageName = ps.name;
19405        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19406        // Retrieve object to delete permissions for shared user later on
19407        final PackageParser.Package deletedPkg;
19408        final PackageSetting deletedPs;
19409        // reader
19410        synchronized (mPackages) {
19411            deletedPkg = mPackages.get(packageName);
19412            deletedPs = mSettings.mPackages.get(packageName);
19413            if (outInfo != null) {
19414                outInfo.removedPackage = packageName;
19415                outInfo.installerPackageName = ps.installerPackageName;
19416                outInfo.isStaticSharedLib = deletedPkg != null
19417                        && deletedPkg.staticSharedLibName != null;
19418                outInfo.populateUsers(deletedPs == null ? null
19419                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19420            }
19421        }
19422
19423        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19424
19425        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19426            final PackageParser.Package resolvedPkg;
19427            if (deletedPkg != null) {
19428                resolvedPkg = deletedPkg;
19429            } else {
19430                // We don't have a parsed package when it lives on an ejected
19431                // adopted storage device, so fake something together
19432                resolvedPkg = new PackageParser.Package(ps.name);
19433                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19434            }
19435            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19436                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19437            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19438            if (outInfo != null) {
19439                outInfo.dataRemoved = true;
19440            }
19441            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19442        }
19443
19444        int removedAppId = -1;
19445
19446        // writer
19447        synchronized (mPackages) {
19448            boolean installedStateChanged = false;
19449            if (deletedPs != null) {
19450                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19451                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19452                    clearDefaultBrowserIfNeeded(packageName);
19453                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19454                    removedAppId = mSettings.removePackageLPw(packageName);
19455                    if (outInfo != null) {
19456                        outInfo.removedAppId = removedAppId;
19457                    }
19458                    updatePermissionsLPw(deletedPs.name, null, 0);
19459                    if (deletedPs.sharedUser != null) {
19460                        // Remove permissions associated with package. Since runtime
19461                        // permissions are per user we have to kill the removed package
19462                        // or packages running under the shared user of the removed
19463                        // package if revoking the permissions requested only by the removed
19464                        // package is successful and this causes a change in gids.
19465                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19466                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19467                                    userId);
19468                            if (userIdToKill == UserHandle.USER_ALL
19469                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19470                                // If gids changed for this user, kill all affected packages.
19471                                mHandler.post(new Runnable() {
19472                                    @Override
19473                                    public void run() {
19474                                        // This has to happen with no lock held.
19475                                        killApplication(deletedPs.name, deletedPs.appId,
19476                                                KILL_APP_REASON_GIDS_CHANGED);
19477                                    }
19478                                });
19479                                break;
19480                            }
19481                        }
19482                    }
19483                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19484                }
19485                // make sure to preserve per-user disabled state if this removal was just
19486                // a downgrade of a system app to the factory package
19487                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19488                    if (DEBUG_REMOVE) {
19489                        Slog.d(TAG, "Propagating install state across downgrade");
19490                    }
19491                    for (int userId : allUserHandles) {
19492                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19493                        if (DEBUG_REMOVE) {
19494                            Slog.d(TAG, "    user " + userId + " => " + installed);
19495                        }
19496                        if (installed != ps.getInstalled(userId)) {
19497                            installedStateChanged = true;
19498                        }
19499                        ps.setInstalled(installed, userId);
19500                    }
19501                }
19502            }
19503            // can downgrade to reader
19504            if (writeSettings) {
19505                // Save settings now
19506                mSettings.writeLPr();
19507            }
19508            if (installedStateChanged) {
19509                mSettings.writeKernelMappingLPr(ps);
19510            }
19511        }
19512        if (removedAppId != -1) {
19513            // A user ID was deleted here. Go through all users and remove it
19514            // from KeyStore.
19515            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19516        }
19517    }
19518
19519    static boolean locationIsPrivileged(File path) {
19520        try {
19521            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19522                    .getCanonicalPath();
19523            return path.getCanonicalPath().startsWith(privilegedAppDir);
19524        } catch (IOException e) {
19525            Slog.e(TAG, "Unable to access code path " + path);
19526        }
19527        return false;
19528    }
19529
19530    /*
19531     * Tries to delete system package.
19532     */
19533    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19534            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19535            boolean writeSettings) {
19536        if (deletedPs.parentPackageName != null) {
19537            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19538            return false;
19539        }
19540
19541        final boolean applyUserRestrictions
19542                = (allUserHandles != null) && (outInfo.origUsers != null);
19543        final PackageSetting disabledPs;
19544        // Confirm if the system package has been updated
19545        // An updated system app can be deleted. This will also have to restore
19546        // the system pkg from system partition
19547        // reader
19548        synchronized (mPackages) {
19549            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19550        }
19551
19552        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19553                + " disabledPs=" + disabledPs);
19554
19555        if (disabledPs == null) {
19556            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19557            return false;
19558        } else if (DEBUG_REMOVE) {
19559            Slog.d(TAG, "Deleting system pkg from data partition");
19560        }
19561
19562        if (DEBUG_REMOVE) {
19563            if (applyUserRestrictions) {
19564                Slog.d(TAG, "Remembering install states:");
19565                for (int userId : allUserHandles) {
19566                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19567                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19568                }
19569            }
19570        }
19571
19572        // Delete the updated package
19573        outInfo.isRemovedPackageSystemUpdate = true;
19574        if (outInfo.removedChildPackages != null) {
19575            final int childCount = (deletedPs.childPackageNames != null)
19576                    ? deletedPs.childPackageNames.size() : 0;
19577            for (int i = 0; i < childCount; i++) {
19578                String childPackageName = deletedPs.childPackageNames.get(i);
19579                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19580                        .contains(childPackageName)) {
19581                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19582                            childPackageName);
19583                    if (childInfo != null) {
19584                        childInfo.isRemovedPackageSystemUpdate = true;
19585                    }
19586                }
19587            }
19588        }
19589
19590        if (disabledPs.versionCode < deletedPs.versionCode) {
19591            // Delete data for downgrades
19592            flags &= ~PackageManager.DELETE_KEEP_DATA;
19593        } else {
19594            // Preserve data by setting flag
19595            flags |= PackageManager.DELETE_KEEP_DATA;
19596        }
19597
19598        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19599                outInfo, writeSettings, disabledPs.pkg);
19600        if (!ret) {
19601            return false;
19602        }
19603
19604        // writer
19605        synchronized (mPackages) {
19606            // Reinstate the old system package
19607            enableSystemPackageLPw(disabledPs.pkg);
19608            // Remove any native libraries from the upgraded package.
19609            removeNativeBinariesLI(deletedPs);
19610        }
19611
19612        // Install the system package
19613        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19614        int parseFlags = mDefParseFlags
19615                | PackageParser.PARSE_MUST_BE_APK
19616                | PackageParser.PARSE_IS_SYSTEM
19617                | PackageParser.PARSE_IS_SYSTEM_DIR;
19618        if (locationIsPrivileged(disabledPs.codePath)) {
19619            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19620        }
19621
19622        final PackageParser.Package newPkg;
19623        try {
19624            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19625                0 /* currentTime */, null);
19626        } catch (PackageManagerException e) {
19627            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19628                    + e.getMessage());
19629            return false;
19630        }
19631
19632        try {
19633            // update shared libraries for the newly re-installed system package
19634            updateSharedLibrariesLPr(newPkg, null);
19635        } catch (PackageManagerException e) {
19636            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19637        }
19638
19639        prepareAppDataAfterInstallLIF(newPkg);
19640
19641        // writer
19642        synchronized (mPackages) {
19643            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19644
19645            // Propagate the permissions state as we do not want to drop on the floor
19646            // runtime permissions. The update permissions method below will take
19647            // care of removing obsolete permissions and grant install permissions.
19648            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19649            updatePermissionsLPw(newPkg.packageName, newPkg,
19650                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19651
19652            if (applyUserRestrictions) {
19653                boolean installedStateChanged = false;
19654                if (DEBUG_REMOVE) {
19655                    Slog.d(TAG, "Propagating install state across reinstall");
19656                }
19657                for (int userId : allUserHandles) {
19658                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19659                    if (DEBUG_REMOVE) {
19660                        Slog.d(TAG, "    user " + userId + " => " + installed);
19661                    }
19662                    if (installed != ps.getInstalled(userId)) {
19663                        installedStateChanged = true;
19664                    }
19665                    ps.setInstalled(installed, userId);
19666
19667                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19668                }
19669                // Regardless of writeSettings we need to ensure that this restriction
19670                // state propagation is persisted
19671                mSettings.writeAllUsersPackageRestrictionsLPr();
19672                if (installedStateChanged) {
19673                    mSettings.writeKernelMappingLPr(ps);
19674                }
19675            }
19676            // can downgrade to reader here
19677            if (writeSettings) {
19678                mSettings.writeLPr();
19679            }
19680        }
19681        return true;
19682    }
19683
19684    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19685            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19686            PackageRemovedInfo outInfo, boolean writeSettings,
19687            PackageParser.Package replacingPackage) {
19688        synchronized (mPackages) {
19689            if (outInfo != null) {
19690                outInfo.uid = ps.appId;
19691            }
19692
19693            if (outInfo != null && outInfo.removedChildPackages != null) {
19694                final int childCount = (ps.childPackageNames != null)
19695                        ? ps.childPackageNames.size() : 0;
19696                for (int i = 0; i < childCount; i++) {
19697                    String childPackageName = ps.childPackageNames.get(i);
19698                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19699                    if (childPs == null) {
19700                        return false;
19701                    }
19702                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19703                            childPackageName);
19704                    if (childInfo != null) {
19705                        childInfo.uid = childPs.appId;
19706                    }
19707                }
19708            }
19709        }
19710
19711        // Delete package data from internal structures and also remove data if flag is set
19712        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19713
19714        // Delete the child packages data
19715        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19716        for (int i = 0; i < childCount; i++) {
19717            PackageSetting childPs;
19718            synchronized (mPackages) {
19719                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19720            }
19721            if (childPs != null) {
19722                PackageRemovedInfo childOutInfo = (outInfo != null
19723                        && outInfo.removedChildPackages != null)
19724                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19725                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19726                        && (replacingPackage != null
19727                        && !replacingPackage.hasChildPackage(childPs.name))
19728                        ? flags & ~DELETE_KEEP_DATA : flags;
19729                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19730                        deleteFlags, writeSettings);
19731            }
19732        }
19733
19734        // Delete application code and resources only for parent packages
19735        if (ps.parentPackageName == null) {
19736            if (deleteCodeAndResources && (outInfo != null)) {
19737                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19738                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19739                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19740            }
19741        }
19742
19743        return true;
19744    }
19745
19746    @Override
19747    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19748            int userId) {
19749        mContext.enforceCallingOrSelfPermission(
19750                android.Manifest.permission.DELETE_PACKAGES, null);
19751        synchronized (mPackages) {
19752            // Cannot block uninstall of static shared libs as they are
19753            // considered a part of the using app (emulating static linking).
19754            // Also static libs are installed always on internal storage.
19755            PackageParser.Package pkg = mPackages.get(packageName);
19756            if (pkg != null && pkg.staticSharedLibName != null) {
19757                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19758                        + " providing static shared library: " + pkg.staticSharedLibName);
19759                return false;
19760            }
19761            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19762            mSettings.writePackageRestrictionsLPr(userId);
19763        }
19764        return true;
19765    }
19766
19767    @Override
19768    public boolean getBlockUninstallForUser(String packageName, int userId) {
19769        synchronized (mPackages) {
19770            final PackageSetting ps = mSettings.mPackages.get(packageName);
19771            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19772                return false;
19773            }
19774            return mSettings.getBlockUninstallLPr(userId, packageName);
19775        }
19776    }
19777
19778    @Override
19779    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19780        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19781        synchronized (mPackages) {
19782            PackageSetting ps = mSettings.mPackages.get(packageName);
19783            if (ps == null) {
19784                Log.w(TAG, "Package doesn't exist: " + packageName);
19785                return false;
19786            }
19787            if (systemUserApp) {
19788                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19789            } else {
19790                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19791            }
19792            mSettings.writeLPr();
19793        }
19794        return true;
19795    }
19796
19797    /*
19798     * This method handles package deletion in general
19799     */
19800    private boolean deletePackageLIF(String packageName, UserHandle user,
19801            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19802            PackageRemovedInfo outInfo, boolean writeSettings,
19803            PackageParser.Package replacingPackage) {
19804        if (packageName == null) {
19805            Slog.w(TAG, "Attempt to delete null packageName.");
19806            return false;
19807        }
19808
19809        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19810
19811        PackageSetting ps;
19812        synchronized (mPackages) {
19813            ps = mSettings.mPackages.get(packageName);
19814            if (ps == null) {
19815                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19816                return false;
19817            }
19818
19819            if (ps.parentPackageName != null && (!isSystemApp(ps)
19820                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19821                if (DEBUG_REMOVE) {
19822                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19823                            + ((user == null) ? UserHandle.USER_ALL : user));
19824                }
19825                final int removedUserId = (user != null) ? user.getIdentifier()
19826                        : UserHandle.USER_ALL;
19827                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19828                    return false;
19829                }
19830                markPackageUninstalledForUserLPw(ps, user);
19831                scheduleWritePackageRestrictionsLocked(user);
19832                return true;
19833            }
19834        }
19835
19836        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19837                && user.getIdentifier() != UserHandle.USER_ALL)) {
19838            // The caller is asking that the package only be deleted for a single
19839            // user.  To do this, we just mark its uninstalled state and delete
19840            // its data. If this is a system app, we only allow this to happen if
19841            // they have set the special DELETE_SYSTEM_APP which requests different
19842            // semantics than normal for uninstalling system apps.
19843            markPackageUninstalledForUserLPw(ps, user);
19844
19845            if (!isSystemApp(ps)) {
19846                // Do not uninstall the APK if an app should be cached
19847                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19848                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19849                    // Other user still have this package installed, so all
19850                    // we need to do is clear this user's data and save that
19851                    // it is uninstalled.
19852                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19853                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19854                        return false;
19855                    }
19856                    scheduleWritePackageRestrictionsLocked(user);
19857                    return true;
19858                } else {
19859                    // We need to set it back to 'installed' so the uninstall
19860                    // broadcasts will be sent correctly.
19861                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19862                    ps.setInstalled(true, user.getIdentifier());
19863                    mSettings.writeKernelMappingLPr(ps);
19864                }
19865            } else {
19866                // This is a system app, so we assume that the
19867                // other users still have this package installed, so all
19868                // we need to do is clear this user's data and save that
19869                // it is uninstalled.
19870                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19871                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19872                    return false;
19873                }
19874                scheduleWritePackageRestrictionsLocked(user);
19875                return true;
19876            }
19877        }
19878
19879        // If we are deleting a composite package for all users, keep track
19880        // of result for each child.
19881        if (ps.childPackageNames != null && outInfo != null) {
19882            synchronized (mPackages) {
19883                final int childCount = ps.childPackageNames.size();
19884                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19885                for (int i = 0; i < childCount; i++) {
19886                    String childPackageName = ps.childPackageNames.get(i);
19887                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19888                    childInfo.removedPackage = childPackageName;
19889                    childInfo.installerPackageName = ps.installerPackageName;
19890                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19891                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19892                    if (childPs != null) {
19893                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19894                    }
19895                }
19896            }
19897        }
19898
19899        boolean ret = false;
19900        if (isSystemApp(ps)) {
19901            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19902            // When an updated system application is deleted we delete the existing resources
19903            // as well and fall back to existing code in system partition
19904            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19905        } else {
19906            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19907            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19908                    outInfo, writeSettings, replacingPackage);
19909        }
19910
19911        // Take a note whether we deleted the package for all users
19912        if (outInfo != null) {
19913            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19914            if (outInfo.removedChildPackages != null) {
19915                synchronized (mPackages) {
19916                    final int childCount = outInfo.removedChildPackages.size();
19917                    for (int i = 0; i < childCount; i++) {
19918                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19919                        if (childInfo != null) {
19920                            childInfo.removedForAllUsers = mPackages.get(
19921                                    childInfo.removedPackage) == null;
19922                        }
19923                    }
19924                }
19925            }
19926            // If we uninstalled an update to a system app there may be some
19927            // child packages that appeared as they are declared in the system
19928            // app but were not declared in the update.
19929            if (isSystemApp(ps)) {
19930                synchronized (mPackages) {
19931                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19932                    final int childCount = (updatedPs.childPackageNames != null)
19933                            ? updatedPs.childPackageNames.size() : 0;
19934                    for (int i = 0; i < childCount; i++) {
19935                        String childPackageName = updatedPs.childPackageNames.get(i);
19936                        if (outInfo.removedChildPackages == null
19937                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19938                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19939                            if (childPs == null) {
19940                                continue;
19941                            }
19942                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19943                            installRes.name = childPackageName;
19944                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19945                            installRes.pkg = mPackages.get(childPackageName);
19946                            installRes.uid = childPs.pkg.applicationInfo.uid;
19947                            if (outInfo.appearedChildPackages == null) {
19948                                outInfo.appearedChildPackages = new ArrayMap<>();
19949                            }
19950                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19951                        }
19952                    }
19953                }
19954            }
19955        }
19956
19957        return ret;
19958    }
19959
19960    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19961        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19962                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19963        for (int nextUserId : userIds) {
19964            if (DEBUG_REMOVE) {
19965                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19966            }
19967            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19968                    false /*installed*/,
19969                    true /*stopped*/,
19970                    true /*notLaunched*/,
19971                    false /*hidden*/,
19972                    false /*suspended*/,
19973                    false /*instantApp*/,
19974                    null /*lastDisableAppCaller*/,
19975                    null /*enabledComponents*/,
19976                    null /*disabledComponents*/,
19977                    ps.readUserState(nextUserId).domainVerificationStatus,
19978                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19979        }
19980        mSettings.writeKernelMappingLPr(ps);
19981    }
19982
19983    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19984            PackageRemovedInfo outInfo) {
19985        final PackageParser.Package pkg;
19986        synchronized (mPackages) {
19987            pkg = mPackages.get(ps.name);
19988        }
19989
19990        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19991                : new int[] {userId};
19992        for (int nextUserId : userIds) {
19993            if (DEBUG_REMOVE) {
19994                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19995                        + nextUserId);
19996            }
19997
19998            destroyAppDataLIF(pkg, userId,
19999                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20000            destroyAppProfilesLIF(pkg, userId);
20001            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20002            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20003            schedulePackageCleaning(ps.name, nextUserId, false);
20004            synchronized (mPackages) {
20005                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20006                    scheduleWritePackageRestrictionsLocked(nextUserId);
20007                }
20008                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20009            }
20010        }
20011
20012        if (outInfo != null) {
20013            outInfo.removedPackage = ps.name;
20014            outInfo.installerPackageName = ps.installerPackageName;
20015            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20016            outInfo.removedAppId = ps.appId;
20017            outInfo.removedUsers = userIds;
20018            outInfo.broadcastUsers = userIds;
20019        }
20020
20021        return true;
20022    }
20023
20024    private final class ClearStorageConnection implements ServiceConnection {
20025        IMediaContainerService mContainerService;
20026
20027        @Override
20028        public void onServiceConnected(ComponentName name, IBinder service) {
20029            synchronized (this) {
20030                mContainerService = IMediaContainerService.Stub
20031                        .asInterface(Binder.allowBlocking(service));
20032                notifyAll();
20033            }
20034        }
20035
20036        @Override
20037        public void onServiceDisconnected(ComponentName name) {
20038        }
20039    }
20040
20041    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20042        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20043
20044        final boolean mounted;
20045        if (Environment.isExternalStorageEmulated()) {
20046            mounted = true;
20047        } else {
20048            final String status = Environment.getExternalStorageState();
20049
20050            mounted = status.equals(Environment.MEDIA_MOUNTED)
20051                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20052        }
20053
20054        if (!mounted) {
20055            return;
20056        }
20057
20058        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20059        int[] users;
20060        if (userId == UserHandle.USER_ALL) {
20061            users = sUserManager.getUserIds();
20062        } else {
20063            users = new int[] { userId };
20064        }
20065        final ClearStorageConnection conn = new ClearStorageConnection();
20066        if (mContext.bindServiceAsUser(
20067                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20068            try {
20069                for (int curUser : users) {
20070                    long timeout = SystemClock.uptimeMillis() + 5000;
20071                    synchronized (conn) {
20072                        long now;
20073                        while (conn.mContainerService == null &&
20074                                (now = SystemClock.uptimeMillis()) < timeout) {
20075                            try {
20076                                conn.wait(timeout - now);
20077                            } catch (InterruptedException e) {
20078                            }
20079                        }
20080                    }
20081                    if (conn.mContainerService == null) {
20082                        return;
20083                    }
20084
20085                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20086                    clearDirectory(conn.mContainerService,
20087                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20088                    if (allData) {
20089                        clearDirectory(conn.mContainerService,
20090                                userEnv.buildExternalStorageAppDataDirs(packageName));
20091                        clearDirectory(conn.mContainerService,
20092                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20093                    }
20094                }
20095            } finally {
20096                mContext.unbindService(conn);
20097            }
20098        }
20099    }
20100
20101    @Override
20102    public void clearApplicationProfileData(String packageName) {
20103        enforceSystemOrRoot("Only the system can clear all profile data");
20104
20105        final PackageParser.Package pkg;
20106        synchronized (mPackages) {
20107            pkg = mPackages.get(packageName);
20108        }
20109
20110        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20111            synchronized (mInstallLock) {
20112                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20113            }
20114        }
20115    }
20116
20117    @Override
20118    public void clearApplicationUserData(final String packageName,
20119            final IPackageDataObserver observer, final int userId) {
20120        mContext.enforceCallingOrSelfPermission(
20121                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20122
20123        final int callingUid = Binder.getCallingUid();
20124        enforceCrossUserPermission(callingUid, userId,
20125                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20126
20127        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20128        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
20129            return;
20130        }
20131        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20132            throw new SecurityException("Cannot clear data for a protected package: "
20133                    + packageName);
20134        }
20135        // Queue up an async operation since the package deletion may take a little while.
20136        mHandler.post(new Runnable() {
20137            public void run() {
20138                mHandler.removeCallbacks(this);
20139                final boolean succeeded;
20140                try (PackageFreezer freezer = freezePackage(packageName,
20141                        "clearApplicationUserData")) {
20142                    synchronized (mInstallLock) {
20143                        succeeded = clearApplicationUserDataLIF(packageName, userId);
20144                    }
20145                    clearExternalStorageDataSync(packageName, userId, true);
20146                    synchronized (mPackages) {
20147                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20148                                packageName, userId);
20149                    }
20150                }
20151                if (succeeded) {
20152                    // invoke DeviceStorageMonitor's update method to clear any notifications
20153                    DeviceStorageMonitorInternal dsm = LocalServices
20154                            .getService(DeviceStorageMonitorInternal.class);
20155                    if (dsm != null) {
20156                        dsm.checkMemory();
20157                    }
20158                }
20159                if(observer != null) {
20160                    try {
20161                        observer.onRemoveCompleted(packageName, succeeded);
20162                    } catch (RemoteException e) {
20163                        Log.i(TAG, "Observer no longer exists.");
20164                    }
20165                } //end if observer
20166            } //end run
20167        });
20168    }
20169
20170    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20171        if (packageName == null) {
20172            Slog.w(TAG, "Attempt to delete null packageName.");
20173            return false;
20174        }
20175
20176        // Try finding details about the requested package
20177        PackageParser.Package pkg;
20178        synchronized (mPackages) {
20179            pkg = mPackages.get(packageName);
20180            if (pkg == null) {
20181                final PackageSetting ps = mSettings.mPackages.get(packageName);
20182                if (ps != null) {
20183                    pkg = ps.pkg;
20184                }
20185            }
20186
20187            if (pkg == null) {
20188                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20189                return false;
20190            }
20191
20192            PackageSetting ps = (PackageSetting) pkg.mExtras;
20193            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20194        }
20195
20196        clearAppDataLIF(pkg, userId,
20197                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20198
20199        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20200        removeKeystoreDataIfNeeded(userId, appId);
20201
20202        UserManagerInternal umInternal = getUserManagerInternal();
20203        final int flags;
20204        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20205            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20206        } else if (umInternal.isUserRunning(userId)) {
20207            flags = StorageManager.FLAG_STORAGE_DE;
20208        } else {
20209            flags = 0;
20210        }
20211        prepareAppDataContentsLIF(pkg, userId, flags);
20212
20213        return true;
20214    }
20215
20216    /**
20217     * Reverts user permission state changes (permissions and flags) in
20218     * all packages for a given user.
20219     *
20220     * @param userId The device user for which to do a reset.
20221     */
20222    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20223        final int packageCount = mPackages.size();
20224        for (int i = 0; i < packageCount; i++) {
20225            PackageParser.Package pkg = mPackages.valueAt(i);
20226            PackageSetting ps = (PackageSetting) pkg.mExtras;
20227            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20228        }
20229    }
20230
20231    private void resetNetworkPolicies(int userId) {
20232        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20233    }
20234
20235    /**
20236     * Reverts user permission state changes (permissions and flags).
20237     *
20238     * @param ps The package for which to reset.
20239     * @param userId The device user for which to do a reset.
20240     */
20241    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20242            final PackageSetting ps, final int userId) {
20243        if (ps.pkg == null) {
20244            return;
20245        }
20246
20247        // These are flags that can change base on user actions.
20248        final int userSettableMask = FLAG_PERMISSION_USER_SET
20249                | FLAG_PERMISSION_USER_FIXED
20250                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20251                | FLAG_PERMISSION_REVIEW_REQUIRED;
20252
20253        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20254                | FLAG_PERMISSION_POLICY_FIXED;
20255
20256        boolean writeInstallPermissions = false;
20257        boolean writeRuntimePermissions = false;
20258
20259        final int permissionCount = ps.pkg.requestedPermissions.size();
20260        for (int i = 0; i < permissionCount; i++) {
20261            String permission = ps.pkg.requestedPermissions.get(i);
20262
20263            BasePermission bp = mSettings.mPermissions.get(permission);
20264            if (bp == null) {
20265                continue;
20266            }
20267
20268            // If shared user we just reset the state to which only this app contributed.
20269            if (ps.sharedUser != null) {
20270                boolean used = false;
20271                final int packageCount = ps.sharedUser.packages.size();
20272                for (int j = 0; j < packageCount; j++) {
20273                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20274                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20275                            && pkg.pkg.requestedPermissions.contains(permission)) {
20276                        used = true;
20277                        break;
20278                    }
20279                }
20280                if (used) {
20281                    continue;
20282                }
20283            }
20284
20285            PermissionsState permissionsState = ps.getPermissionsState();
20286
20287            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20288
20289            // Always clear the user settable flags.
20290            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20291                    bp.name) != null;
20292            // If permission review is enabled and this is a legacy app, mark the
20293            // permission as requiring a review as this is the initial state.
20294            int flags = 0;
20295            if (mPermissionReviewRequired
20296                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20297                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20298            }
20299            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20300                if (hasInstallState) {
20301                    writeInstallPermissions = true;
20302                } else {
20303                    writeRuntimePermissions = true;
20304                }
20305            }
20306
20307            // Below is only runtime permission handling.
20308            if (!bp.isRuntime()) {
20309                continue;
20310            }
20311
20312            // Never clobber system or policy.
20313            if ((oldFlags & policyOrSystemFlags) != 0) {
20314                continue;
20315            }
20316
20317            // If this permission was granted by default, make sure it is.
20318            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20319                if (permissionsState.grantRuntimePermission(bp, userId)
20320                        != PERMISSION_OPERATION_FAILURE) {
20321                    writeRuntimePermissions = true;
20322                }
20323            // If permission review is enabled the permissions for a legacy apps
20324            // are represented as constantly granted runtime ones, so don't revoke.
20325            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20326                // Otherwise, reset the permission.
20327                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20328                switch (revokeResult) {
20329                    case PERMISSION_OPERATION_SUCCESS:
20330                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20331                        writeRuntimePermissions = true;
20332                        final int appId = ps.appId;
20333                        mHandler.post(new Runnable() {
20334                            @Override
20335                            public void run() {
20336                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20337                            }
20338                        });
20339                    } break;
20340                }
20341            }
20342        }
20343
20344        // Synchronously write as we are taking permissions away.
20345        if (writeRuntimePermissions) {
20346            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20347        }
20348
20349        // Synchronously write as we are taking permissions away.
20350        if (writeInstallPermissions) {
20351            mSettings.writeLPr();
20352        }
20353    }
20354
20355    /**
20356     * Remove entries from the keystore daemon. Will only remove it if the
20357     * {@code appId} is valid.
20358     */
20359    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20360        if (appId < 0) {
20361            return;
20362        }
20363
20364        final KeyStore keyStore = KeyStore.getInstance();
20365        if (keyStore != null) {
20366            if (userId == UserHandle.USER_ALL) {
20367                for (final int individual : sUserManager.getUserIds()) {
20368                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20369                }
20370            } else {
20371                keyStore.clearUid(UserHandle.getUid(userId, appId));
20372            }
20373        } else {
20374            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20375        }
20376    }
20377
20378    @Override
20379    public void deleteApplicationCacheFiles(final String packageName,
20380            final IPackageDataObserver observer) {
20381        final int userId = UserHandle.getCallingUserId();
20382        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20383    }
20384
20385    @Override
20386    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20387            final IPackageDataObserver observer) {
20388        final int callingUid = Binder.getCallingUid();
20389        mContext.enforceCallingOrSelfPermission(
20390                android.Manifest.permission.DELETE_CACHE_FILES, null);
20391        enforceCrossUserPermission(callingUid, userId,
20392                /* requireFullPermission= */ true, /* checkShell= */ false,
20393                "delete application cache files");
20394        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20395                android.Manifest.permission.ACCESS_INSTANT_APPS);
20396
20397        final PackageParser.Package pkg;
20398        synchronized (mPackages) {
20399            pkg = mPackages.get(packageName);
20400        }
20401
20402        // Queue up an async operation since the package deletion may take a little while.
20403        mHandler.post(new Runnable() {
20404            public void run() {
20405                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20406                boolean doClearData = true;
20407                if (ps != null) {
20408                    final boolean targetIsInstantApp =
20409                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20410                    doClearData = !targetIsInstantApp
20411                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20412                }
20413                if (doClearData) {
20414                    synchronized (mInstallLock) {
20415                        final int flags = StorageManager.FLAG_STORAGE_DE
20416                                | StorageManager.FLAG_STORAGE_CE;
20417                        // We're only clearing cache files, so we don't care if the
20418                        // app is unfrozen and still able to run
20419                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20420                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20421                    }
20422                    clearExternalStorageDataSync(packageName, userId, false);
20423                }
20424                if (observer != null) {
20425                    try {
20426                        observer.onRemoveCompleted(packageName, true);
20427                    } catch (RemoteException e) {
20428                        Log.i(TAG, "Observer no longer exists.");
20429                    }
20430                }
20431            }
20432        });
20433    }
20434
20435    @Override
20436    public void getPackageSizeInfo(final String packageName, int userHandle,
20437            final IPackageStatsObserver observer) {
20438        throw new UnsupportedOperationException(
20439                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20440    }
20441
20442    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20443        final PackageSetting ps;
20444        synchronized (mPackages) {
20445            ps = mSettings.mPackages.get(packageName);
20446            if (ps == null) {
20447                Slog.w(TAG, "Failed to find settings for " + packageName);
20448                return false;
20449            }
20450        }
20451
20452        final String[] packageNames = { packageName };
20453        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20454        final String[] codePaths = { ps.codePathString };
20455
20456        try {
20457            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20458                    ps.appId, ceDataInodes, codePaths, stats);
20459
20460            // For now, ignore code size of packages on system partition
20461            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20462                stats.codeSize = 0;
20463            }
20464
20465            // External clients expect these to be tracked separately
20466            stats.dataSize -= stats.cacheSize;
20467
20468        } catch (InstallerException e) {
20469            Slog.w(TAG, String.valueOf(e));
20470            return false;
20471        }
20472
20473        return true;
20474    }
20475
20476    private int getUidTargetSdkVersionLockedLPr(int uid) {
20477        Object obj = mSettings.getUserIdLPr(uid);
20478        if (obj instanceof SharedUserSetting) {
20479            final SharedUserSetting sus = (SharedUserSetting) obj;
20480            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20481            final Iterator<PackageSetting> it = sus.packages.iterator();
20482            while (it.hasNext()) {
20483                final PackageSetting ps = it.next();
20484                if (ps.pkg != null) {
20485                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20486                    if (v < vers) vers = v;
20487                }
20488            }
20489            return vers;
20490        } else if (obj instanceof PackageSetting) {
20491            final PackageSetting ps = (PackageSetting) obj;
20492            if (ps.pkg != null) {
20493                return ps.pkg.applicationInfo.targetSdkVersion;
20494            }
20495        }
20496        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20497    }
20498
20499    @Override
20500    public void addPreferredActivity(IntentFilter filter, int match,
20501            ComponentName[] set, ComponentName activity, int userId) {
20502        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20503                "Adding preferred");
20504    }
20505
20506    private void addPreferredActivityInternal(IntentFilter filter, int match,
20507            ComponentName[] set, ComponentName activity, boolean always, int userId,
20508            String opname) {
20509        // writer
20510        int callingUid = Binder.getCallingUid();
20511        enforceCrossUserPermission(callingUid, userId,
20512                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20513        if (filter.countActions() == 0) {
20514            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20515            return;
20516        }
20517        synchronized (mPackages) {
20518            if (mContext.checkCallingOrSelfPermission(
20519                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20520                    != PackageManager.PERMISSION_GRANTED) {
20521                if (getUidTargetSdkVersionLockedLPr(callingUid)
20522                        < Build.VERSION_CODES.FROYO) {
20523                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20524                            + callingUid);
20525                    return;
20526                }
20527                mContext.enforceCallingOrSelfPermission(
20528                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20529            }
20530
20531            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20532            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20533                    + userId + ":");
20534            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20535            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20536            scheduleWritePackageRestrictionsLocked(userId);
20537            postPreferredActivityChangedBroadcast(userId);
20538        }
20539    }
20540
20541    private void postPreferredActivityChangedBroadcast(int userId) {
20542        mHandler.post(() -> {
20543            final IActivityManager am = ActivityManager.getService();
20544            if (am == null) {
20545                return;
20546            }
20547
20548            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20549            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20550            try {
20551                am.broadcastIntent(null, intent, null, null,
20552                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20553                        null, false, false, userId);
20554            } catch (RemoteException e) {
20555            }
20556        });
20557    }
20558
20559    @Override
20560    public void replacePreferredActivity(IntentFilter filter, int match,
20561            ComponentName[] set, ComponentName activity, int userId) {
20562        if (filter.countActions() != 1) {
20563            throw new IllegalArgumentException(
20564                    "replacePreferredActivity expects filter to have only 1 action.");
20565        }
20566        if (filter.countDataAuthorities() != 0
20567                || filter.countDataPaths() != 0
20568                || filter.countDataSchemes() > 1
20569                || filter.countDataTypes() != 0) {
20570            throw new IllegalArgumentException(
20571                    "replacePreferredActivity expects filter to have no data authorities, " +
20572                    "paths, or types; and at most one scheme.");
20573        }
20574
20575        final int callingUid = Binder.getCallingUid();
20576        enforceCrossUserPermission(callingUid, userId,
20577                true /* requireFullPermission */, false /* checkShell */,
20578                "replace preferred activity");
20579        synchronized (mPackages) {
20580            if (mContext.checkCallingOrSelfPermission(
20581                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20582                    != PackageManager.PERMISSION_GRANTED) {
20583                if (getUidTargetSdkVersionLockedLPr(callingUid)
20584                        < Build.VERSION_CODES.FROYO) {
20585                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20586                            + Binder.getCallingUid());
20587                    return;
20588                }
20589                mContext.enforceCallingOrSelfPermission(
20590                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20591            }
20592
20593            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20594            if (pir != null) {
20595                // Get all of the existing entries that exactly match this filter.
20596                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20597                if (existing != null && existing.size() == 1) {
20598                    PreferredActivity cur = existing.get(0);
20599                    if (DEBUG_PREFERRED) {
20600                        Slog.i(TAG, "Checking replace of preferred:");
20601                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20602                        if (!cur.mPref.mAlways) {
20603                            Slog.i(TAG, "  -- CUR; not mAlways!");
20604                        } else {
20605                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20606                            Slog.i(TAG, "  -- CUR: mSet="
20607                                    + Arrays.toString(cur.mPref.mSetComponents));
20608                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20609                            Slog.i(TAG, "  -- NEW: mMatch="
20610                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20611                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20612                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20613                        }
20614                    }
20615                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20616                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20617                            && cur.mPref.sameSet(set)) {
20618                        // Setting the preferred activity to what it happens to be already
20619                        if (DEBUG_PREFERRED) {
20620                            Slog.i(TAG, "Replacing with same preferred activity "
20621                                    + cur.mPref.mShortComponent + " for user "
20622                                    + userId + ":");
20623                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20624                        }
20625                        return;
20626                    }
20627                }
20628
20629                if (existing != null) {
20630                    if (DEBUG_PREFERRED) {
20631                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20632                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20633                    }
20634                    for (int i = 0; i < existing.size(); i++) {
20635                        PreferredActivity pa = existing.get(i);
20636                        if (DEBUG_PREFERRED) {
20637                            Slog.i(TAG, "Removing existing preferred activity "
20638                                    + pa.mPref.mComponent + ":");
20639                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20640                        }
20641                        pir.removeFilter(pa);
20642                    }
20643                }
20644            }
20645            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20646                    "Replacing preferred");
20647        }
20648    }
20649
20650    @Override
20651    public void clearPackagePreferredActivities(String packageName) {
20652        final int callingUid = Binder.getCallingUid();
20653        if (getInstantAppPackageName(callingUid) != null) {
20654            return;
20655        }
20656        // writer
20657        synchronized (mPackages) {
20658            PackageParser.Package pkg = mPackages.get(packageName);
20659            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20660                if (mContext.checkCallingOrSelfPermission(
20661                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20662                        != PackageManager.PERMISSION_GRANTED) {
20663                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20664                            < Build.VERSION_CODES.FROYO) {
20665                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20666                                + callingUid);
20667                        return;
20668                    }
20669                    mContext.enforceCallingOrSelfPermission(
20670                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20671                }
20672            }
20673            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20674            if (ps != null
20675                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20676                return;
20677            }
20678            int user = UserHandle.getCallingUserId();
20679            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20680                scheduleWritePackageRestrictionsLocked(user);
20681            }
20682        }
20683    }
20684
20685    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20686    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20687        ArrayList<PreferredActivity> removed = null;
20688        boolean changed = false;
20689        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20690            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20691            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20692            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20693                continue;
20694            }
20695            Iterator<PreferredActivity> it = pir.filterIterator();
20696            while (it.hasNext()) {
20697                PreferredActivity pa = it.next();
20698                // Mark entry for removal only if it matches the package name
20699                // and the entry is of type "always".
20700                if (packageName == null ||
20701                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20702                                && pa.mPref.mAlways)) {
20703                    if (removed == null) {
20704                        removed = new ArrayList<PreferredActivity>();
20705                    }
20706                    removed.add(pa);
20707                }
20708            }
20709            if (removed != null) {
20710                for (int j=0; j<removed.size(); j++) {
20711                    PreferredActivity pa = removed.get(j);
20712                    pir.removeFilter(pa);
20713                }
20714                changed = true;
20715            }
20716        }
20717        if (changed) {
20718            postPreferredActivityChangedBroadcast(userId);
20719        }
20720        return changed;
20721    }
20722
20723    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20724    private void clearIntentFilterVerificationsLPw(int userId) {
20725        final int packageCount = mPackages.size();
20726        for (int i = 0; i < packageCount; i++) {
20727            PackageParser.Package pkg = mPackages.valueAt(i);
20728            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20729        }
20730    }
20731
20732    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20733    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20734        if (userId == UserHandle.USER_ALL) {
20735            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20736                    sUserManager.getUserIds())) {
20737                for (int oneUserId : sUserManager.getUserIds()) {
20738                    scheduleWritePackageRestrictionsLocked(oneUserId);
20739                }
20740            }
20741        } else {
20742            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20743                scheduleWritePackageRestrictionsLocked(userId);
20744            }
20745        }
20746    }
20747
20748    /** Clears state for all users, and touches intent filter verification policy */
20749    void clearDefaultBrowserIfNeeded(String packageName) {
20750        for (int oneUserId : sUserManager.getUserIds()) {
20751            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20752        }
20753    }
20754
20755    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20756        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20757        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20758            if (packageName.equals(defaultBrowserPackageName)) {
20759                setDefaultBrowserPackageName(null, userId);
20760            }
20761        }
20762    }
20763
20764    @Override
20765    public void resetApplicationPreferences(int userId) {
20766        mContext.enforceCallingOrSelfPermission(
20767                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20768        final long identity = Binder.clearCallingIdentity();
20769        // writer
20770        try {
20771            synchronized (mPackages) {
20772                clearPackagePreferredActivitiesLPw(null, userId);
20773                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20774                // TODO: We have to reset the default SMS and Phone. This requires
20775                // significant refactoring to keep all default apps in the package
20776                // manager (cleaner but more work) or have the services provide
20777                // callbacks to the package manager to request a default app reset.
20778                applyFactoryDefaultBrowserLPw(userId);
20779                clearIntentFilterVerificationsLPw(userId);
20780                primeDomainVerificationsLPw(userId);
20781                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20782                scheduleWritePackageRestrictionsLocked(userId);
20783            }
20784            resetNetworkPolicies(userId);
20785        } finally {
20786            Binder.restoreCallingIdentity(identity);
20787        }
20788    }
20789
20790    @Override
20791    public int getPreferredActivities(List<IntentFilter> outFilters,
20792            List<ComponentName> outActivities, String packageName) {
20793        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20794            return 0;
20795        }
20796        int num = 0;
20797        final int userId = UserHandle.getCallingUserId();
20798        // reader
20799        synchronized (mPackages) {
20800            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20801            if (pir != null) {
20802                final Iterator<PreferredActivity> it = pir.filterIterator();
20803                while (it.hasNext()) {
20804                    final PreferredActivity pa = it.next();
20805                    if (packageName == null
20806                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20807                                    && pa.mPref.mAlways)) {
20808                        if (outFilters != null) {
20809                            outFilters.add(new IntentFilter(pa));
20810                        }
20811                        if (outActivities != null) {
20812                            outActivities.add(pa.mPref.mComponent);
20813                        }
20814                    }
20815                }
20816            }
20817        }
20818
20819        return num;
20820    }
20821
20822    @Override
20823    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20824            int userId) {
20825        int callingUid = Binder.getCallingUid();
20826        if (callingUid != Process.SYSTEM_UID) {
20827            throw new SecurityException(
20828                    "addPersistentPreferredActivity can only be run by the system");
20829        }
20830        if (filter.countActions() == 0) {
20831            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20832            return;
20833        }
20834        synchronized (mPackages) {
20835            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20836                    ":");
20837            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20838            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20839                    new PersistentPreferredActivity(filter, activity));
20840            scheduleWritePackageRestrictionsLocked(userId);
20841            postPreferredActivityChangedBroadcast(userId);
20842        }
20843    }
20844
20845    @Override
20846    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20847        int callingUid = Binder.getCallingUid();
20848        if (callingUid != Process.SYSTEM_UID) {
20849            throw new SecurityException(
20850                    "clearPackagePersistentPreferredActivities can only be run by the system");
20851        }
20852        ArrayList<PersistentPreferredActivity> removed = null;
20853        boolean changed = false;
20854        synchronized (mPackages) {
20855            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20856                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20857                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20858                        .valueAt(i);
20859                if (userId != thisUserId) {
20860                    continue;
20861                }
20862                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20863                while (it.hasNext()) {
20864                    PersistentPreferredActivity ppa = it.next();
20865                    // Mark entry for removal only if it matches the package name.
20866                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20867                        if (removed == null) {
20868                            removed = new ArrayList<PersistentPreferredActivity>();
20869                        }
20870                        removed.add(ppa);
20871                    }
20872                }
20873                if (removed != null) {
20874                    for (int j=0; j<removed.size(); j++) {
20875                        PersistentPreferredActivity ppa = removed.get(j);
20876                        ppir.removeFilter(ppa);
20877                    }
20878                    changed = true;
20879                }
20880            }
20881
20882            if (changed) {
20883                scheduleWritePackageRestrictionsLocked(userId);
20884                postPreferredActivityChangedBroadcast(userId);
20885            }
20886        }
20887    }
20888
20889    /**
20890     * Common machinery for picking apart a restored XML blob and passing
20891     * it to a caller-supplied functor to be applied to the running system.
20892     */
20893    private void restoreFromXml(XmlPullParser parser, int userId,
20894            String expectedStartTag, BlobXmlRestorer functor)
20895            throws IOException, XmlPullParserException {
20896        int type;
20897        while ((type = parser.next()) != XmlPullParser.START_TAG
20898                && type != XmlPullParser.END_DOCUMENT) {
20899        }
20900        if (type != XmlPullParser.START_TAG) {
20901            // oops didn't find a start tag?!
20902            if (DEBUG_BACKUP) {
20903                Slog.e(TAG, "Didn't find start tag during restore");
20904            }
20905            return;
20906        }
20907Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20908        // this is supposed to be TAG_PREFERRED_BACKUP
20909        if (!expectedStartTag.equals(parser.getName())) {
20910            if (DEBUG_BACKUP) {
20911                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20912            }
20913            return;
20914        }
20915
20916        // skip interfering stuff, then we're aligned with the backing implementation
20917        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20918Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20919        functor.apply(parser, userId);
20920    }
20921
20922    private interface BlobXmlRestorer {
20923        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20924    }
20925
20926    /**
20927     * Non-Binder method, support for the backup/restore mechanism: write the
20928     * full set of preferred activities in its canonical XML format.  Returns the
20929     * XML output as a byte array, or null if there is none.
20930     */
20931    @Override
20932    public byte[] getPreferredActivityBackup(int userId) {
20933        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20934            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20935        }
20936
20937        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20938        try {
20939            final XmlSerializer serializer = new FastXmlSerializer();
20940            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20941            serializer.startDocument(null, true);
20942            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20943
20944            synchronized (mPackages) {
20945                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20946            }
20947
20948            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20949            serializer.endDocument();
20950            serializer.flush();
20951        } catch (Exception e) {
20952            if (DEBUG_BACKUP) {
20953                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20954            }
20955            return null;
20956        }
20957
20958        return dataStream.toByteArray();
20959    }
20960
20961    @Override
20962    public void restorePreferredActivities(byte[] backup, int userId) {
20963        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20964            throw new SecurityException("Only the system may call restorePreferredActivities()");
20965        }
20966
20967        try {
20968            final XmlPullParser parser = Xml.newPullParser();
20969            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20970            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20971                    new BlobXmlRestorer() {
20972                        @Override
20973                        public void apply(XmlPullParser parser, int userId)
20974                                throws XmlPullParserException, IOException {
20975                            synchronized (mPackages) {
20976                                mSettings.readPreferredActivitiesLPw(parser, userId);
20977                            }
20978                        }
20979                    } );
20980        } catch (Exception e) {
20981            if (DEBUG_BACKUP) {
20982                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20983            }
20984        }
20985    }
20986
20987    /**
20988     * Non-Binder method, support for the backup/restore mechanism: write the
20989     * default browser (etc) settings in its canonical XML format.  Returns the default
20990     * browser XML representation as a byte array, or null if there is none.
20991     */
20992    @Override
20993    public byte[] getDefaultAppsBackup(int userId) {
20994        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20995            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20996        }
20997
20998        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20999        try {
21000            final XmlSerializer serializer = new FastXmlSerializer();
21001            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21002            serializer.startDocument(null, true);
21003            serializer.startTag(null, TAG_DEFAULT_APPS);
21004
21005            synchronized (mPackages) {
21006                mSettings.writeDefaultAppsLPr(serializer, userId);
21007            }
21008
21009            serializer.endTag(null, TAG_DEFAULT_APPS);
21010            serializer.endDocument();
21011            serializer.flush();
21012        } catch (Exception e) {
21013            if (DEBUG_BACKUP) {
21014                Slog.e(TAG, "Unable to write default apps for backup", e);
21015            }
21016            return null;
21017        }
21018
21019        return dataStream.toByteArray();
21020    }
21021
21022    @Override
21023    public void restoreDefaultApps(byte[] backup, int userId) {
21024        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21025            throw new SecurityException("Only the system may call restoreDefaultApps()");
21026        }
21027
21028        try {
21029            final XmlPullParser parser = Xml.newPullParser();
21030            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21031            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21032                    new BlobXmlRestorer() {
21033                        @Override
21034                        public void apply(XmlPullParser parser, int userId)
21035                                throws XmlPullParserException, IOException {
21036                            synchronized (mPackages) {
21037                                mSettings.readDefaultAppsLPw(parser, userId);
21038                            }
21039                        }
21040                    } );
21041        } catch (Exception e) {
21042            if (DEBUG_BACKUP) {
21043                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21044            }
21045        }
21046    }
21047
21048    @Override
21049    public byte[] getIntentFilterVerificationBackup(int userId) {
21050        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21051            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21052        }
21053
21054        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21055        try {
21056            final XmlSerializer serializer = new FastXmlSerializer();
21057            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21058            serializer.startDocument(null, true);
21059            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21060
21061            synchronized (mPackages) {
21062                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21063            }
21064
21065            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21066            serializer.endDocument();
21067            serializer.flush();
21068        } catch (Exception e) {
21069            if (DEBUG_BACKUP) {
21070                Slog.e(TAG, "Unable to write default apps for backup", e);
21071            }
21072            return null;
21073        }
21074
21075        return dataStream.toByteArray();
21076    }
21077
21078    @Override
21079    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21080        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21081            throw new SecurityException("Only the system may call restorePreferredActivities()");
21082        }
21083
21084        try {
21085            final XmlPullParser parser = Xml.newPullParser();
21086            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21087            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21088                    new BlobXmlRestorer() {
21089                        @Override
21090                        public void apply(XmlPullParser parser, int userId)
21091                                throws XmlPullParserException, IOException {
21092                            synchronized (mPackages) {
21093                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21094                                mSettings.writeLPr();
21095                            }
21096                        }
21097                    } );
21098        } catch (Exception e) {
21099            if (DEBUG_BACKUP) {
21100                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21101            }
21102        }
21103    }
21104
21105    @Override
21106    public byte[] getPermissionGrantBackup(int userId) {
21107        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21108            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21109        }
21110
21111        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21112        try {
21113            final XmlSerializer serializer = new FastXmlSerializer();
21114            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21115            serializer.startDocument(null, true);
21116            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21117
21118            synchronized (mPackages) {
21119                serializeRuntimePermissionGrantsLPr(serializer, userId);
21120            }
21121
21122            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21123            serializer.endDocument();
21124            serializer.flush();
21125        } catch (Exception e) {
21126            if (DEBUG_BACKUP) {
21127                Slog.e(TAG, "Unable to write default apps for backup", e);
21128            }
21129            return null;
21130        }
21131
21132        return dataStream.toByteArray();
21133    }
21134
21135    @Override
21136    public void restorePermissionGrants(byte[] backup, int userId) {
21137        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21138            throw new SecurityException("Only the system may call restorePermissionGrants()");
21139        }
21140
21141        try {
21142            final XmlPullParser parser = Xml.newPullParser();
21143            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21144            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21145                    new BlobXmlRestorer() {
21146                        @Override
21147                        public void apply(XmlPullParser parser, int userId)
21148                                throws XmlPullParserException, IOException {
21149                            synchronized (mPackages) {
21150                                processRestoredPermissionGrantsLPr(parser, userId);
21151                            }
21152                        }
21153                    } );
21154        } catch (Exception e) {
21155            if (DEBUG_BACKUP) {
21156                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21157            }
21158        }
21159    }
21160
21161    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21162            throws IOException {
21163        serializer.startTag(null, TAG_ALL_GRANTS);
21164
21165        final int N = mSettings.mPackages.size();
21166        for (int i = 0; i < N; i++) {
21167            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21168            boolean pkgGrantsKnown = false;
21169
21170            PermissionsState packagePerms = ps.getPermissionsState();
21171
21172            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21173                final int grantFlags = state.getFlags();
21174                // only look at grants that are not system/policy fixed
21175                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21176                    final boolean isGranted = state.isGranted();
21177                    // And only back up the user-twiddled state bits
21178                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21179                        final String packageName = mSettings.mPackages.keyAt(i);
21180                        if (!pkgGrantsKnown) {
21181                            serializer.startTag(null, TAG_GRANT);
21182                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21183                            pkgGrantsKnown = true;
21184                        }
21185
21186                        final boolean userSet =
21187                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21188                        final boolean userFixed =
21189                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21190                        final boolean revoke =
21191                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21192
21193                        serializer.startTag(null, TAG_PERMISSION);
21194                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21195                        if (isGranted) {
21196                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21197                        }
21198                        if (userSet) {
21199                            serializer.attribute(null, ATTR_USER_SET, "true");
21200                        }
21201                        if (userFixed) {
21202                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21203                        }
21204                        if (revoke) {
21205                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21206                        }
21207                        serializer.endTag(null, TAG_PERMISSION);
21208                    }
21209                }
21210            }
21211
21212            if (pkgGrantsKnown) {
21213                serializer.endTag(null, TAG_GRANT);
21214            }
21215        }
21216
21217        serializer.endTag(null, TAG_ALL_GRANTS);
21218    }
21219
21220    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21221            throws XmlPullParserException, IOException {
21222        String pkgName = null;
21223        int outerDepth = parser.getDepth();
21224        int type;
21225        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21226                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21227            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21228                continue;
21229            }
21230
21231            final String tagName = parser.getName();
21232            if (tagName.equals(TAG_GRANT)) {
21233                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21234                if (DEBUG_BACKUP) {
21235                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21236                }
21237            } else if (tagName.equals(TAG_PERMISSION)) {
21238
21239                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21240                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21241
21242                int newFlagSet = 0;
21243                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21244                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21245                }
21246                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21247                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21248                }
21249                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21250                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21251                }
21252                if (DEBUG_BACKUP) {
21253                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21254                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21255                }
21256                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21257                if (ps != null) {
21258                    // Already installed so we apply the grant immediately
21259                    if (DEBUG_BACKUP) {
21260                        Slog.v(TAG, "        + already installed; applying");
21261                    }
21262                    PermissionsState perms = ps.getPermissionsState();
21263                    BasePermission bp = mSettings.mPermissions.get(permName);
21264                    if (bp != null) {
21265                        if (isGranted) {
21266                            perms.grantRuntimePermission(bp, userId);
21267                        }
21268                        if (newFlagSet != 0) {
21269                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21270                        }
21271                    }
21272                } else {
21273                    // Need to wait for post-restore install to apply the grant
21274                    if (DEBUG_BACKUP) {
21275                        Slog.v(TAG, "        - not yet installed; saving for later");
21276                    }
21277                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21278                            isGranted, newFlagSet, userId);
21279                }
21280            } else {
21281                PackageManagerService.reportSettingsProblem(Log.WARN,
21282                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21283                XmlUtils.skipCurrentTag(parser);
21284            }
21285        }
21286
21287        scheduleWriteSettingsLocked();
21288        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21289    }
21290
21291    @Override
21292    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21293            int sourceUserId, int targetUserId, int flags) {
21294        mContext.enforceCallingOrSelfPermission(
21295                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21296        int callingUid = Binder.getCallingUid();
21297        enforceOwnerRights(ownerPackage, callingUid);
21298        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21299        if (intentFilter.countActions() == 0) {
21300            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21301            return;
21302        }
21303        synchronized (mPackages) {
21304            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21305                    ownerPackage, targetUserId, flags);
21306            CrossProfileIntentResolver resolver =
21307                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21308            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21309            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21310            if (existing != null) {
21311                int size = existing.size();
21312                for (int i = 0; i < size; i++) {
21313                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21314                        return;
21315                    }
21316                }
21317            }
21318            resolver.addFilter(newFilter);
21319            scheduleWritePackageRestrictionsLocked(sourceUserId);
21320        }
21321    }
21322
21323    @Override
21324    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21325        mContext.enforceCallingOrSelfPermission(
21326                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21327        final int callingUid = Binder.getCallingUid();
21328        enforceOwnerRights(ownerPackage, callingUid);
21329        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21330        synchronized (mPackages) {
21331            CrossProfileIntentResolver resolver =
21332                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21333            ArraySet<CrossProfileIntentFilter> set =
21334                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21335            for (CrossProfileIntentFilter filter : set) {
21336                if (filter.getOwnerPackage().equals(ownerPackage)) {
21337                    resolver.removeFilter(filter);
21338                }
21339            }
21340            scheduleWritePackageRestrictionsLocked(sourceUserId);
21341        }
21342    }
21343
21344    // Enforcing that callingUid is owning pkg on userId
21345    private void enforceOwnerRights(String pkg, int callingUid) {
21346        // The system owns everything.
21347        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21348            return;
21349        }
21350        final int callingUserId = UserHandle.getUserId(callingUid);
21351        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21352        if (pi == null) {
21353            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21354                    + callingUserId);
21355        }
21356        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21357            throw new SecurityException("Calling uid " + callingUid
21358                    + " does not own package " + pkg);
21359        }
21360    }
21361
21362    @Override
21363    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21364        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21365            return null;
21366        }
21367        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21368    }
21369
21370    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21371        UserManagerService ums = UserManagerService.getInstance();
21372        if (ums != null) {
21373            final UserInfo parent = ums.getProfileParent(userId);
21374            final int launcherUid = (parent != null) ? parent.id : userId;
21375            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21376            if (launcherComponent != null) {
21377                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21378                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21379                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21380                        .setPackage(launcherComponent.getPackageName());
21381                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21382            }
21383        }
21384    }
21385
21386    /**
21387     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21388     * then reports the most likely home activity or null if there are more than one.
21389     */
21390    private ComponentName getDefaultHomeActivity(int userId) {
21391        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21392        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21393        if (cn != null) {
21394            return cn;
21395        }
21396
21397        // Find the launcher with the highest priority and return that component if there are no
21398        // other home activity with the same priority.
21399        int lastPriority = Integer.MIN_VALUE;
21400        ComponentName lastComponent = null;
21401        final int size = allHomeCandidates.size();
21402        for (int i = 0; i < size; i++) {
21403            final ResolveInfo ri = allHomeCandidates.get(i);
21404            if (ri.priority > lastPriority) {
21405                lastComponent = ri.activityInfo.getComponentName();
21406                lastPriority = ri.priority;
21407            } else if (ri.priority == lastPriority) {
21408                // Two components found with same priority.
21409                lastComponent = null;
21410            }
21411        }
21412        return lastComponent;
21413    }
21414
21415    private Intent getHomeIntent() {
21416        Intent intent = new Intent(Intent.ACTION_MAIN);
21417        intent.addCategory(Intent.CATEGORY_HOME);
21418        intent.addCategory(Intent.CATEGORY_DEFAULT);
21419        return intent;
21420    }
21421
21422    private IntentFilter getHomeFilter() {
21423        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21424        filter.addCategory(Intent.CATEGORY_HOME);
21425        filter.addCategory(Intent.CATEGORY_DEFAULT);
21426        return filter;
21427    }
21428
21429    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21430            int userId) {
21431        Intent intent  = getHomeIntent();
21432        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21433                PackageManager.GET_META_DATA, userId);
21434        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21435                true, false, false, userId);
21436
21437        allHomeCandidates.clear();
21438        if (list != null) {
21439            for (ResolveInfo ri : list) {
21440                allHomeCandidates.add(ri);
21441            }
21442        }
21443        return (preferred == null || preferred.activityInfo == null)
21444                ? null
21445                : new ComponentName(preferred.activityInfo.packageName,
21446                        preferred.activityInfo.name);
21447    }
21448
21449    @Override
21450    public void setHomeActivity(ComponentName comp, int userId) {
21451        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21452            return;
21453        }
21454        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21455        getHomeActivitiesAsUser(homeActivities, userId);
21456
21457        boolean found = false;
21458
21459        final int size = homeActivities.size();
21460        final ComponentName[] set = new ComponentName[size];
21461        for (int i = 0; i < size; i++) {
21462            final ResolveInfo candidate = homeActivities.get(i);
21463            final ActivityInfo info = candidate.activityInfo;
21464            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21465            set[i] = activityName;
21466            if (!found && activityName.equals(comp)) {
21467                found = true;
21468            }
21469        }
21470        if (!found) {
21471            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21472                    + userId);
21473        }
21474        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21475                set, comp, userId);
21476    }
21477
21478    private @Nullable String getSetupWizardPackageName() {
21479        final Intent intent = new Intent(Intent.ACTION_MAIN);
21480        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21481
21482        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21483                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21484                        | MATCH_DISABLED_COMPONENTS,
21485                UserHandle.myUserId());
21486        if (matches.size() == 1) {
21487            return matches.get(0).getComponentInfo().packageName;
21488        } else {
21489            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21490                    + ": matches=" + matches);
21491            return null;
21492        }
21493    }
21494
21495    private @Nullable String getStorageManagerPackageName() {
21496        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21497
21498        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21499                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21500                        | MATCH_DISABLED_COMPONENTS,
21501                UserHandle.myUserId());
21502        if (matches.size() == 1) {
21503            return matches.get(0).getComponentInfo().packageName;
21504        } else {
21505            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21506                    + matches.size() + ": matches=" + matches);
21507            return null;
21508        }
21509    }
21510
21511    @Override
21512    public void setApplicationEnabledSetting(String appPackageName,
21513            int newState, int flags, int userId, String callingPackage) {
21514        if (!sUserManager.exists(userId)) return;
21515        if (callingPackage == null) {
21516            callingPackage = Integer.toString(Binder.getCallingUid());
21517        }
21518        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21519    }
21520
21521    @Override
21522    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21523        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21524        synchronized (mPackages) {
21525            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21526            if (pkgSetting != null) {
21527                pkgSetting.setUpdateAvailable(updateAvailable);
21528            }
21529        }
21530    }
21531
21532    @Override
21533    public void setComponentEnabledSetting(ComponentName componentName,
21534            int newState, int flags, int userId) {
21535        if (!sUserManager.exists(userId)) return;
21536        setEnabledSetting(componentName.getPackageName(),
21537                componentName.getClassName(), newState, flags, userId, null);
21538    }
21539
21540    private void setEnabledSetting(final String packageName, String className, int newState,
21541            final int flags, int userId, String callingPackage) {
21542        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21543              || newState == COMPONENT_ENABLED_STATE_ENABLED
21544              || newState == COMPONENT_ENABLED_STATE_DISABLED
21545              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21546              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21547            throw new IllegalArgumentException("Invalid new component state: "
21548                    + newState);
21549        }
21550        PackageSetting pkgSetting;
21551        final int callingUid = Binder.getCallingUid();
21552        final int permission;
21553        if (callingUid == Process.SYSTEM_UID) {
21554            permission = PackageManager.PERMISSION_GRANTED;
21555        } else {
21556            permission = mContext.checkCallingOrSelfPermission(
21557                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21558        }
21559        enforceCrossUserPermission(callingUid, userId,
21560                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21561        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21562        boolean sendNow = false;
21563        boolean isApp = (className == null);
21564        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21565        String componentName = isApp ? packageName : className;
21566        int packageUid = -1;
21567        ArrayList<String> components;
21568
21569        // reader
21570        synchronized (mPackages) {
21571            pkgSetting = mSettings.mPackages.get(packageName);
21572            if (pkgSetting == null) {
21573                if (!isCallerInstantApp) {
21574                    if (className == null) {
21575                        throw new IllegalArgumentException("Unknown package: " + packageName);
21576                    }
21577                    throw new IllegalArgumentException(
21578                            "Unknown component: " + packageName + "/" + className);
21579                } else {
21580                    // throw SecurityException to prevent leaking package information
21581                    throw new SecurityException(
21582                            "Attempt to change component state; "
21583                            + "pid=" + Binder.getCallingPid()
21584                            + ", uid=" + callingUid
21585                            + (className == null
21586                                    ? ", package=" + packageName
21587                                    : ", component=" + packageName + "/" + className));
21588                }
21589            }
21590        }
21591
21592        // Limit who can change which apps
21593        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21594            // Don't allow apps that don't have permission to modify other apps
21595            if (!allowedByPermission
21596                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21597                throw new SecurityException(
21598                        "Attempt to change component state; "
21599                        + "pid=" + Binder.getCallingPid()
21600                        + ", uid=" + callingUid
21601                        + (className == null
21602                                ? ", package=" + packageName
21603                                : ", component=" + packageName + "/" + className));
21604            }
21605            // Don't allow changing protected packages.
21606            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21607                throw new SecurityException("Cannot disable a protected package: " + packageName);
21608            }
21609        }
21610
21611        synchronized (mPackages) {
21612            if (callingUid == Process.SHELL_UID
21613                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21614                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21615                // unless it is a test package.
21616                int oldState = pkgSetting.getEnabled(userId);
21617                if (className == null
21618                    &&
21619                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21620                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21621                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21622                    &&
21623                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21624                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21625                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21626                    // ok
21627                } else {
21628                    throw new SecurityException(
21629                            "Shell cannot change component state for " + packageName + "/"
21630                            + className + " to " + newState);
21631                }
21632            }
21633            if (className == null) {
21634                // We're dealing with an application/package level state change
21635                if (pkgSetting.getEnabled(userId) == newState) {
21636                    // Nothing to do
21637                    return;
21638                }
21639                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21640                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21641                    // Don't care about who enables an app.
21642                    callingPackage = null;
21643                }
21644                pkgSetting.setEnabled(newState, userId, callingPackage);
21645                // pkgSetting.pkg.mSetEnabled = newState;
21646            } else {
21647                // We're dealing with a component level state change
21648                // First, verify that this is a valid class name.
21649                PackageParser.Package pkg = pkgSetting.pkg;
21650                if (pkg == null || !pkg.hasComponentClassName(className)) {
21651                    if (pkg != null &&
21652                            pkg.applicationInfo.targetSdkVersion >=
21653                                    Build.VERSION_CODES.JELLY_BEAN) {
21654                        throw new IllegalArgumentException("Component class " + className
21655                                + " does not exist in " + packageName);
21656                    } else {
21657                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21658                                + className + " does not exist in " + packageName);
21659                    }
21660                }
21661                switch (newState) {
21662                case COMPONENT_ENABLED_STATE_ENABLED:
21663                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21664                        return;
21665                    }
21666                    break;
21667                case COMPONENT_ENABLED_STATE_DISABLED:
21668                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21669                        return;
21670                    }
21671                    break;
21672                case COMPONENT_ENABLED_STATE_DEFAULT:
21673                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21674                        return;
21675                    }
21676                    break;
21677                default:
21678                    Slog.e(TAG, "Invalid new component state: " + newState);
21679                    return;
21680                }
21681            }
21682            scheduleWritePackageRestrictionsLocked(userId);
21683            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21684            final long callingId = Binder.clearCallingIdentity();
21685            try {
21686                updateInstantAppInstallerLocked(packageName);
21687            } finally {
21688                Binder.restoreCallingIdentity(callingId);
21689            }
21690            components = mPendingBroadcasts.get(userId, packageName);
21691            final boolean newPackage = components == null;
21692            if (newPackage) {
21693                components = new ArrayList<String>();
21694            }
21695            if (!components.contains(componentName)) {
21696                components.add(componentName);
21697            }
21698            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21699                sendNow = true;
21700                // Purge entry from pending broadcast list if another one exists already
21701                // since we are sending one right away.
21702                mPendingBroadcasts.remove(userId, packageName);
21703            } else {
21704                if (newPackage) {
21705                    mPendingBroadcasts.put(userId, packageName, components);
21706                }
21707                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21708                    // Schedule a message
21709                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21710                }
21711            }
21712        }
21713
21714        long callingId = Binder.clearCallingIdentity();
21715        try {
21716            if (sendNow) {
21717                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21718                sendPackageChangedBroadcast(packageName,
21719                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21720            }
21721        } finally {
21722            Binder.restoreCallingIdentity(callingId);
21723        }
21724    }
21725
21726    @Override
21727    public void flushPackageRestrictionsAsUser(int userId) {
21728        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21729            return;
21730        }
21731        if (!sUserManager.exists(userId)) {
21732            return;
21733        }
21734        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21735                false /* checkShell */, "flushPackageRestrictions");
21736        synchronized (mPackages) {
21737            mSettings.writePackageRestrictionsLPr(userId);
21738            mDirtyUsers.remove(userId);
21739            if (mDirtyUsers.isEmpty()) {
21740                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21741            }
21742        }
21743    }
21744
21745    private void sendPackageChangedBroadcast(String packageName,
21746            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21747        if (DEBUG_INSTALL)
21748            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21749                    + componentNames);
21750        Bundle extras = new Bundle(4);
21751        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21752        String nameList[] = new String[componentNames.size()];
21753        componentNames.toArray(nameList);
21754        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21755        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21756        extras.putInt(Intent.EXTRA_UID, packageUid);
21757        // If this is not reporting a change of the overall package, then only send it
21758        // to registered receivers.  We don't want to launch a swath of apps for every
21759        // little component state change.
21760        final int flags = !componentNames.contains(packageName)
21761                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21762        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21763                new int[] {UserHandle.getUserId(packageUid)});
21764    }
21765
21766    @Override
21767    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21768        if (!sUserManager.exists(userId)) return;
21769        final int callingUid = Binder.getCallingUid();
21770        if (getInstantAppPackageName(callingUid) != null) {
21771            return;
21772        }
21773        final int permission = mContext.checkCallingOrSelfPermission(
21774                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21775        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21776        enforceCrossUserPermission(callingUid, userId,
21777                true /* requireFullPermission */, true /* checkShell */, "stop package");
21778        // writer
21779        synchronized (mPackages) {
21780            final PackageSetting ps = mSettings.mPackages.get(packageName);
21781            if (!filterAppAccessLPr(ps, callingUid, userId)
21782                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21783                            allowedByPermission, callingUid, userId)) {
21784                scheduleWritePackageRestrictionsLocked(userId);
21785            }
21786        }
21787    }
21788
21789    @Override
21790    public String getInstallerPackageName(String packageName) {
21791        final int callingUid = Binder.getCallingUid();
21792        if (getInstantAppPackageName(callingUid) != null) {
21793            return null;
21794        }
21795        // reader
21796        synchronized (mPackages) {
21797            final PackageSetting ps = mSettings.mPackages.get(packageName);
21798            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21799                return null;
21800            }
21801            return mSettings.getInstallerPackageNameLPr(packageName);
21802        }
21803    }
21804
21805    public boolean isOrphaned(String packageName) {
21806        // reader
21807        synchronized (mPackages) {
21808            return mSettings.isOrphaned(packageName);
21809        }
21810    }
21811
21812    @Override
21813    public int getApplicationEnabledSetting(String packageName, int userId) {
21814        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21815        int callingUid = Binder.getCallingUid();
21816        enforceCrossUserPermission(callingUid, userId,
21817                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21818        // reader
21819        synchronized (mPackages) {
21820            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21821                return COMPONENT_ENABLED_STATE_DISABLED;
21822            }
21823            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21824        }
21825    }
21826
21827    @Override
21828    public int getComponentEnabledSetting(ComponentName component, int userId) {
21829        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21830        int callingUid = Binder.getCallingUid();
21831        enforceCrossUserPermission(callingUid, userId,
21832                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21833        synchronized (mPackages) {
21834            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21835                    component, TYPE_UNKNOWN, userId)) {
21836                return COMPONENT_ENABLED_STATE_DISABLED;
21837            }
21838            return mSettings.getComponentEnabledSettingLPr(component, userId);
21839        }
21840    }
21841
21842    @Override
21843    public void enterSafeMode() {
21844        enforceSystemOrRoot("Only the system can request entering safe mode");
21845
21846        if (!mSystemReady) {
21847            mSafeMode = true;
21848        }
21849    }
21850
21851    @Override
21852    public void systemReady() {
21853        enforceSystemOrRoot("Only the system can claim the system is ready");
21854
21855        mSystemReady = true;
21856        final ContentResolver resolver = mContext.getContentResolver();
21857        ContentObserver co = new ContentObserver(mHandler) {
21858            @Override
21859            public void onChange(boolean selfChange) {
21860                mEphemeralAppsDisabled =
21861                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21862                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21863            }
21864        };
21865        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21866                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21867                false, co, UserHandle.USER_SYSTEM);
21868        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21869                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21870        co.onChange(true);
21871
21872        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21873        // disabled after already being started.
21874        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21875                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21876
21877        // Read the compatibilty setting when the system is ready.
21878        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21879                mContext.getContentResolver(),
21880                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21881        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21882        if (DEBUG_SETTINGS) {
21883            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21884        }
21885
21886        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21887
21888        synchronized (mPackages) {
21889            // Verify that all of the preferred activity components actually
21890            // exist.  It is possible for applications to be updated and at
21891            // that point remove a previously declared activity component that
21892            // had been set as a preferred activity.  We try to clean this up
21893            // the next time we encounter that preferred activity, but it is
21894            // possible for the user flow to never be able to return to that
21895            // situation so here we do a sanity check to make sure we haven't
21896            // left any junk around.
21897            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21898            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21899                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21900                removed.clear();
21901                for (PreferredActivity pa : pir.filterSet()) {
21902                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21903                        removed.add(pa);
21904                    }
21905                }
21906                if (removed.size() > 0) {
21907                    for (int r=0; r<removed.size(); r++) {
21908                        PreferredActivity pa = removed.get(r);
21909                        Slog.w(TAG, "Removing dangling preferred activity: "
21910                                + pa.mPref.mComponent);
21911                        pir.removeFilter(pa);
21912                    }
21913                    mSettings.writePackageRestrictionsLPr(
21914                            mSettings.mPreferredActivities.keyAt(i));
21915                }
21916            }
21917
21918            for (int userId : UserManagerService.getInstance().getUserIds()) {
21919                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21920                    grantPermissionsUserIds = ArrayUtils.appendInt(
21921                            grantPermissionsUserIds, userId);
21922                }
21923            }
21924        }
21925        sUserManager.systemReady();
21926
21927        // If we upgraded grant all default permissions before kicking off.
21928        for (int userId : grantPermissionsUserIds) {
21929            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21930        }
21931
21932        // If we did not grant default permissions, we preload from this the
21933        // default permission exceptions lazily to ensure we don't hit the
21934        // disk on a new user creation.
21935        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21936            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21937        }
21938
21939        // Kick off any messages waiting for system ready
21940        if (mPostSystemReadyMessages != null) {
21941            for (Message msg : mPostSystemReadyMessages) {
21942                msg.sendToTarget();
21943            }
21944            mPostSystemReadyMessages = null;
21945        }
21946
21947        // Watch for external volumes that come and go over time
21948        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21949        storage.registerListener(mStorageListener);
21950
21951        mInstallerService.systemReady();
21952        mPackageDexOptimizer.systemReady();
21953
21954        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21955                StorageManagerInternal.class);
21956        StorageManagerInternal.addExternalStoragePolicy(
21957                new StorageManagerInternal.ExternalStorageMountPolicy() {
21958            @Override
21959            public int getMountMode(int uid, String packageName) {
21960                if (Process.isIsolated(uid)) {
21961                    return Zygote.MOUNT_EXTERNAL_NONE;
21962                }
21963                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21964                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21965                }
21966                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21967                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21968                }
21969                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21970                    return Zygote.MOUNT_EXTERNAL_READ;
21971                }
21972                return Zygote.MOUNT_EXTERNAL_WRITE;
21973            }
21974
21975            @Override
21976            public boolean hasExternalStorage(int uid, String packageName) {
21977                return true;
21978            }
21979        });
21980
21981        // Now that we're mostly running, clean up stale users and apps
21982        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21983        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21984
21985        if (mPrivappPermissionsViolations != null) {
21986            Slog.wtf(TAG,"Signature|privileged permissions not in "
21987                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21988            mPrivappPermissionsViolations = null;
21989        }
21990    }
21991
21992    public void waitForAppDataPrepared() {
21993        if (mPrepareAppDataFuture == null) {
21994            return;
21995        }
21996        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21997        mPrepareAppDataFuture = null;
21998    }
21999
22000    @Override
22001    public boolean isSafeMode() {
22002        // allow instant applications
22003        return mSafeMode;
22004    }
22005
22006    @Override
22007    public boolean hasSystemUidErrors() {
22008        // allow instant applications
22009        return mHasSystemUidErrors;
22010    }
22011
22012    static String arrayToString(int[] array) {
22013        StringBuffer buf = new StringBuffer(128);
22014        buf.append('[');
22015        if (array != null) {
22016            for (int i=0; i<array.length; i++) {
22017                if (i > 0) buf.append(", ");
22018                buf.append(array[i]);
22019            }
22020        }
22021        buf.append(']');
22022        return buf.toString();
22023    }
22024
22025    static class DumpState {
22026        public static final int DUMP_LIBS = 1 << 0;
22027        public static final int DUMP_FEATURES = 1 << 1;
22028        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22029        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22030        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22031        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22032        public static final int DUMP_PERMISSIONS = 1 << 6;
22033        public static final int DUMP_PACKAGES = 1 << 7;
22034        public static final int DUMP_SHARED_USERS = 1 << 8;
22035        public static final int DUMP_MESSAGES = 1 << 9;
22036        public static final int DUMP_PROVIDERS = 1 << 10;
22037        public static final int DUMP_VERIFIERS = 1 << 11;
22038        public static final int DUMP_PREFERRED = 1 << 12;
22039        public static final int DUMP_PREFERRED_XML = 1 << 13;
22040        public static final int DUMP_KEYSETS = 1 << 14;
22041        public static final int DUMP_VERSION = 1 << 15;
22042        public static final int DUMP_INSTALLS = 1 << 16;
22043        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22044        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22045        public static final int DUMP_FROZEN = 1 << 19;
22046        public static final int DUMP_DEXOPT = 1 << 20;
22047        public static final int DUMP_COMPILER_STATS = 1 << 21;
22048        public static final int DUMP_CHANGES = 1 << 22;
22049        public static final int DUMP_VOLUMES = 1 << 23;
22050
22051        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22052
22053        private int mTypes;
22054
22055        private int mOptions;
22056
22057        private boolean mTitlePrinted;
22058
22059        private SharedUserSetting mSharedUser;
22060
22061        public boolean isDumping(int type) {
22062            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22063                return true;
22064            }
22065
22066            return (mTypes & type) != 0;
22067        }
22068
22069        public void setDump(int type) {
22070            mTypes |= type;
22071        }
22072
22073        public boolean isOptionEnabled(int option) {
22074            return (mOptions & option) != 0;
22075        }
22076
22077        public void setOptionEnabled(int option) {
22078            mOptions |= option;
22079        }
22080
22081        public boolean onTitlePrinted() {
22082            final boolean printed = mTitlePrinted;
22083            mTitlePrinted = true;
22084            return printed;
22085        }
22086
22087        public boolean getTitlePrinted() {
22088            return mTitlePrinted;
22089        }
22090
22091        public void setTitlePrinted(boolean enabled) {
22092            mTitlePrinted = enabled;
22093        }
22094
22095        public SharedUserSetting getSharedUser() {
22096            return mSharedUser;
22097        }
22098
22099        public void setSharedUser(SharedUserSetting user) {
22100            mSharedUser = user;
22101        }
22102    }
22103
22104    @Override
22105    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22106            FileDescriptor err, String[] args, ShellCallback callback,
22107            ResultReceiver resultReceiver) {
22108        (new PackageManagerShellCommand(this)).exec(
22109                this, in, out, err, args, callback, resultReceiver);
22110    }
22111
22112    @Override
22113    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22114        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22115
22116        DumpState dumpState = new DumpState();
22117        boolean fullPreferred = false;
22118        boolean checkin = false;
22119
22120        String packageName = null;
22121        ArraySet<String> permissionNames = null;
22122
22123        int opti = 0;
22124        while (opti < args.length) {
22125            String opt = args[opti];
22126            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22127                break;
22128            }
22129            opti++;
22130
22131            if ("-a".equals(opt)) {
22132                // Right now we only know how to print all.
22133            } else if ("-h".equals(opt)) {
22134                pw.println("Package manager dump options:");
22135                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22136                pw.println("    --checkin: dump for a checkin");
22137                pw.println("    -f: print details of intent filters");
22138                pw.println("    -h: print this help");
22139                pw.println("  cmd may be one of:");
22140                pw.println("    l[ibraries]: list known shared libraries");
22141                pw.println("    f[eatures]: list device features");
22142                pw.println("    k[eysets]: print known keysets");
22143                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22144                pw.println("    perm[issions]: dump permissions");
22145                pw.println("    permission [name ...]: dump declaration and use of given permission");
22146                pw.println("    pref[erred]: print preferred package settings");
22147                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22148                pw.println("    prov[iders]: dump content providers");
22149                pw.println("    p[ackages]: dump installed packages");
22150                pw.println("    s[hared-users]: dump shared user IDs");
22151                pw.println("    m[essages]: print collected runtime messages");
22152                pw.println("    v[erifiers]: print package verifier info");
22153                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22154                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22155                pw.println("    version: print database version info");
22156                pw.println("    write: write current settings now");
22157                pw.println("    installs: details about install sessions");
22158                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22159                pw.println("    dexopt: dump dexopt state");
22160                pw.println("    compiler-stats: dump compiler statistics");
22161                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22162                pw.println("    <package.name>: info about given package");
22163                return;
22164            } else if ("--checkin".equals(opt)) {
22165                checkin = true;
22166            } else if ("-f".equals(opt)) {
22167                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22168            } else if ("--proto".equals(opt)) {
22169                dumpProto(fd);
22170                return;
22171            } else {
22172                pw.println("Unknown argument: " + opt + "; use -h for help");
22173            }
22174        }
22175
22176        // Is the caller requesting to dump a particular piece of data?
22177        if (opti < args.length) {
22178            String cmd = args[opti];
22179            opti++;
22180            // Is this a package name?
22181            if ("android".equals(cmd) || cmd.contains(".")) {
22182                packageName = cmd;
22183                // When dumping a single package, we always dump all of its
22184                // filter information since the amount of data will be reasonable.
22185                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22186            } else if ("check-permission".equals(cmd)) {
22187                if (opti >= args.length) {
22188                    pw.println("Error: check-permission missing permission argument");
22189                    return;
22190                }
22191                String perm = args[opti];
22192                opti++;
22193                if (opti >= args.length) {
22194                    pw.println("Error: check-permission missing package argument");
22195                    return;
22196                }
22197
22198                String pkg = args[opti];
22199                opti++;
22200                int user = UserHandle.getUserId(Binder.getCallingUid());
22201                if (opti < args.length) {
22202                    try {
22203                        user = Integer.parseInt(args[opti]);
22204                    } catch (NumberFormatException e) {
22205                        pw.println("Error: check-permission user argument is not a number: "
22206                                + args[opti]);
22207                        return;
22208                    }
22209                }
22210
22211                // Normalize package name to handle renamed packages and static libs
22212                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22213
22214                pw.println(checkPermission(perm, pkg, user));
22215                return;
22216            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22217                dumpState.setDump(DumpState.DUMP_LIBS);
22218            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22219                dumpState.setDump(DumpState.DUMP_FEATURES);
22220            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22221                if (opti >= args.length) {
22222                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22223                            | DumpState.DUMP_SERVICE_RESOLVERS
22224                            | DumpState.DUMP_RECEIVER_RESOLVERS
22225                            | DumpState.DUMP_CONTENT_RESOLVERS);
22226                } else {
22227                    while (opti < args.length) {
22228                        String name = args[opti];
22229                        if ("a".equals(name) || "activity".equals(name)) {
22230                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22231                        } else if ("s".equals(name) || "service".equals(name)) {
22232                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22233                        } else if ("r".equals(name) || "receiver".equals(name)) {
22234                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22235                        } else if ("c".equals(name) || "content".equals(name)) {
22236                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22237                        } else {
22238                            pw.println("Error: unknown resolver table type: " + name);
22239                            return;
22240                        }
22241                        opti++;
22242                    }
22243                }
22244            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22245                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22246            } else if ("permission".equals(cmd)) {
22247                if (opti >= args.length) {
22248                    pw.println("Error: permission requires permission name");
22249                    return;
22250                }
22251                permissionNames = new ArraySet<>();
22252                while (opti < args.length) {
22253                    permissionNames.add(args[opti]);
22254                    opti++;
22255                }
22256                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22257                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22258            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22259                dumpState.setDump(DumpState.DUMP_PREFERRED);
22260            } else if ("preferred-xml".equals(cmd)) {
22261                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22262                if (opti < args.length && "--full".equals(args[opti])) {
22263                    fullPreferred = true;
22264                    opti++;
22265                }
22266            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22267                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22268            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22269                dumpState.setDump(DumpState.DUMP_PACKAGES);
22270            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22271                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22272            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22273                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22274            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22275                dumpState.setDump(DumpState.DUMP_MESSAGES);
22276            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22277                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22278            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22279                    || "intent-filter-verifiers".equals(cmd)) {
22280                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22281            } else if ("version".equals(cmd)) {
22282                dumpState.setDump(DumpState.DUMP_VERSION);
22283            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22284                dumpState.setDump(DumpState.DUMP_KEYSETS);
22285            } else if ("installs".equals(cmd)) {
22286                dumpState.setDump(DumpState.DUMP_INSTALLS);
22287            } else if ("frozen".equals(cmd)) {
22288                dumpState.setDump(DumpState.DUMP_FROZEN);
22289            } else if ("volumes".equals(cmd)) {
22290                dumpState.setDump(DumpState.DUMP_VOLUMES);
22291            } else if ("dexopt".equals(cmd)) {
22292                dumpState.setDump(DumpState.DUMP_DEXOPT);
22293            } else if ("compiler-stats".equals(cmd)) {
22294                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22295            } else if ("changes".equals(cmd)) {
22296                dumpState.setDump(DumpState.DUMP_CHANGES);
22297            } else if ("write".equals(cmd)) {
22298                synchronized (mPackages) {
22299                    mSettings.writeLPr();
22300                    pw.println("Settings written.");
22301                    return;
22302                }
22303            }
22304        }
22305
22306        if (checkin) {
22307            pw.println("vers,1");
22308        }
22309
22310        // reader
22311        synchronized (mPackages) {
22312            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22313                if (!checkin) {
22314                    if (dumpState.onTitlePrinted())
22315                        pw.println();
22316                    pw.println("Database versions:");
22317                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22318                }
22319            }
22320
22321            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22322                if (!checkin) {
22323                    if (dumpState.onTitlePrinted())
22324                        pw.println();
22325                    pw.println("Verifiers:");
22326                    pw.print("  Required: ");
22327                    pw.print(mRequiredVerifierPackage);
22328                    pw.print(" (uid=");
22329                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22330                            UserHandle.USER_SYSTEM));
22331                    pw.println(")");
22332                } else if (mRequiredVerifierPackage != null) {
22333                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22334                    pw.print(",");
22335                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22336                            UserHandle.USER_SYSTEM));
22337                }
22338            }
22339
22340            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22341                    packageName == null) {
22342                if (mIntentFilterVerifierComponent != null) {
22343                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22344                    if (!checkin) {
22345                        if (dumpState.onTitlePrinted())
22346                            pw.println();
22347                        pw.println("Intent Filter Verifier:");
22348                        pw.print("  Using: ");
22349                        pw.print(verifierPackageName);
22350                        pw.print(" (uid=");
22351                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22352                                UserHandle.USER_SYSTEM));
22353                        pw.println(")");
22354                    } else if (verifierPackageName != null) {
22355                        pw.print("ifv,"); pw.print(verifierPackageName);
22356                        pw.print(",");
22357                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22358                                UserHandle.USER_SYSTEM));
22359                    }
22360                } else {
22361                    pw.println();
22362                    pw.println("No Intent Filter Verifier available!");
22363                }
22364            }
22365
22366            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22367                boolean printedHeader = false;
22368                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22369                while (it.hasNext()) {
22370                    String libName = it.next();
22371                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22372                    if (versionedLib == null) {
22373                        continue;
22374                    }
22375                    final int versionCount = versionedLib.size();
22376                    for (int i = 0; i < versionCount; i++) {
22377                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22378                        if (!checkin) {
22379                            if (!printedHeader) {
22380                                if (dumpState.onTitlePrinted())
22381                                    pw.println();
22382                                pw.println("Libraries:");
22383                                printedHeader = true;
22384                            }
22385                            pw.print("  ");
22386                        } else {
22387                            pw.print("lib,");
22388                        }
22389                        pw.print(libEntry.info.getName());
22390                        if (libEntry.info.isStatic()) {
22391                            pw.print(" version=" + libEntry.info.getVersion());
22392                        }
22393                        if (!checkin) {
22394                            pw.print(" -> ");
22395                        }
22396                        if (libEntry.path != null) {
22397                            pw.print(" (jar) ");
22398                            pw.print(libEntry.path);
22399                        } else {
22400                            pw.print(" (apk) ");
22401                            pw.print(libEntry.apk);
22402                        }
22403                        pw.println();
22404                    }
22405                }
22406            }
22407
22408            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22409                if (dumpState.onTitlePrinted())
22410                    pw.println();
22411                if (!checkin) {
22412                    pw.println("Features:");
22413                }
22414
22415                synchronized (mAvailableFeatures) {
22416                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22417                        if (checkin) {
22418                            pw.print("feat,");
22419                            pw.print(feat.name);
22420                            pw.print(",");
22421                            pw.println(feat.version);
22422                        } else {
22423                            pw.print("  ");
22424                            pw.print(feat.name);
22425                            if (feat.version > 0) {
22426                                pw.print(" version=");
22427                                pw.print(feat.version);
22428                            }
22429                            pw.println();
22430                        }
22431                    }
22432                }
22433            }
22434
22435            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22436                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22437                        : "Activity Resolver Table:", "  ", packageName,
22438                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22439                    dumpState.setTitlePrinted(true);
22440                }
22441            }
22442            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22443                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22444                        : "Receiver Resolver Table:", "  ", packageName,
22445                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22446                    dumpState.setTitlePrinted(true);
22447                }
22448            }
22449            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22450                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22451                        : "Service Resolver Table:", "  ", packageName,
22452                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22453                    dumpState.setTitlePrinted(true);
22454                }
22455            }
22456            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22457                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22458                        : "Provider Resolver Table:", "  ", packageName,
22459                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22460                    dumpState.setTitlePrinted(true);
22461                }
22462            }
22463
22464            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22465                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22466                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22467                    int user = mSettings.mPreferredActivities.keyAt(i);
22468                    if (pir.dump(pw,
22469                            dumpState.getTitlePrinted()
22470                                ? "\nPreferred Activities User " + user + ":"
22471                                : "Preferred Activities User " + user + ":", "  ",
22472                            packageName, true, false)) {
22473                        dumpState.setTitlePrinted(true);
22474                    }
22475                }
22476            }
22477
22478            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22479                pw.flush();
22480                FileOutputStream fout = new FileOutputStream(fd);
22481                BufferedOutputStream str = new BufferedOutputStream(fout);
22482                XmlSerializer serializer = new FastXmlSerializer();
22483                try {
22484                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22485                    serializer.startDocument(null, true);
22486                    serializer.setFeature(
22487                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22488                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22489                    serializer.endDocument();
22490                    serializer.flush();
22491                } catch (IllegalArgumentException e) {
22492                    pw.println("Failed writing: " + e);
22493                } catch (IllegalStateException e) {
22494                    pw.println("Failed writing: " + e);
22495                } catch (IOException e) {
22496                    pw.println("Failed writing: " + e);
22497                }
22498            }
22499
22500            if (!checkin
22501                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22502                    && packageName == null) {
22503                pw.println();
22504                int count = mSettings.mPackages.size();
22505                if (count == 0) {
22506                    pw.println("No applications!");
22507                    pw.println();
22508                } else {
22509                    final String prefix = "  ";
22510                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22511                    if (allPackageSettings.size() == 0) {
22512                        pw.println("No domain preferred apps!");
22513                        pw.println();
22514                    } else {
22515                        pw.println("App verification status:");
22516                        pw.println();
22517                        count = 0;
22518                        for (PackageSetting ps : allPackageSettings) {
22519                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22520                            if (ivi == null || ivi.getPackageName() == null) continue;
22521                            pw.println(prefix + "Package: " + ivi.getPackageName());
22522                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22523                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22524                            pw.println();
22525                            count++;
22526                        }
22527                        if (count == 0) {
22528                            pw.println(prefix + "No app verification established.");
22529                            pw.println();
22530                        }
22531                        for (int userId : sUserManager.getUserIds()) {
22532                            pw.println("App linkages for user " + userId + ":");
22533                            pw.println();
22534                            count = 0;
22535                            for (PackageSetting ps : allPackageSettings) {
22536                                final long status = ps.getDomainVerificationStatusForUser(userId);
22537                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22538                                        && !DEBUG_DOMAIN_VERIFICATION) {
22539                                    continue;
22540                                }
22541                                pw.println(prefix + "Package: " + ps.name);
22542                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22543                                String statusStr = IntentFilterVerificationInfo.
22544                                        getStatusStringFromValue(status);
22545                                pw.println(prefix + "Status:  " + statusStr);
22546                                pw.println();
22547                                count++;
22548                            }
22549                            if (count == 0) {
22550                                pw.println(prefix + "No configured app linkages.");
22551                                pw.println();
22552                            }
22553                        }
22554                    }
22555                }
22556            }
22557
22558            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22559                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22560                if (packageName == null && permissionNames == null) {
22561                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22562                        if (iperm == 0) {
22563                            if (dumpState.onTitlePrinted())
22564                                pw.println();
22565                            pw.println("AppOp Permissions:");
22566                        }
22567                        pw.print("  AppOp Permission ");
22568                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22569                        pw.println(":");
22570                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22571                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22572                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22573                        }
22574                    }
22575                }
22576            }
22577
22578            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22579                boolean printedSomething = false;
22580                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22581                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22582                        continue;
22583                    }
22584                    if (!printedSomething) {
22585                        if (dumpState.onTitlePrinted())
22586                            pw.println();
22587                        pw.println("Registered ContentProviders:");
22588                        printedSomething = true;
22589                    }
22590                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22591                    pw.print("    "); pw.println(p.toString());
22592                }
22593                printedSomething = false;
22594                for (Map.Entry<String, PackageParser.Provider> entry :
22595                        mProvidersByAuthority.entrySet()) {
22596                    PackageParser.Provider p = entry.getValue();
22597                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22598                        continue;
22599                    }
22600                    if (!printedSomething) {
22601                        if (dumpState.onTitlePrinted())
22602                            pw.println();
22603                        pw.println("ContentProvider Authorities:");
22604                        printedSomething = true;
22605                    }
22606                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22607                    pw.print("    "); pw.println(p.toString());
22608                    if (p.info != null && p.info.applicationInfo != null) {
22609                        final String appInfo = p.info.applicationInfo.toString();
22610                        pw.print("      applicationInfo="); pw.println(appInfo);
22611                    }
22612                }
22613            }
22614
22615            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22616                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22617            }
22618
22619            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22620                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22621            }
22622
22623            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22624                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22625            }
22626
22627            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22628                if (dumpState.onTitlePrinted()) pw.println();
22629                pw.println("Package Changes:");
22630                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22631                final int K = mChangedPackages.size();
22632                for (int i = 0; i < K; i++) {
22633                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22634                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22635                    final int N = changes.size();
22636                    if (N == 0) {
22637                        pw.print("    "); pw.println("No packages changed");
22638                    } else {
22639                        for (int j = 0; j < N; j++) {
22640                            final String pkgName = changes.valueAt(j);
22641                            final int sequenceNumber = changes.keyAt(j);
22642                            pw.print("    ");
22643                            pw.print("seq=");
22644                            pw.print(sequenceNumber);
22645                            pw.print(", package=");
22646                            pw.println(pkgName);
22647                        }
22648                    }
22649                }
22650            }
22651
22652            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22653                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22654            }
22655
22656            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22657                // XXX should handle packageName != null by dumping only install data that
22658                // the given package is involved with.
22659                if (dumpState.onTitlePrinted()) pw.println();
22660
22661                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22662                ipw.println();
22663                ipw.println("Frozen packages:");
22664                ipw.increaseIndent();
22665                if (mFrozenPackages.size() == 0) {
22666                    ipw.println("(none)");
22667                } else {
22668                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22669                        ipw.println(mFrozenPackages.valueAt(i));
22670                    }
22671                }
22672                ipw.decreaseIndent();
22673            }
22674
22675            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22676                if (dumpState.onTitlePrinted()) pw.println();
22677
22678                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22679                ipw.println();
22680                ipw.println("Loaded volumes:");
22681                ipw.increaseIndent();
22682                if (mLoadedVolumes.size() == 0) {
22683                    ipw.println("(none)");
22684                } else {
22685                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22686                        ipw.println(mLoadedVolumes.valueAt(i));
22687                    }
22688                }
22689                ipw.decreaseIndent();
22690            }
22691
22692            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22693                if (dumpState.onTitlePrinted()) pw.println();
22694                dumpDexoptStateLPr(pw, packageName);
22695            }
22696
22697            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22698                if (dumpState.onTitlePrinted()) pw.println();
22699                dumpCompilerStatsLPr(pw, packageName);
22700            }
22701
22702            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22703                if (dumpState.onTitlePrinted()) pw.println();
22704                mSettings.dumpReadMessagesLPr(pw, dumpState);
22705
22706                pw.println();
22707                pw.println("Package warning messages:");
22708                BufferedReader in = null;
22709                String line = null;
22710                try {
22711                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22712                    while ((line = in.readLine()) != null) {
22713                        if (line.contains("ignored: updated version")) continue;
22714                        pw.println(line);
22715                    }
22716                } catch (IOException ignored) {
22717                } finally {
22718                    IoUtils.closeQuietly(in);
22719                }
22720            }
22721
22722            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22723                BufferedReader in = null;
22724                String line = null;
22725                try {
22726                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22727                    while ((line = in.readLine()) != null) {
22728                        if (line.contains("ignored: updated version")) continue;
22729                        pw.print("msg,");
22730                        pw.println(line);
22731                    }
22732                } catch (IOException ignored) {
22733                } finally {
22734                    IoUtils.closeQuietly(in);
22735                }
22736            }
22737        }
22738
22739        // PackageInstaller should be called outside of mPackages lock
22740        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22741            // XXX should handle packageName != null by dumping only install data that
22742            // the given package is involved with.
22743            if (dumpState.onTitlePrinted()) pw.println();
22744            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22745        }
22746    }
22747
22748    private void dumpProto(FileDescriptor fd) {
22749        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22750
22751        synchronized (mPackages) {
22752            final long requiredVerifierPackageToken =
22753                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22754            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22755            proto.write(
22756                    PackageServiceDumpProto.PackageShortProto.UID,
22757                    getPackageUid(
22758                            mRequiredVerifierPackage,
22759                            MATCH_DEBUG_TRIAGED_MISSING,
22760                            UserHandle.USER_SYSTEM));
22761            proto.end(requiredVerifierPackageToken);
22762
22763            if (mIntentFilterVerifierComponent != null) {
22764                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22765                final long verifierPackageToken =
22766                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22767                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22768                proto.write(
22769                        PackageServiceDumpProto.PackageShortProto.UID,
22770                        getPackageUid(
22771                                verifierPackageName,
22772                                MATCH_DEBUG_TRIAGED_MISSING,
22773                                UserHandle.USER_SYSTEM));
22774                proto.end(verifierPackageToken);
22775            }
22776
22777            dumpSharedLibrariesProto(proto);
22778            dumpFeaturesProto(proto);
22779            mSettings.dumpPackagesProto(proto);
22780            mSettings.dumpSharedUsersProto(proto);
22781            dumpMessagesProto(proto);
22782        }
22783        proto.flush();
22784    }
22785
22786    private void dumpMessagesProto(ProtoOutputStream proto) {
22787        BufferedReader in = null;
22788        String line = null;
22789        try {
22790            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22791            while ((line = in.readLine()) != null) {
22792                if (line.contains("ignored: updated version")) continue;
22793                proto.write(PackageServiceDumpProto.MESSAGES, line);
22794            }
22795        } catch (IOException ignored) {
22796        } finally {
22797            IoUtils.closeQuietly(in);
22798        }
22799    }
22800
22801    private void dumpFeaturesProto(ProtoOutputStream proto) {
22802        synchronized (mAvailableFeatures) {
22803            final int count = mAvailableFeatures.size();
22804            for (int i = 0; i < count; i++) {
22805                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22806                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22807                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22808                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22809                proto.end(featureToken);
22810            }
22811        }
22812    }
22813
22814    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22815        final int count = mSharedLibraries.size();
22816        for (int i = 0; i < count; i++) {
22817            final String libName = mSharedLibraries.keyAt(i);
22818            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22819            if (versionedLib == null) {
22820                continue;
22821            }
22822            final int versionCount = versionedLib.size();
22823            for (int j = 0; j < versionCount; j++) {
22824                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22825                final long sharedLibraryToken =
22826                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22827                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22828                final boolean isJar = (libEntry.path != null);
22829                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22830                if (isJar) {
22831                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22832                } else {
22833                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22834                }
22835                proto.end(sharedLibraryToken);
22836            }
22837        }
22838    }
22839
22840    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22841        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22842        ipw.println();
22843        ipw.println("Dexopt state:");
22844        ipw.increaseIndent();
22845        Collection<PackageParser.Package> packages = null;
22846        if (packageName != null) {
22847            PackageParser.Package targetPackage = mPackages.get(packageName);
22848            if (targetPackage != null) {
22849                packages = Collections.singletonList(targetPackage);
22850            } else {
22851                ipw.println("Unable to find package: " + packageName);
22852                return;
22853            }
22854        } else {
22855            packages = mPackages.values();
22856        }
22857
22858        for (PackageParser.Package pkg : packages) {
22859            ipw.println("[" + pkg.packageName + "]");
22860            ipw.increaseIndent();
22861            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22862            ipw.decreaseIndent();
22863        }
22864    }
22865
22866    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22867        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22868        ipw.println();
22869        ipw.println("Compiler stats:");
22870        ipw.increaseIndent();
22871        Collection<PackageParser.Package> packages = null;
22872        if (packageName != null) {
22873            PackageParser.Package targetPackage = mPackages.get(packageName);
22874            if (targetPackage != null) {
22875                packages = Collections.singletonList(targetPackage);
22876            } else {
22877                ipw.println("Unable to find package: " + packageName);
22878                return;
22879            }
22880        } else {
22881            packages = mPackages.values();
22882        }
22883
22884        for (PackageParser.Package pkg : packages) {
22885            ipw.println("[" + pkg.packageName + "]");
22886            ipw.increaseIndent();
22887
22888            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22889            if (stats == null) {
22890                ipw.println("(No recorded stats)");
22891            } else {
22892                stats.dump(ipw);
22893            }
22894            ipw.decreaseIndent();
22895        }
22896    }
22897
22898    private String dumpDomainString(String packageName) {
22899        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22900                .getList();
22901        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22902
22903        ArraySet<String> result = new ArraySet<>();
22904        if (iviList.size() > 0) {
22905            for (IntentFilterVerificationInfo ivi : iviList) {
22906                for (String host : ivi.getDomains()) {
22907                    result.add(host);
22908                }
22909            }
22910        }
22911        if (filters != null && filters.size() > 0) {
22912            for (IntentFilter filter : filters) {
22913                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22914                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22915                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22916                    result.addAll(filter.getHostsList());
22917                }
22918            }
22919        }
22920
22921        StringBuilder sb = new StringBuilder(result.size() * 16);
22922        for (String domain : result) {
22923            if (sb.length() > 0) sb.append(" ");
22924            sb.append(domain);
22925        }
22926        return sb.toString();
22927    }
22928
22929    // ------- apps on sdcard specific code -------
22930    static final boolean DEBUG_SD_INSTALL = false;
22931
22932    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22933
22934    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22935
22936    private boolean mMediaMounted = false;
22937
22938    static String getEncryptKey() {
22939        try {
22940            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22941                    SD_ENCRYPTION_KEYSTORE_NAME);
22942            if (sdEncKey == null) {
22943                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22944                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22945                if (sdEncKey == null) {
22946                    Slog.e(TAG, "Failed to create encryption keys");
22947                    return null;
22948                }
22949            }
22950            return sdEncKey;
22951        } catch (NoSuchAlgorithmException nsae) {
22952            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22953            return null;
22954        } catch (IOException ioe) {
22955            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22956            return null;
22957        }
22958    }
22959
22960    /*
22961     * Update media status on PackageManager.
22962     */
22963    @Override
22964    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22965        enforceSystemOrRoot("Media status can only be updated by the system");
22966        // reader; this apparently protects mMediaMounted, but should probably
22967        // be a different lock in that case.
22968        synchronized (mPackages) {
22969            Log.i(TAG, "Updating external media status from "
22970                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22971                    + (mediaStatus ? "mounted" : "unmounted"));
22972            if (DEBUG_SD_INSTALL)
22973                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22974                        + ", mMediaMounted=" + mMediaMounted);
22975            if (mediaStatus == mMediaMounted) {
22976                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22977                        : 0, -1);
22978                mHandler.sendMessage(msg);
22979                return;
22980            }
22981            mMediaMounted = mediaStatus;
22982        }
22983        // Queue up an async operation since the package installation may take a
22984        // little while.
22985        mHandler.post(new Runnable() {
22986            public void run() {
22987                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22988            }
22989        });
22990    }
22991
22992    /**
22993     * Called by StorageManagerService when the initial ASECs to scan are available.
22994     * Should block until all the ASEC containers are finished being scanned.
22995     */
22996    public void scanAvailableAsecs() {
22997        updateExternalMediaStatusInner(true, false, false);
22998    }
22999
23000    /*
23001     * Collect information of applications on external media, map them against
23002     * existing containers and update information based on current mount status.
23003     * Please note that we always have to report status if reportStatus has been
23004     * set to true especially when unloading packages.
23005     */
23006    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23007            boolean externalStorage) {
23008        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23009        int[] uidArr = EmptyArray.INT;
23010
23011        final String[] list = PackageHelper.getSecureContainerList();
23012        if (ArrayUtils.isEmpty(list)) {
23013            Log.i(TAG, "No secure containers found");
23014        } else {
23015            // Process list of secure containers and categorize them
23016            // as active or stale based on their package internal state.
23017
23018            // reader
23019            synchronized (mPackages) {
23020                for (String cid : list) {
23021                    // Leave stages untouched for now; installer service owns them
23022                    if (PackageInstallerService.isStageName(cid)) continue;
23023
23024                    if (DEBUG_SD_INSTALL)
23025                        Log.i(TAG, "Processing container " + cid);
23026                    String pkgName = getAsecPackageName(cid);
23027                    if (pkgName == null) {
23028                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23029                        continue;
23030                    }
23031                    if (DEBUG_SD_INSTALL)
23032                        Log.i(TAG, "Looking for pkg : " + pkgName);
23033
23034                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23035                    if (ps == null) {
23036                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23037                        continue;
23038                    }
23039
23040                    /*
23041                     * Skip packages that are not external if we're unmounting
23042                     * external storage.
23043                     */
23044                    if (externalStorage && !isMounted && !isExternal(ps)) {
23045                        continue;
23046                    }
23047
23048                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23049                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23050                    // The package status is changed only if the code path
23051                    // matches between settings and the container id.
23052                    if (ps.codePathString != null
23053                            && ps.codePathString.startsWith(args.getCodePath())) {
23054                        if (DEBUG_SD_INSTALL) {
23055                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23056                                    + " at code path: " + ps.codePathString);
23057                        }
23058
23059                        // We do have a valid package installed on sdcard
23060                        processCids.put(args, ps.codePathString);
23061                        final int uid = ps.appId;
23062                        if (uid != -1) {
23063                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23064                        }
23065                    } else {
23066                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23067                                + ps.codePathString);
23068                    }
23069                }
23070            }
23071
23072            Arrays.sort(uidArr);
23073        }
23074
23075        // Process packages with valid entries.
23076        if (isMounted) {
23077            if (DEBUG_SD_INSTALL)
23078                Log.i(TAG, "Loading packages");
23079            loadMediaPackages(processCids, uidArr, externalStorage);
23080            startCleaningPackages();
23081            mInstallerService.onSecureContainersAvailable();
23082        } else {
23083            if (DEBUG_SD_INSTALL)
23084                Log.i(TAG, "Unloading packages");
23085            unloadMediaPackages(processCids, uidArr, reportStatus);
23086        }
23087    }
23088
23089    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23090            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23091        final int size = infos.size();
23092        final String[] packageNames = new String[size];
23093        final int[] packageUids = new int[size];
23094        for (int i = 0; i < size; i++) {
23095            final ApplicationInfo info = infos.get(i);
23096            packageNames[i] = info.packageName;
23097            packageUids[i] = info.uid;
23098        }
23099        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23100                finishedReceiver);
23101    }
23102
23103    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23104            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23105        sendResourcesChangedBroadcast(mediaStatus, replacing,
23106                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23107    }
23108
23109    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23110            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23111        int size = pkgList.length;
23112        if (size > 0) {
23113            // Send broadcasts here
23114            Bundle extras = new Bundle();
23115            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23116            if (uidArr != null) {
23117                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23118            }
23119            if (replacing) {
23120                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23121            }
23122            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23123                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23124            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23125        }
23126    }
23127
23128   /*
23129     * Look at potentially valid container ids from processCids If package
23130     * information doesn't match the one on record or package scanning fails,
23131     * the cid is added to list of removeCids. We currently don't delete stale
23132     * containers.
23133     */
23134    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23135            boolean externalStorage) {
23136        ArrayList<String> pkgList = new ArrayList<String>();
23137        Set<AsecInstallArgs> keys = processCids.keySet();
23138
23139        for (AsecInstallArgs args : keys) {
23140            String codePath = processCids.get(args);
23141            if (DEBUG_SD_INSTALL)
23142                Log.i(TAG, "Loading container : " + args.cid);
23143            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23144            try {
23145                // Make sure there are no container errors first.
23146                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23147                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23148                            + " when installing from sdcard");
23149                    continue;
23150                }
23151                // Check code path here.
23152                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23153                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23154                            + " does not match one in settings " + codePath);
23155                    continue;
23156                }
23157                // Parse package
23158                int parseFlags = mDefParseFlags;
23159                if (args.isExternalAsec()) {
23160                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23161                }
23162                if (args.isFwdLocked()) {
23163                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23164                }
23165
23166                synchronized (mInstallLock) {
23167                    PackageParser.Package pkg = null;
23168                    try {
23169                        // Sadly we don't know the package name yet to freeze it
23170                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23171                                SCAN_IGNORE_FROZEN, 0, null);
23172                    } catch (PackageManagerException e) {
23173                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23174                    }
23175                    // Scan the package
23176                    if (pkg != null) {
23177                        /*
23178                         * TODO why is the lock being held? doPostInstall is
23179                         * called in other places without the lock. This needs
23180                         * to be straightened out.
23181                         */
23182                        // writer
23183                        synchronized (mPackages) {
23184                            retCode = PackageManager.INSTALL_SUCCEEDED;
23185                            pkgList.add(pkg.packageName);
23186                            // Post process args
23187                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23188                                    pkg.applicationInfo.uid);
23189                        }
23190                    } else {
23191                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23192                    }
23193                }
23194
23195            } finally {
23196                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23197                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23198                }
23199            }
23200        }
23201        // writer
23202        synchronized (mPackages) {
23203            // If the platform SDK has changed since the last time we booted,
23204            // we need to re-grant app permission to catch any new ones that
23205            // appear. This is really a hack, and means that apps can in some
23206            // cases get permissions that the user didn't initially explicitly
23207            // allow... it would be nice to have some better way to handle
23208            // this situation.
23209            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23210                    : mSettings.getInternalVersion();
23211            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23212                    : StorageManager.UUID_PRIVATE_INTERNAL;
23213
23214            int updateFlags = UPDATE_PERMISSIONS_ALL;
23215            if (ver.sdkVersion != mSdkVersion) {
23216                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23217                        + mSdkVersion + "; regranting permissions for external");
23218                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23219            }
23220            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23221
23222            // Yay, everything is now upgraded
23223            ver.forceCurrent();
23224
23225            // can downgrade to reader
23226            // Persist settings
23227            mSettings.writeLPr();
23228        }
23229        // Send a broadcast to let everyone know we are done processing
23230        if (pkgList.size() > 0) {
23231            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23232        }
23233    }
23234
23235   /*
23236     * Utility method to unload a list of specified containers
23237     */
23238    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23239        // Just unmount all valid containers.
23240        for (AsecInstallArgs arg : cidArgs) {
23241            synchronized (mInstallLock) {
23242                arg.doPostDeleteLI(false);
23243           }
23244       }
23245   }
23246
23247    /*
23248     * Unload packages mounted on external media. This involves deleting package
23249     * data from internal structures, sending broadcasts about disabled packages,
23250     * gc'ing to free up references, unmounting all secure containers
23251     * corresponding to packages on external media, and posting a
23252     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23253     * that we always have to post this message if status has been requested no
23254     * matter what.
23255     */
23256    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23257            final boolean reportStatus) {
23258        if (DEBUG_SD_INSTALL)
23259            Log.i(TAG, "unloading media packages");
23260        ArrayList<String> pkgList = new ArrayList<String>();
23261        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23262        final Set<AsecInstallArgs> keys = processCids.keySet();
23263        for (AsecInstallArgs args : keys) {
23264            String pkgName = args.getPackageName();
23265            if (DEBUG_SD_INSTALL)
23266                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23267            // Delete package internally
23268            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23269            synchronized (mInstallLock) {
23270                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23271                final boolean res;
23272                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23273                        "unloadMediaPackages")) {
23274                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23275                            null);
23276                }
23277                if (res) {
23278                    pkgList.add(pkgName);
23279                } else {
23280                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23281                    failedList.add(args);
23282                }
23283            }
23284        }
23285
23286        // reader
23287        synchronized (mPackages) {
23288            // We didn't update the settings after removing each package;
23289            // write them now for all packages.
23290            mSettings.writeLPr();
23291        }
23292
23293        // We have to absolutely send UPDATED_MEDIA_STATUS only
23294        // after confirming that all the receivers processed the ordered
23295        // broadcast when packages get disabled, force a gc to clean things up.
23296        // and unload all the containers.
23297        if (pkgList.size() > 0) {
23298            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23299                    new IIntentReceiver.Stub() {
23300                public void performReceive(Intent intent, int resultCode, String data,
23301                        Bundle extras, boolean ordered, boolean sticky,
23302                        int sendingUser) throws RemoteException {
23303                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23304                            reportStatus ? 1 : 0, 1, keys);
23305                    mHandler.sendMessage(msg);
23306                }
23307            });
23308        } else {
23309            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23310                    keys);
23311            mHandler.sendMessage(msg);
23312        }
23313    }
23314
23315    private void loadPrivatePackages(final VolumeInfo vol) {
23316        mHandler.post(new Runnable() {
23317            @Override
23318            public void run() {
23319                loadPrivatePackagesInner(vol);
23320            }
23321        });
23322    }
23323
23324    private void loadPrivatePackagesInner(VolumeInfo vol) {
23325        final String volumeUuid = vol.fsUuid;
23326        if (TextUtils.isEmpty(volumeUuid)) {
23327            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23328            return;
23329        }
23330
23331        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23332        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23333        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23334
23335        final VersionInfo ver;
23336        final List<PackageSetting> packages;
23337        synchronized (mPackages) {
23338            ver = mSettings.findOrCreateVersion(volumeUuid);
23339            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23340        }
23341
23342        for (PackageSetting ps : packages) {
23343            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23344            synchronized (mInstallLock) {
23345                final PackageParser.Package pkg;
23346                try {
23347                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23348                    loaded.add(pkg.applicationInfo);
23349
23350                } catch (PackageManagerException e) {
23351                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23352                }
23353
23354                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23355                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23356                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23357                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23358                }
23359            }
23360        }
23361
23362        // Reconcile app data for all started/unlocked users
23363        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23364        final UserManager um = mContext.getSystemService(UserManager.class);
23365        UserManagerInternal umInternal = getUserManagerInternal();
23366        for (UserInfo user : um.getUsers()) {
23367            final int flags;
23368            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23369                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23370            } else if (umInternal.isUserRunning(user.id)) {
23371                flags = StorageManager.FLAG_STORAGE_DE;
23372            } else {
23373                continue;
23374            }
23375
23376            try {
23377                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23378                synchronized (mInstallLock) {
23379                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23380                }
23381            } catch (IllegalStateException e) {
23382                // Device was probably ejected, and we'll process that event momentarily
23383                Slog.w(TAG, "Failed to prepare storage: " + e);
23384            }
23385        }
23386
23387        synchronized (mPackages) {
23388            int updateFlags = UPDATE_PERMISSIONS_ALL;
23389            if (ver.sdkVersion != mSdkVersion) {
23390                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23391                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23392                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23393            }
23394            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23395
23396            // Yay, everything is now upgraded
23397            ver.forceCurrent();
23398
23399            mSettings.writeLPr();
23400        }
23401
23402        for (PackageFreezer freezer : freezers) {
23403            freezer.close();
23404        }
23405
23406        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23407        sendResourcesChangedBroadcast(true, false, loaded, null);
23408        mLoadedVolumes.add(vol.getId());
23409    }
23410
23411    private void unloadPrivatePackages(final VolumeInfo vol) {
23412        mHandler.post(new Runnable() {
23413            @Override
23414            public void run() {
23415                unloadPrivatePackagesInner(vol);
23416            }
23417        });
23418    }
23419
23420    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23421        final String volumeUuid = vol.fsUuid;
23422        if (TextUtils.isEmpty(volumeUuid)) {
23423            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23424            return;
23425        }
23426
23427        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23428        synchronized (mInstallLock) {
23429        synchronized (mPackages) {
23430            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23431            for (PackageSetting ps : packages) {
23432                if (ps.pkg == null) continue;
23433
23434                final ApplicationInfo info = ps.pkg.applicationInfo;
23435                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23436                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23437
23438                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23439                        "unloadPrivatePackagesInner")) {
23440                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23441                            false, null)) {
23442                        unloaded.add(info);
23443                    } else {
23444                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23445                    }
23446                }
23447
23448                // Try very hard to release any references to this package
23449                // so we don't risk the system server being killed due to
23450                // open FDs
23451                AttributeCache.instance().removePackage(ps.name);
23452            }
23453
23454            mSettings.writeLPr();
23455        }
23456        }
23457
23458        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23459        sendResourcesChangedBroadcast(false, false, unloaded, null);
23460        mLoadedVolumes.remove(vol.getId());
23461
23462        // Try very hard to release any references to this path so we don't risk
23463        // the system server being killed due to open FDs
23464        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23465
23466        for (int i = 0; i < 3; i++) {
23467            System.gc();
23468            System.runFinalization();
23469        }
23470    }
23471
23472    private void assertPackageKnown(String volumeUuid, String packageName)
23473            throws PackageManagerException {
23474        synchronized (mPackages) {
23475            // Normalize package name to handle renamed packages
23476            packageName = normalizePackageNameLPr(packageName);
23477
23478            final PackageSetting ps = mSettings.mPackages.get(packageName);
23479            if (ps == null) {
23480                throw new PackageManagerException("Package " + packageName + " is unknown");
23481            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23482                throw new PackageManagerException(
23483                        "Package " + packageName + " found on unknown volume " + volumeUuid
23484                                + "; expected volume " + ps.volumeUuid);
23485            }
23486        }
23487    }
23488
23489    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23490            throws PackageManagerException {
23491        synchronized (mPackages) {
23492            // Normalize package name to handle renamed packages
23493            packageName = normalizePackageNameLPr(packageName);
23494
23495            final PackageSetting ps = mSettings.mPackages.get(packageName);
23496            if (ps == null) {
23497                throw new PackageManagerException("Package " + packageName + " is unknown");
23498            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23499                throw new PackageManagerException(
23500                        "Package " + packageName + " found on unknown volume " + volumeUuid
23501                                + "; expected volume " + ps.volumeUuid);
23502            } else if (!ps.getInstalled(userId)) {
23503                throw new PackageManagerException(
23504                        "Package " + packageName + " not installed for user " + userId);
23505            }
23506        }
23507    }
23508
23509    private List<String> collectAbsoluteCodePaths() {
23510        synchronized (mPackages) {
23511            List<String> codePaths = new ArrayList<>();
23512            final int packageCount = mSettings.mPackages.size();
23513            for (int i = 0; i < packageCount; i++) {
23514                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23515                codePaths.add(ps.codePath.getAbsolutePath());
23516            }
23517            return codePaths;
23518        }
23519    }
23520
23521    /**
23522     * Examine all apps present on given mounted volume, and destroy apps that
23523     * aren't expected, either due to uninstallation or reinstallation on
23524     * another volume.
23525     */
23526    private void reconcileApps(String volumeUuid) {
23527        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23528        List<File> filesToDelete = null;
23529
23530        final File[] files = FileUtils.listFilesOrEmpty(
23531                Environment.getDataAppDirectory(volumeUuid));
23532        for (File file : files) {
23533            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23534                    && !PackageInstallerService.isStageName(file.getName());
23535            if (!isPackage) {
23536                // Ignore entries which are not packages
23537                continue;
23538            }
23539
23540            String absolutePath = file.getAbsolutePath();
23541
23542            boolean pathValid = false;
23543            final int absoluteCodePathCount = absoluteCodePaths.size();
23544            for (int i = 0; i < absoluteCodePathCount; i++) {
23545                String absoluteCodePath = absoluteCodePaths.get(i);
23546                if (absolutePath.startsWith(absoluteCodePath)) {
23547                    pathValid = true;
23548                    break;
23549                }
23550            }
23551
23552            if (!pathValid) {
23553                if (filesToDelete == null) {
23554                    filesToDelete = new ArrayList<>();
23555                }
23556                filesToDelete.add(file);
23557            }
23558        }
23559
23560        if (filesToDelete != null) {
23561            final int fileToDeleteCount = filesToDelete.size();
23562            for (int i = 0; i < fileToDeleteCount; i++) {
23563                File fileToDelete = filesToDelete.get(i);
23564                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23565                synchronized (mInstallLock) {
23566                    removeCodePathLI(fileToDelete);
23567                }
23568            }
23569        }
23570    }
23571
23572    /**
23573     * Reconcile all app data for the given user.
23574     * <p>
23575     * Verifies that directories exist and that ownership and labeling is
23576     * correct for all installed apps on all mounted volumes.
23577     */
23578    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23579        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23580        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23581            final String volumeUuid = vol.getFsUuid();
23582            synchronized (mInstallLock) {
23583                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23584            }
23585        }
23586    }
23587
23588    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23589            boolean migrateAppData) {
23590        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23591    }
23592
23593    /**
23594     * Reconcile all app data on given mounted volume.
23595     * <p>
23596     * Destroys app data that isn't expected, either due to uninstallation or
23597     * reinstallation on another volume.
23598     * <p>
23599     * Verifies that directories exist and that ownership and labeling is
23600     * correct for all installed apps.
23601     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23602     */
23603    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23604            boolean migrateAppData, boolean onlyCoreApps) {
23605        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23606                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23607        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23608
23609        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23610        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23611
23612        // First look for stale data that doesn't belong, and check if things
23613        // have changed since we did our last restorecon
23614        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23615            if (StorageManager.isFileEncryptedNativeOrEmulated()
23616                    && !StorageManager.isUserKeyUnlocked(userId)) {
23617                throw new RuntimeException(
23618                        "Yikes, someone asked us to reconcile CE storage while " + userId
23619                                + " was still locked; this would have caused massive data loss!");
23620            }
23621
23622            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23623            for (File file : files) {
23624                final String packageName = file.getName();
23625                try {
23626                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23627                } catch (PackageManagerException e) {
23628                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23629                    try {
23630                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23631                                StorageManager.FLAG_STORAGE_CE, 0);
23632                    } catch (InstallerException e2) {
23633                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23634                    }
23635                }
23636            }
23637        }
23638        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23639            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23640            for (File file : files) {
23641                final String packageName = file.getName();
23642                try {
23643                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23644                } catch (PackageManagerException e) {
23645                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23646                    try {
23647                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23648                                StorageManager.FLAG_STORAGE_DE, 0);
23649                    } catch (InstallerException e2) {
23650                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23651                    }
23652                }
23653            }
23654        }
23655
23656        // Ensure that data directories are ready to roll for all packages
23657        // installed for this volume and user
23658        final List<PackageSetting> packages;
23659        synchronized (mPackages) {
23660            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23661        }
23662        int preparedCount = 0;
23663        for (PackageSetting ps : packages) {
23664            final String packageName = ps.name;
23665            if (ps.pkg == null) {
23666                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23667                // TODO: might be due to legacy ASEC apps; we should circle back
23668                // and reconcile again once they're scanned
23669                continue;
23670            }
23671            // Skip non-core apps if requested
23672            if (onlyCoreApps && !ps.pkg.coreApp) {
23673                result.add(packageName);
23674                continue;
23675            }
23676
23677            if (ps.getInstalled(userId)) {
23678                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23679                preparedCount++;
23680            }
23681        }
23682
23683        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23684        return result;
23685    }
23686
23687    /**
23688     * Prepare app data for the given app just after it was installed or
23689     * upgraded. This method carefully only touches users that it's installed
23690     * for, and it forces a restorecon to handle any seinfo changes.
23691     * <p>
23692     * Verifies that directories exist and that ownership and labeling is
23693     * correct for all installed apps. If there is an ownership mismatch, it
23694     * will try recovering system apps by wiping data; third-party app data is
23695     * left intact.
23696     * <p>
23697     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23698     */
23699    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23700        final PackageSetting ps;
23701        synchronized (mPackages) {
23702            ps = mSettings.mPackages.get(pkg.packageName);
23703            mSettings.writeKernelMappingLPr(ps);
23704        }
23705
23706        final UserManager um = mContext.getSystemService(UserManager.class);
23707        UserManagerInternal umInternal = getUserManagerInternal();
23708        for (UserInfo user : um.getUsers()) {
23709            final int flags;
23710            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23711                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23712            } else if (umInternal.isUserRunning(user.id)) {
23713                flags = StorageManager.FLAG_STORAGE_DE;
23714            } else {
23715                continue;
23716            }
23717
23718            if (ps.getInstalled(user.id)) {
23719                // TODO: when user data is locked, mark that we're still dirty
23720                prepareAppDataLIF(pkg, user.id, flags);
23721            }
23722        }
23723    }
23724
23725    /**
23726     * Prepare app data for the given app.
23727     * <p>
23728     * Verifies that directories exist and that ownership and labeling is
23729     * correct for all installed apps. If there is an ownership mismatch, this
23730     * will try recovering system apps by wiping data; third-party app data is
23731     * left intact.
23732     */
23733    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23734        if (pkg == null) {
23735            Slog.wtf(TAG, "Package was null!", new Throwable());
23736            return;
23737        }
23738        prepareAppDataLeafLIF(pkg, userId, flags);
23739        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23740        for (int i = 0; i < childCount; i++) {
23741            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23742        }
23743    }
23744
23745    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23746            boolean maybeMigrateAppData) {
23747        prepareAppDataLIF(pkg, userId, flags);
23748
23749        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23750            // We may have just shuffled around app data directories, so
23751            // prepare them one more time
23752            prepareAppDataLIF(pkg, userId, flags);
23753        }
23754    }
23755
23756    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23757        if (DEBUG_APP_DATA) {
23758            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23759                    + Integer.toHexString(flags));
23760        }
23761
23762        final String volumeUuid = pkg.volumeUuid;
23763        final String packageName = pkg.packageName;
23764        final ApplicationInfo app = pkg.applicationInfo;
23765        final int appId = UserHandle.getAppId(app.uid);
23766
23767        Preconditions.checkNotNull(app.seInfo);
23768
23769        long ceDataInode = -1;
23770        try {
23771            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23772                    appId, app.seInfo, app.targetSdkVersion);
23773        } catch (InstallerException e) {
23774            if (app.isSystemApp()) {
23775                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23776                        + ", but trying to recover: " + e);
23777                destroyAppDataLeafLIF(pkg, userId, flags);
23778                try {
23779                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23780                            appId, app.seInfo, app.targetSdkVersion);
23781                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23782                } catch (InstallerException e2) {
23783                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23784                }
23785            } else {
23786                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23787            }
23788        }
23789
23790        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23791            // TODO: mark this structure as dirty so we persist it!
23792            synchronized (mPackages) {
23793                final PackageSetting ps = mSettings.mPackages.get(packageName);
23794                if (ps != null) {
23795                    ps.setCeDataInode(ceDataInode, userId);
23796                }
23797            }
23798        }
23799
23800        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23801    }
23802
23803    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23804        if (pkg == null) {
23805            Slog.wtf(TAG, "Package was null!", new Throwable());
23806            return;
23807        }
23808        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23809        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23810        for (int i = 0; i < childCount; i++) {
23811            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23812        }
23813    }
23814
23815    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23816        final String volumeUuid = pkg.volumeUuid;
23817        final String packageName = pkg.packageName;
23818        final ApplicationInfo app = pkg.applicationInfo;
23819
23820        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23821            // Create a native library symlink only if we have native libraries
23822            // and if the native libraries are 32 bit libraries. We do not provide
23823            // this symlink for 64 bit libraries.
23824            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23825                final String nativeLibPath = app.nativeLibraryDir;
23826                try {
23827                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23828                            nativeLibPath, userId);
23829                } catch (InstallerException e) {
23830                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23831                }
23832            }
23833        }
23834    }
23835
23836    /**
23837     * For system apps on non-FBE devices, this method migrates any existing
23838     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23839     * requested by the app.
23840     */
23841    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23842        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23843                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23844            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23845                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23846            try {
23847                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23848                        storageTarget);
23849            } catch (InstallerException e) {
23850                logCriticalInfo(Log.WARN,
23851                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23852            }
23853            return true;
23854        } else {
23855            return false;
23856        }
23857    }
23858
23859    public PackageFreezer freezePackage(String packageName, String killReason) {
23860        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23861    }
23862
23863    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23864        return new PackageFreezer(packageName, userId, killReason);
23865    }
23866
23867    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23868            String killReason) {
23869        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23870    }
23871
23872    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23873            String killReason) {
23874        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23875            return new PackageFreezer();
23876        } else {
23877            return freezePackage(packageName, userId, killReason);
23878        }
23879    }
23880
23881    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23882            String killReason) {
23883        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23884    }
23885
23886    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23887            String killReason) {
23888        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23889            return new PackageFreezer();
23890        } else {
23891            return freezePackage(packageName, userId, killReason);
23892        }
23893    }
23894
23895    /**
23896     * Class that freezes and kills the given package upon creation, and
23897     * unfreezes it upon closing. This is typically used when doing surgery on
23898     * app code/data to prevent the app from running while you're working.
23899     */
23900    private class PackageFreezer implements AutoCloseable {
23901        private final String mPackageName;
23902        private final PackageFreezer[] mChildren;
23903
23904        private final boolean mWeFroze;
23905
23906        private final AtomicBoolean mClosed = new AtomicBoolean();
23907        private final CloseGuard mCloseGuard = CloseGuard.get();
23908
23909        /**
23910         * Create and return a stub freezer that doesn't actually do anything,
23911         * typically used when someone requested
23912         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23913         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23914         */
23915        public PackageFreezer() {
23916            mPackageName = null;
23917            mChildren = null;
23918            mWeFroze = false;
23919            mCloseGuard.open("close");
23920        }
23921
23922        public PackageFreezer(String packageName, int userId, String killReason) {
23923            synchronized (mPackages) {
23924                mPackageName = packageName;
23925                mWeFroze = mFrozenPackages.add(mPackageName);
23926
23927                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23928                if (ps != null) {
23929                    killApplication(ps.name, ps.appId, userId, killReason);
23930                }
23931
23932                final PackageParser.Package p = mPackages.get(packageName);
23933                if (p != null && p.childPackages != null) {
23934                    final int N = p.childPackages.size();
23935                    mChildren = new PackageFreezer[N];
23936                    for (int i = 0; i < N; i++) {
23937                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23938                                userId, killReason);
23939                    }
23940                } else {
23941                    mChildren = null;
23942                }
23943            }
23944            mCloseGuard.open("close");
23945        }
23946
23947        @Override
23948        protected void finalize() throws Throwable {
23949            try {
23950                if (mCloseGuard != null) {
23951                    mCloseGuard.warnIfOpen();
23952                }
23953
23954                close();
23955            } finally {
23956                super.finalize();
23957            }
23958        }
23959
23960        @Override
23961        public void close() {
23962            mCloseGuard.close();
23963            if (mClosed.compareAndSet(false, true)) {
23964                synchronized (mPackages) {
23965                    if (mWeFroze) {
23966                        mFrozenPackages.remove(mPackageName);
23967                    }
23968
23969                    if (mChildren != null) {
23970                        for (PackageFreezer freezer : mChildren) {
23971                            freezer.close();
23972                        }
23973                    }
23974                }
23975            }
23976        }
23977    }
23978
23979    /**
23980     * Verify that given package is currently frozen.
23981     */
23982    private void checkPackageFrozen(String packageName) {
23983        synchronized (mPackages) {
23984            if (!mFrozenPackages.contains(packageName)) {
23985                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23986            }
23987        }
23988    }
23989
23990    @Override
23991    public int movePackage(final String packageName, final String volumeUuid) {
23992        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23993
23994        final int callingUid = Binder.getCallingUid();
23995        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23996        final int moveId = mNextMoveId.getAndIncrement();
23997        mHandler.post(new Runnable() {
23998            @Override
23999            public void run() {
24000                try {
24001                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24002                } catch (PackageManagerException e) {
24003                    Slog.w(TAG, "Failed to move " + packageName, e);
24004                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24005                }
24006            }
24007        });
24008        return moveId;
24009    }
24010
24011    private void movePackageInternal(final String packageName, final String volumeUuid,
24012            final int moveId, final int callingUid, UserHandle user)
24013                    throws PackageManagerException {
24014        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24015        final PackageManager pm = mContext.getPackageManager();
24016
24017        final boolean currentAsec;
24018        final String currentVolumeUuid;
24019        final File codeFile;
24020        final String installerPackageName;
24021        final String packageAbiOverride;
24022        final int appId;
24023        final String seinfo;
24024        final String label;
24025        final int targetSdkVersion;
24026        final PackageFreezer freezer;
24027        final int[] installedUserIds;
24028
24029        // reader
24030        synchronized (mPackages) {
24031            final PackageParser.Package pkg = mPackages.get(packageName);
24032            final PackageSetting ps = mSettings.mPackages.get(packageName);
24033            if (pkg == null
24034                    || ps == null
24035                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24036                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24037            }
24038            if (pkg.applicationInfo.isSystemApp()) {
24039                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24040                        "Cannot move system application");
24041            }
24042
24043            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24044            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24045                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24046            if (isInternalStorage && !allow3rdPartyOnInternal) {
24047                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24048                        "3rd party apps are not allowed on internal storage");
24049            }
24050
24051            if (pkg.applicationInfo.isExternalAsec()) {
24052                currentAsec = true;
24053                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24054            } else if (pkg.applicationInfo.isForwardLocked()) {
24055                currentAsec = true;
24056                currentVolumeUuid = "forward_locked";
24057            } else {
24058                currentAsec = false;
24059                currentVolumeUuid = ps.volumeUuid;
24060
24061                final File probe = new File(pkg.codePath);
24062                final File probeOat = new File(probe, "oat");
24063                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24064                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24065                            "Move only supported for modern cluster style installs");
24066                }
24067            }
24068
24069            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24070                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24071                        "Package already moved to " + volumeUuid);
24072            }
24073            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24074                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24075                        "Device admin cannot be moved");
24076            }
24077
24078            if (mFrozenPackages.contains(packageName)) {
24079                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24080                        "Failed to move already frozen package");
24081            }
24082
24083            codeFile = new File(pkg.codePath);
24084            installerPackageName = ps.installerPackageName;
24085            packageAbiOverride = ps.cpuAbiOverrideString;
24086            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24087            seinfo = pkg.applicationInfo.seInfo;
24088            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24089            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24090            freezer = freezePackage(packageName, "movePackageInternal");
24091            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24092        }
24093
24094        final Bundle extras = new Bundle();
24095        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24096        extras.putString(Intent.EXTRA_TITLE, label);
24097        mMoveCallbacks.notifyCreated(moveId, extras);
24098
24099        int installFlags;
24100        final boolean moveCompleteApp;
24101        final File measurePath;
24102
24103        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24104            installFlags = INSTALL_INTERNAL;
24105            moveCompleteApp = !currentAsec;
24106            measurePath = Environment.getDataAppDirectory(volumeUuid);
24107        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24108            installFlags = INSTALL_EXTERNAL;
24109            moveCompleteApp = false;
24110            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24111        } else {
24112            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24113            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24114                    || !volume.isMountedWritable()) {
24115                freezer.close();
24116                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24117                        "Move location not mounted private volume");
24118            }
24119
24120            Preconditions.checkState(!currentAsec);
24121
24122            installFlags = INSTALL_INTERNAL;
24123            moveCompleteApp = true;
24124            measurePath = Environment.getDataAppDirectory(volumeUuid);
24125        }
24126
24127        // If we're moving app data around, we need all the users unlocked
24128        if (moveCompleteApp) {
24129            for (int userId : installedUserIds) {
24130                if (StorageManager.isFileEncryptedNativeOrEmulated()
24131                        && !StorageManager.isUserKeyUnlocked(userId)) {
24132                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24133                            "User " + userId + " must be unlocked");
24134                }
24135            }
24136        }
24137
24138        final PackageStats stats = new PackageStats(null, -1);
24139        synchronized (mInstaller) {
24140            for (int userId : installedUserIds) {
24141                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24142                    freezer.close();
24143                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24144                            "Failed to measure package size");
24145                }
24146            }
24147        }
24148
24149        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24150                + stats.dataSize);
24151
24152        final long startFreeBytes = measurePath.getUsableSpace();
24153        final long sizeBytes;
24154        if (moveCompleteApp) {
24155            sizeBytes = stats.codeSize + stats.dataSize;
24156        } else {
24157            sizeBytes = stats.codeSize;
24158        }
24159
24160        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24161            freezer.close();
24162            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24163                    "Not enough free space to move");
24164        }
24165
24166        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24167
24168        final CountDownLatch installedLatch = new CountDownLatch(1);
24169        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24170            @Override
24171            public void onUserActionRequired(Intent intent) throws RemoteException {
24172                throw new IllegalStateException();
24173            }
24174
24175            @Override
24176            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24177                    Bundle extras) throws RemoteException {
24178                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24179                        + PackageManager.installStatusToString(returnCode, msg));
24180
24181                installedLatch.countDown();
24182                freezer.close();
24183
24184                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24185                switch (status) {
24186                    case PackageInstaller.STATUS_SUCCESS:
24187                        mMoveCallbacks.notifyStatusChanged(moveId,
24188                                PackageManager.MOVE_SUCCEEDED);
24189                        break;
24190                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24191                        mMoveCallbacks.notifyStatusChanged(moveId,
24192                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24193                        break;
24194                    default:
24195                        mMoveCallbacks.notifyStatusChanged(moveId,
24196                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24197                        break;
24198                }
24199            }
24200        };
24201
24202        final MoveInfo move;
24203        if (moveCompleteApp) {
24204            // Kick off a thread to report progress estimates
24205            new Thread() {
24206                @Override
24207                public void run() {
24208                    while (true) {
24209                        try {
24210                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24211                                break;
24212                            }
24213                        } catch (InterruptedException ignored) {
24214                        }
24215
24216                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24217                        final int progress = 10 + (int) MathUtils.constrain(
24218                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24219                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24220                    }
24221                }
24222            }.start();
24223
24224            final String dataAppName = codeFile.getName();
24225            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24226                    dataAppName, appId, seinfo, targetSdkVersion);
24227        } else {
24228            move = null;
24229        }
24230
24231        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24232
24233        final Message msg = mHandler.obtainMessage(INIT_COPY);
24234        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24235        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24236                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24237                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24238                PackageManager.INSTALL_REASON_UNKNOWN);
24239        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24240        msg.obj = params;
24241
24242        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24243                System.identityHashCode(msg.obj));
24244        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24245                System.identityHashCode(msg.obj));
24246
24247        mHandler.sendMessage(msg);
24248    }
24249
24250    @Override
24251    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24252        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24253
24254        final int realMoveId = mNextMoveId.getAndIncrement();
24255        final Bundle extras = new Bundle();
24256        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24257        mMoveCallbacks.notifyCreated(realMoveId, extras);
24258
24259        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24260            @Override
24261            public void onCreated(int moveId, Bundle extras) {
24262                // Ignored
24263            }
24264
24265            @Override
24266            public void onStatusChanged(int moveId, int status, long estMillis) {
24267                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24268            }
24269        };
24270
24271        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24272        storage.setPrimaryStorageUuid(volumeUuid, callback);
24273        return realMoveId;
24274    }
24275
24276    @Override
24277    public int getMoveStatus(int moveId) {
24278        mContext.enforceCallingOrSelfPermission(
24279                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24280        return mMoveCallbacks.mLastStatus.get(moveId);
24281    }
24282
24283    @Override
24284    public void registerMoveCallback(IPackageMoveObserver callback) {
24285        mContext.enforceCallingOrSelfPermission(
24286                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24287        mMoveCallbacks.register(callback);
24288    }
24289
24290    @Override
24291    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24292        mContext.enforceCallingOrSelfPermission(
24293                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24294        mMoveCallbacks.unregister(callback);
24295    }
24296
24297    @Override
24298    public boolean setInstallLocation(int loc) {
24299        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24300                null);
24301        if (getInstallLocation() == loc) {
24302            return true;
24303        }
24304        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24305                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24306            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24307                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24308            return true;
24309        }
24310        return false;
24311   }
24312
24313    @Override
24314    public int getInstallLocation() {
24315        // allow instant app access
24316        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24317                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24318                PackageHelper.APP_INSTALL_AUTO);
24319    }
24320
24321    /** Called by UserManagerService */
24322    void cleanUpUser(UserManagerService userManager, int userHandle) {
24323        synchronized (mPackages) {
24324            mDirtyUsers.remove(userHandle);
24325            mUserNeedsBadging.delete(userHandle);
24326            mSettings.removeUserLPw(userHandle);
24327            mPendingBroadcasts.remove(userHandle);
24328            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24329            removeUnusedPackagesLPw(userManager, userHandle);
24330        }
24331    }
24332
24333    /**
24334     * We're removing userHandle and would like to remove any downloaded packages
24335     * that are no longer in use by any other user.
24336     * @param userHandle the user being removed
24337     */
24338    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24339        final boolean DEBUG_CLEAN_APKS = false;
24340        int [] users = userManager.getUserIds();
24341        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24342        while (psit.hasNext()) {
24343            PackageSetting ps = psit.next();
24344            if (ps.pkg == null) {
24345                continue;
24346            }
24347            final String packageName = ps.pkg.packageName;
24348            // Skip over if system app
24349            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24350                continue;
24351            }
24352            if (DEBUG_CLEAN_APKS) {
24353                Slog.i(TAG, "Checking package " + packageName);
24354            }
24355            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24356            if (keep) {
24357                if (DEBUG_CLEAN_APKS) {
24358                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24359                }
24360            } else {
24361                for (int i = 0; i < users.length; i++) {
24362                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24363                        keep = true;
24364                        if (DEBUG_CLEAN_APKS) {
24365                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24366                                    + users[i]);
24367                        }
24368                        break;
24369                    }
24370                }
24371            }
24372            if (!keep) {
24373                if (DEBUG_CLEAN_APKS) {
24374                    Slog.i(TAG, "  Removing package " + packageName);
24375                }
24376                mHandler.post(new Runnable() {
24377                    public void run() {
24378                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24379                                userHandle, 0);
24380                    } //end run
24381                });
24382            }
24383        }
24384    }
24385
24386    /** Called by UserManagerService */
24387    void createNewUser(int userId, String[] disallowedPackages) {
24388        synchronized (mInstallLock) {
24389            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24390        }
24391        synchronized (mPackages) {
24392            scheduleWritePackageRestrictionsLocked(userId);
24393            scheduleWritePackageListLocked(userId);
24394            applyFactoryDefaultBrowserLPw(userId);
24395            primeDomainVerificationsLPw(userId);
24396        }
24397    }
24398
24399    void onNewUserCreated(final int userId) {
24400        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24401        // If permission review for legacy apps is required, we represent
24402        // dagerous permissions for such apps as always granted runtime
24403        // permissions to keep per user flag state whether review is needed.
24404        // Hence, if a new user is added we have to propagate dangerous
24405        // permission grants for these legacy apps.
24406        if (mPermissionReviewRequired) {
24407            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24408                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24409        }
24410    }
24411
24412    @Override
24413    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24414        mContext.enforceCallingOrSelfPermission(
24415                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24416                "Only package verification agents can read the verifier device identity");
24417
24418        synchronized (mPackages) {
24419            return mSettings.getVerifierDeviceIdentityLPw();
24420        }
24421    }
24422
24423    @Override
24424    public void setPermissionEnforced(String permission, boolean enforced) {
24425        // TODO: Now that we no longer change GID for storage, this should to away.
24426        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24427                "setPermissionEnforced");
24428        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24429            synchronized (mPackages) {
24430                if (mSettings.mReadExternalStorageEnforced == null
24431                        || mSettings.mReadExternalStorageEnforced != enforced) {
24432                    mSettings.mReadExternalStorageEnforced = enforced;
24433                    mSettings.writeLPr();
24434                }
24435            }
24436            // kill any non-foreground processes so we restart them and
24437            // grant/revoke the GID.
24438            final IActivityManager am = ActivityManager.getService();
24439            if (am != null) {
24440                final long token = Binder.clearCallingIdentity();
24441                try {
24442                    am.killProcessesBelowForeground("setPermissionEnforcement");
24443                } catch (RemoteException e) {
24444                } finally {
24445                    Binder.restoreCallingIdentity(token);
24446                }
24447            }
24448        } else {
24449            throw new IllegalArgumentException("No selective enforcement for " + permission);
24450        }
24451    }
24452
24453    @Override
24454    @Deprecated
24455    public boolean isPermissionEnforced(String permission) {
24456        // allow instant applications
24457        return true;
24458    }
24459
24460    @Override
24461    public boolean isStorageLow() {
24462        // allow instant applications
24463        final long token = Binder.clearCallingIdentity();
24464        try {
24465            final DeviceStorageMonitorInternal
24466                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24467            if (dsm != null) {
24468                return dsm.isMemoryLow();
24469            } else {
24470                return false;
24471            }
24472        } finally {
24473            Binder.restoreCallingIdentity(token);
24474        }
24475    }
24476
24477    @Override
24478    public IPackageInstaller getPackageInstaller() {
24479        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24480            return null;
24481        }
24482        return mInstallerService;
24483    }
24484
24485    private boolean userNeedsBadging(int userId) {
24486        int index = mUserNeedsBadging.indexOfKey(userId);
24487        if (index < 0) {
24488            final UserInfo userInfo;
24489            final long token = Binder.clearCallingIdentity();
24490            try {
24491                userInfo = sUserManager.getUserInfo(userId);
24492            } finally {
24493                Binder.restoreCallingIdentity(token);
24494            }
24495            final boolean b;
24496            if (userInfo != null && userInfo.isManagedProfile()) {
24497                b = true;
24498            } else {
24499                b = false;
24500            }
24501            mUserNeedsBadging.put(userId, b);
24502            return b;
24503        }
24504        return mUserNeedsBadging.valueAt(index);
24505    }
24506
24507    @Override
24508    public KeySet getKeySetByAlias(String packageName, String alias) {
24509        if (packageName == null || alias == null) {
24510            return null;
24511        }
24512        synchronized(mPackages) {
24513            final PackageParser.Package pkg = mPackages.get(packageName);
24514            if (pkg == null) {
24515                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24516                throw new IllegalArgumentException("Unknown package: " + packageName);
24517            }
24518            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24519            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24520                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24521                throw new IllegalArgumentException("Unknown package: " + packageName);
24522            }
24523            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24524            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24525        }
24526    }
24527
24528    @Override
24529    public KeySet getSigningKeySet(String packageName) {
24530        if (packageName == null) {
24531            return null;
24532        }
24533        synchronized(mPackages) {
24534            final int callingUid = Binder.getCallingUid();
24535            final int callingUserId = UserHandle.getUserId(callingUid);
24536            final PackageParser.Package pkg = mPackages.get(packageName);
24537            if (pkg == null) {
24538                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24539                throw new IllegalArgumentException("Unknown package: " + packageName);
24540            }
24541            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24542            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24543                // filter and pretend the package doesn't exist
24544                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24545                        + ", uid:" + callingUid);
24546                throw new IllegalArgumentException("Unknown package: " + packageName);
24547            }
24548            if (pkg.applicationInfo.uid != callingUid
24549                    && Process.SYSTEM_UID != callingUid) {
24550                throw new SecurityException("May not access signing KeySet of other apps.");
24551            }
24552            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24553            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24554        }
24555    }
24556
24557    @Override
24558    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24559        final int callingUid = Binder.getCallingUid();
24560        if (getInstantAppPackageName(callingUid) != null) {
24561            return false;
24562        }
24563        if (packageName == null || ks == null) {
24564            return false;
24565        }
24566        synchronized(mPackages) {
24567            final PackageParser.Package pkg = mPackages.get(packageName);
24568            if (pkg == null
24569                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24570                            UserHandle.getUserId(callingUid))) {
24571                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24572                throw new IllegalArgumentException("Unknown package: " + packageName);
24573            }
24574            IBinder ksh = ks.getToken();
24575            if (ksh instanceof KeySetHandle) {
24576                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24577                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24578            }
24579            return false;
24580        }
24581    }
24582
24583    @Override
24584    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24585        final int callingUid = Binder.getCallingUid();
24586        if (getInstantAppPackageName(callingUid) != null) {
24587            return false;
24588        }
24589        if (packageName == null || ks == null) {
24590            return false;
24591        }
24592        synchronized(mPackages) {
24593            final PackageParser.Package pkg = mPackages.get(packageName);
24594            if (pkg == null
24595                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24596                            UserHandle.getUserId(callingUid))) {
24597                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24598                throw new IllegalArgumentException("Unknown package: " + packageName);
24599            }
24600            IBinder ksh = ks.getToken();
24601            if (ksh instanceof KeySetHandle) {
24602                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24603                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24604            }
24605            return false;
24606        }
24607    }
24608
24609    private void deletePackageIfUnusedLPr(final String packageName) {
24610        PackageSetting ps = mSettings.mPackages.get(packageName);
24611        if (ps == null) {
24612            return;
24613        }
24614        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24615            // TODO Implement atomic delete if package is unused
24616            // It is currently possible that the package will be deleted even if it is installed
24617            // after this method returns.
24618            mHandler.post(new Runnable() {
24619                public void run() {
24620                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24621                            0, PackageManager.DELETE_ALL_USERS);
24622                }
24623            });
24624        }
24625    }
24626
24627    /**
24628     * Check and throw if the given before/after packages would be considered a
24629     * downgrade.
24630     */
24631    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24632            throws PackageManagerException {
24633        if (after.versionCode < before.mVersionCode) {
24634            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24635                    "Update version code " + after.versionCode + " is older than current "
24636                    + before.mVersionCode);
24637        } else if (after.versionCode == before.mVersionCode) {
24638            if (after.baseRevisionCode < before.baseRevisionCode) {
24639                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24640                        "Update base revision code " + after.baseRevisionCode
24641                        + " is older than current " + before.baseRevisionCode);
24642            }
24643
24644            if (!ArrayUtils.isEmpty(after.splitNames)) {
24645                for (int i = 0; i < after.splitNames.length; i++) {
24646                    final String splitName = after.splitNames[i];
24647                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24648                    if (j != -1) {
24649                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24650                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24651                                    "Update split " + splitName + " revision code "
24652                                    + after.splitRevisionCodes[i] + " is older than current "
24653                                    + before.splitRevisionCodes[j]);
24654                        }
24655                    }
24656                }
24657            }
24658        }
24659    }
24660
24661    private static class MoveCallbacks extends Handler {
24662        private static final int MSG_CREATED = 1;
24663        private static final int MSG_STATUS_CHANGED = 2;
24664
24665        private final RemoteCallbackList<IPackageMoveObserver>
24666                mCallbacks = new RemoteCallbackList<>();
24667
24668        private final SparseIntArray mLastStatus = new SparseIntArray();
24669
24670        public MoveCallbacks(Looper looper) {
24671            super(looper);
24672        }
24673
24674        public void register(IPackageMoveObserver callback) {
24675            mCallbacks.register(callback);
24676        }
24677
24678        public void unregister(IPackageMoveObserver callback) {
24679            mCallbacks.unregister(callback);
24680        }
24681
24682        @Override
24683        public void handleMessage(Message msg) {
24684            final SomeArgs args = (SomeArgs) msg.obj;
24685            final int n = mCallbacks.beginBroadcast();
24686            for (int i = 0; i < n; i++) {
24687                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24688                try {
24689                    invokeCallback(callback, msg.what, args);
24690                } catch (RemoteException ignored) {
24691                }
24692            }
24693            mCallbacks.finishBroadcast();
24694            args.recycle();
24695        }
24696
24697        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24698                throws RemoteException {
24699            switch (what) {
24700                case MSG_CREATED: {
24701                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24702                    break;
24703                }
24704                case MSG_STATUS_CHANGED: {
24705                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24706                    break;
24707                }
24708            }
24709        }
24710
24711        private void notifyCreated(int moveId, Bundle extras) {
24712            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24713
24714            final SomeArgs args = SomeArgs.obtain();
24715            args.argi1 = moveId;
24716            args.arg2 = extras;
24717            obtainMessage(MSG_CREATED, args).sendToTarget();
24718        }
24719
24720        private void notifyStatusChanged(int moveId, int status) {
24721            notifyStatusChanged(moveId, status, -1);
24722        }
24723
24724        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24725            Slog.v(TAG, "Move " + moveId + " status " + status);
24726
24727            final SomeArgs args = SomeArgs.obtain();
24728            args.argi1 = moveId;
24729            args.argi2 = status;
24730            args.arg3 = estMillis;
24731            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24732
24733            synchronized (mLastStatus) {
24734                mLastStatus.put(moveId, status);
24735            }
24736        }
24737    }
24738
24739    private final static class OnPermissionChangeListeners extends Handler {
24740        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24741
24742        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24743                new RemoteCallbackList<>();
24744
24745        public OnPermissionChangeListeners(Looper looper) {
24746            super(looper);
24747        }
24748
24749        @Override
24750        public void handleMessage(Message msg) {
24751            switch (msg.what) {
24752                case MSG_ON_PERMISSIONS_CHANGED: {
24753                    final int uid = msg.arg1;
24754                    handleOnPermissionsChanged(uid);
24755                } break;
24756            }
24757        }
24758
24759        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24760            mPermissionListeners.register(listener);
24761
24762        }
24763
24764        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24765            mPermissionListeners.unregister(listener);
24766        }
24767
24768        public void onPermissionsChanged(int uid) {
24769            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24770                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24771            }
24772        }
24773
24774        private void handleOnPermissionsChanged(int uid) {
24775            final int count = mPermissionListeners.beginBroadcast();
24776            try {
24777                for (int i = 0; i < count; i++) {
24778                    IOnPermissionsChangeListener callback = mPermissionListeners
24779                            .getBroadcastItem(i);
24780                    try {
24781                        callback.onPermissionsChanged(uid);
24782                    } catch (RemoteException e) {
24783                        Log.e(TAG, "Permission listener is dead", e);
24784                    }
24785                }
24786            } finally {
24787                mPermissionListeners.finishBroadcast();
24788            }
24789        }
24790    }
24791
24792    private class PackageManagerInternalImpl extends PackageManagerInternal {
24793        @Override
24794        public void setLocationPackagesProvider(PackagesProvider provider) {
24795            synchronized (mPackages) {
24796                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24797            }
24798        }
24799
24800        @Override
24801        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24802            synchronized (mPackages) {
24803                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24804            }
24805        }
24806
24807        @Override
24808        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24809            synchronized (mPackages) {
24810                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24811            }
24812        }
24813
24814        @Override
24815        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24816            synchronized (mPackages) {
24817                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24818            }
24819        }
24820
24821        @Override
24822        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24823            synchronized (mPackages) {
24824                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24825            }
24826        }
24827
24828        @Override
24829        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24830            synchronized (mPackages) {
24831                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24832            }
24833        }
24834
24835        @Override
24836        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24837            synchronized (mPackages) {
24838                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24839                        packageName, userId);
24840            }
24841        }
24842
24843        @Override
24844        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24845            synchronized (mPackages) {
24846                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24847                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24848                        packageName, userId);
24849            }
24850        }
24851
24852        @Override
24853        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24854            synchronized (mPackages) {
24855                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24856                        packageName, userId);
24857            }
24858        }
24859
24860        @Override
24861        public void setKeepUninstalledPackages(final List<String> packageList) {
24862            Preconditions.checkNotNull(packageList);
24863            List<String> removedFromList = null;
24864            synchronized (mPackages) {
24865                if (mKeepUninstalledPackages != null) {
24866                    final int packagesCount = mKeepUninstalledPackages.size();
24867                    for (int i = 0; i < packagesCount; i++) {
24868                        String oldPackage = mKeepUninstalledPackages.get(i);
24869                        if (packageList != null && packageList.contains(oldPackage)) {
24870                            continue;
24871                        }
24872                        if (removedFromList == null) {
24873                            removedFromList = new ArrayList<>();
24874                        }
24875                        removedFromList.add(oldPackage);
24876                    }
24877                }
24878                mKeepUninstalledPackages = new ArrayList<>(packageList);
24879                if (removedFromList != null) {
24880                    final int removedCount = removedFromList.size();
24881                    for (int i = 0; i < removedCount; i++) {
24882                        deletePackageIfUnusedLPr(removedFromList.get(i));
24883                    }
24884                }
24885            }
24886        }
24887
24888        @Override
24889        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24890            synchronized (mPackages) {
24891                // If we do not support permission review, done.
24892                if (!mPermissionReviewRequired) {
24893                    return false;
24894                }
24895
24896                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24897                if (packageSetting == null) {
24898                    return false;
24899                }
24900
24901                // Permission review applies only to apps not supporting the new permission model.
24902                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24903                    return false;
24904                }
24905
24906                // Legacy apps have the permission and get user consent on launch.
24907                PermissionsState permissionsState = packageSetting.getPermissionsState();
24908                return permissionsState.isPermissionReviewRequired(userId);
24909            }
24910        }
24911
24912        @Override
24913        public PackageInfo getPackageInfo(
24914                String packageName, int flags, int filterCallingUid, int userId) {
24915            return PackageManagerService.this
24916                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24917                            flags, filterCallingUid, userId);
24918        }
24919
24920        @Override
24921        public ApplicationInfo getApplicationInfo(
24922                String packageName, int flags, int filterCallingUid, int userId) {
24923            return PackageManagerService.this
24924                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24925        }
24926
24927        @Override
24928        public ActivityInfo getActivityInfo(
24929                ComponentName component, int flags, int filterCallingUid, int userId) {
24930            return PackageManagerService.this
24931                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24932        }
24933
24934        @Override
24935        public List<ResolveInfo> queryIntentActivities(
24936                Intent intent, int flags, int filterCallingUid, int userId) {
24937            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24938            return PackageManagerService.this
24939                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24940                            userId, false /*resolveForStart*/);
24941        }
24942
24943        @Override
24944        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24945                int userId) {
24946            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24947        }
24948
24949        @Override
24950        public void setDeviceAndProfileOwnerPackages(
24951                int deviceOwnerUserId, String deviceOwnerPackage,
24952                SparseArray<String> profileOwnerPackages) {
24953            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24954                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24955        }
24956
24957        @Override
24958        public boolean isPackageDataProtected(int userId, String packageName) {
24959            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24960        }
24961
24962        @Override
24963        public boolean isPackageEphemeral(int userId, String packageName) {
24964            synchronized (mPackages) {
24965                final PackageSetting ps = mSettings.mPackages.get(packageName);
24966                return ps != null ? ps.getInstantApp(userId) : false;
24967            }
24968        }
24969
24970        @Override
24971        public boolean wasPackageEverLaunched(String packageName, int userId) {
24972            synchronized (mPackages) {
24973                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24974            }
24975        }
24976
24977        @Override
24978        public void grantRuntimePermission(String packageName, String name, int userId,
24979                boolean overridePolicy) {
24980            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24981                    overridePolicy);
24982        }
24983
24984        @Override
24985        public void revokeRuntimePermission(String packageName, String name, int userId,
24986                boolean overridePolicy) {
24987            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24988                    overridePolicy);
24989        }
24990
24991        @Override
24992        public String getNameForUid(int uid) {
24993            return PackageManagerService.this.getNameForUid(uid);
24994        }
24995
24996        @Override
24997        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24998                Intent origIntent, String resolvedType, String callingPackage,
24999                Bundle verificationBundle, int userId) {
25000            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25001                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25002                    userId);
25003        }
25004
25005        @Override
25006        public void grantEphemeralAccess(int userId, Intent intent,
25007                int targetAppId, int ephemeralAppId) {
25008            synchronized (mPackages) {
25009                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25010                        targetAppId, ephemeralAppId);
25011            }
25012        }
25013
25014        @Override
25015        public boolean isInstantAppInstallerComponent(ComponentName component) {
25016            synchronized (mPackages) {
25017                return mInstantAppInstallerActivity != null
25018                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25019            }
25020        }
25021
25022        @Override
25023        public void pruneInstantApps() {
25024            mInstantAppRegistry.pruneInstantApps();
25025        }
25026
25027        @Override
25028        public String getSetupWizardPackageName() {
25029            return mSetupWizardPackage;
25030        }
25031
25032        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25033            if (policy != null) {
25034                mExternalSourcesPolicy = policy;
25035            }
25036        }
25037
25038        @Override
25039        public boolean isPackagePersistent(String packageName) {
25040            synchronized (mPackages) {
25041                PackageParser.Package pkg = mPackages.get(packageName);
25042                return pkg != null
25043                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25044                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25045                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25046                        : false;
25047            }
25048        }
25049
25050        @Override
25051        public List<PackageInfo> getOverlayPackages(int userId) {
25052            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25053            synchronized (mPackages) {
25054                for (PackageParser.Package p : mPackages.values()) {
25055                    if (p.mOverlayTarget != null) {
25056                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25057                        if (pkg != null) {
25058                            overlayPackages.add(pkg);
25059                        }
25060                    }
25061                }
25062            }
25063            return overlayPackages;
25064        }
25065
25066        @Override
25067        public List<String> getTargetPackageNames(int userId) {
25068            List<String> targetPackages = new ArrayList<>();
25069            synchronized (mPackages) {
25070                for (PackageParser.Package p : mPackages.values()) {
25071                    if (p.mOverlayTarget == null) {
25072                        targetPackages.add(p.packageName);
25073                    }
25074                }
25075            }
25076            return targetPackages;
25077        }
25078
25079        @Override
25080        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25081                @Nullable List<String> overlayPackageNames) {
25082            synchronized (mPackages) {
25083                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25084                    Slog.e(TAG, "failed to find package " + targetPackageName);
25085                    return false;
25086                }
25087                ArrayList<String> overlayPaths = null;
25088                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25089                    final int N = overlayPackageNames.size();
25090                    overlayPaths = new ArrayList<>(N);
25091                    for (int i = 0; i < N; i++) {
25092                        final String packageName = overlayPackageNames.get(i);
25093                        final PackageParser.Package pkg = mPackages.get(packageName);
25094                        if (pkg == null) {
25095                            Slog.e(TAG, "failed to find package " + packageName);
25096                            return false;
25097                        }
25098                        overlayPaths.add(pkg.baseCodePath);
25099                    }
25100                }
25101
25102                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25103                ps.setOverlayPaths(overlayPaths, userId);
25104                return true;
25105            }
25106        }
25107
25108        @Override
25109        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25110                int flags, int userId) {
25111            return resolveIntentInternal(
25112                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25113        }
25114
25115        @Override
25116        public ResolveInfo resolveService(Intent intent, String resolvedType,
25117                int flags, int userId, int callingUid) {
25118            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25119        }
25120
25121        @Override
25122        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25123            synchronized (mPackages) {
25124                mIsolatedOwners.put(isolatedUid, ownerUid);
25125            }
25126        }
25127
25128        @Override
25129        public void removeIsolatedUid(int isolatedUid) {
25130            synchronized (mPackages) {
25131                mIsolatedOwners.delete(isolatedUid);
25132            }
25133        }
25134
25135        @Override
25136        public int getUidTargetSdkVersion(int uid) {
25137            synchronized (mPackages) {
25138                return getUidTargetSdkVersionLockedLPr(uid);
25139            }
25140        }
25141
25142        @Override
25143        public boolean canAccessInstantApps(int callingUid, int userId) {
25144            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25145        }
25146    }
25147
25148    @Override
25149    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25150        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25151        synchronized (mPackages) {
25152            final long identity = Binder.clearCallingIdentity();
25153            try {
25154                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25155                        packageNames, userId);
25156            } finally {
25157                Binder.restoreCallingIdentity(identity);
25158            }
25159        }
25160    }
25161
25162    @Override
25163    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25164        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25165        synchronized (mPackages) {
25166            final long identity = Binder.clearCallingIdentity();
25167            try {
25168                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25169                        packageNames, userId);
25170            } finally {
25171                Binder.restoreCallingIdentity(identity);
25172            }
25173        }
25174    }
25175
25176    private static void enforceSystemOrPhoneCaller(String tag) {
25177        int callingUid = Binder.getCallingUid();
25178        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25179            throw new SecurityException(
25180                    "Cannot call " + tag + " from UID " + callingUid);
25181        }
25182    }
25183
25184    boolean isHistoricalPackageUsageAvailable() {
25185        return mPackageUsage.isHistoricalPackageUsageAvailable();
25186    }
25187
25188    /**
25189     * Return a <b>copy</b> of the collection of packages known to the package manager.
25190     * @return A copy of the values of mPackages.
25191     */
25192    Collection<PackageParser.Package> getPackages() {
25193        synchronized (mPackages) {
25194            return new ArrayList<>(mPackages.values());
25195        }
25196    }
25197
25198    /**
25199     * Logs process start information (including base APK hash) to the security log.
25200     * @hide
25201     */
25202    @Override
25203    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25204            String apkFile, int pid) {
25205        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25206            return;
25207        }
25208        if (!SecurityLog.isLoggingEnabled()) {
25209            return;
25210        }
25211        Bundle data = new Bundle();
25212        data.putLong("startTimestamp", System.currentTimeMillis());
25213        data.putString("processName", processName);
25214        data.putInt("uid", uid);
25215        data.putString("seinfo", seinfo);
25216        data.putString("apkFile", apkFile);
25217        data.putInt("pid", pid);
25218        Message msg = mProcessLoggingHandler.obtainMessage(
25219                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25220        msg.setData(data);
25221        mProcessLoggingHandler.sendMessage(msg);
25222    }
25223
25224    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25225        return mCompilerStats.getPackageStats(pkgName);
25226    }
25227
25228    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25229        return getOrCreateCompilerPackageStats(pkg.packageName);
25230    }
25231
25232    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25233        return mCompilerStats.getOrCreatePackageStats(pkgName);
25234    }
25235
25236    public void deleteCompilerPackageStats(String pkgName) {
25237        mCompilerStats.deletePackageStats(pkgName);
25238    }
25239
25240    @Override
25241    public int getInstallReason(String packageName, int userId) {
25242        final int callingUid = Binder.getCallingUid();
25243        enforceCrossUserPermission(callingUid, userId,
25244                true /* requireFullPermission */, false /* checkShell */,
25245                "get install reason");
25246        synchronized (mPackages) {
25247            final PackageSetting ps = mSettings.mPackages.get(packageName);
25248            if (filterAppAccessLPr(ps, callingUid, userId)) {
25249                return PackageManager.INSTALL_REASON_UNKNOWN;
25250            }
25251            if (ps != null) {
25252                return ps.getInstallReason(userId);
25253            }
25254        }
25255        return PackageManager.INSTALL_REASON_UNKNOWN;
25256    }
25257
25258    @Override
25259    public boolean canRequestPackageInstalls(String packageName, int userId) {
25260        return canRequestPackageInstallsInternal(packageName, 0, userId,
25261                true /* throwIfPermNotDeclared*/);
25262    }
25263
25264    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25265            boolean throwIfPermNotDeclared) {
25266        int callingUid = Binder.getCallingUid();
25267        int uid = getPackageUid(packageName, 0, userId);
25268        if (callingUid != uid && callingUid != Process.ROOT_UID
25269                && callingUid != Process.SYSTEM_UID) {
25270            throw new SecurityException(
25271                    "Caller uid " + callingUid + " does not own package " + packageName);
25272        }
25273        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25274        if (info == null) {
25275            return false;
25276        }
25277        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25278            return false;
25279        }
25280        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25281        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25282        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25283            if (throwIfPermNotDeclared) {
25284                throw new SecurityException("Need to declare " + appOpPermission
25285                        + " to call this api");
25286            } else {
25287                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25288                return false;
25289            }
25290        }
25291        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25292            return false;
25293        }
25294        if (mExternalSourcesPolicy != null) {
25295            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25296            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25297                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25298            }
25299        }
25300        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25301    }
25302
25303    @Override
25304    public ComponentName getInstantAppResolverSettingsComponent() {
25305        return mInstantAppResolverSettingsComponent;
25306    }
25307
25308    @Override
25309    public ComponentName getInstantAppInstallerComponent() {
25310        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25311            return null;
25312        }
25313        return mInstantAppInstallerActivity == null
25314                ? null : mInstantAppInstallerActivity.getComponentName();
25315    }
25316
25317    @Override
25318    public String getInstantAppAndroidId(String packageName, int userId) {
25319        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25320                "getInstantAppAndroidId");
25321        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25322                true /* requireFullPermission */, false /* checkShell */,
25323                "getInstantAppAndroidId");
25324        // Make sure the target is an Instant App.
25325        if (!isInstantApp(packageName, userId)) {
25326            return null;
25327        }
25328        synchronized (mPackages) {
25329            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25330        }
25331    }
25332
25333    boolean canHaveOatDir(String packageName) {
25334        synchronized (mPackages) {
25335            PackageParser.Package p = mPackages.get(packageName);
25336            if (p == null) {
25337                return false;
25338            }
25339            return p.canHaveOatDir();
25340        }
25341    }
25342
25343    private String getOatDir(PackageParser.Package pkg) {
25344        if (!pkg.canHaveOatDir()) {
25345            return null;
25346        }
25347        File codePath = new File(pkg.codePath);
25348        if (codePath.isDirectory()) {
25349            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25350        }
25351        return null;
25352    }
25353
25354    void deleteOatArtifactsOfPackage(String packageName) {
25355        final String[] instructionSets;
25356        final List<String> codePaths;
25357        final String oatDir;
25358        final PackageParser.Package pkg;
25359        synchronized (mPackages) {
25360            pkg = mPackages.get(packageName);
25361        }
25362        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25363        codePaths = pkg.getAllCodePaths();
25364        oatDir = getOatDir(pkg);
25365
25366        for (String codePath : codePaths) {
25367            for (String isa : instructionSets) {
25368                try {
25369                    mInstaller.deleteOdex(codePath, isa, oatDir);
25370                } catch (InstallerException e) {
25371                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25372                }
25373            }
25374        }
25375    }
25376
25377    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25378        Set<String> unusedPackages = new HashSet<>();
25379        long currentTimeInMillis = System.currentTimeMillis();
25380        synchronized (mPackages) {
25381            for (PackageParser.Package pkg : mPackages.values()) {
25382                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25383                if (ps == null) {
25384                    continue;
25385                }
25386                PackageDexUsage.PackageUseInfo packageUseInfo = getDexManager().getPackageUseInfo(
25387                        pkg.packageName);
25388                if (PackageManagerServiceUtils
25389                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25390                                downgradeTimeThresholdMillis, packageUseInfo,
25391                                pkg.getLatestPackageUseTimeInMills(),
25392                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25393                    unusedPackages.add(pkg.packageName);
25394                }
25395            }
25396        }
25397        return unusedPackages;
25398    }
25399}
25400
25401interface PackageSender {
25402    void sendPackageBroadcast(final String action, final String pkg,
25403        final Bundle extras, final int flags, final String targetPkg,
25404        final IIntentReceiver finishedReceiver, final int[] userIds);
25405    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25406        boolean includeStopped, int appId, int... userIds);
25407}
25408