PackageManagerService.java revision ad192a392bb51dc71863eab61cb8d415fef4d54f
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.IPackageManagerNative;
147import android.content.pm.IPackageMoveObserver;
148import android.content.pm.IPackageStatsObserver;
149import android.content.pm.InstantAppInfo;
150import android.content.pm.InstantAppRequest;
151import android.content.pm.InstantAppResolveInfo;
152import android.content.pm.InstrumentationInfo;
153import android.content.pm.IntentFilterVerificationInfo;
154import android.content.pm.KeySet;
155import android.content.pm.PackageCleanItem;
156import android.content.pm.PackageInfo;
157import android.content.pm.PackageInfoLite;
158import android.content.pm.PackageInstaller;
159import android.content.pm.PackageManager;
160import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
161import android.content.pm.PackageManagerInternal;
162import android.content.pm.PackageParser;
163import android.content.pm.PackageParser.ActivityIntentInfo;
164import android.content.pm.PackageParser.PackageLite;
165import android.content.pm.PackageParser.PackageParserException;
166import android.content.pm.PackageStats;
167import android.content.pm.PackageUserState;
168import android.content.pm.ParceledListSlice;
169import android.content.pm.PermissionGroupInfo;
170import android.content.pm.PermissionInfo;
171import android.content.pm.ProviderInfo;
172import android.content.pm.ResolveInfo;
173import android.content.pm.ServiceInfo;
174import android.content.pm.SharedLibraryInfo;
175import android.content.pm.Signature;
176import android.content.pm.UserInfo;
177import android.content.pm.VerifierDeviceIdentity;
178import android.content.pm.VerifierInfo;
179import android.content.pm.VersionedPackage;
180import android.content.res.Resources;
181import android.database.ContentObserver;
182import android.graphics.Bitmap;
183import android.hardware.display.DisplayManager;
184import android.net.Uri;
185import android.os.Binder;
186import android.os.Build;
187import android.os.Bundle;
188import android.os.Debug;
189import android.os.Environment;
190import android.os.Environment.UserEnvironment;
191import android.os.FileUtils;
192import android.os.Handler;
193import android.os.IBinder;
194import android.os.Looper;
195import android.os.Message;
196import android.os.Parcel;
197import android.os.ParcelFileDescriptor;
198import android.os.PatternMatcher;
199import android.os.Process;
200import android.os.RemoteCallbackList;
201import android.os.RemoteException;
202import android.os.ResultReceiver;
203import android.os.SELinux;
204import android.os.ServiceManager;
205import android.os.ShellCallback;
206import android.os.SystemClock;
207import android.os.SystemProperties;
208import android.os.Trace;
209import android.os.UserHandle;
210import android.os.UserManager;
211import android.os.UserManagerInternal;
212import android.os.storage.IStorageManager;
213import android.os.storage.StorageEventListener;
214import android.os.storage.StorageManager;
215import android.os.storage.StorageManagerInternal;
216import android.os.storage.VolumeInfo;
217import android.os.storage.VolumeRecord;
218import android.provider.Settings.Global;
219import android.provider.Settings.Secure;
220import android.security.KeyStore;
221import android.security.SystemKeyStore;
222import android.service.pm.PackageServiceDumpProto;
223import android.system.ErrnoException;
224import android.system.Os;
225import android.text.TextUtils;
226import android.text.format.DateUtils;
227import android.util.ArrayMap;
228import android.util.ArraySet;
229import android.util.Base64;
230import android.util.BootTimingsTraceLog;
231import android.util.DisplayMetrics;
232import android.util.EventLog;
233import android.util.ExceptionUtils;
234import android.util.Log;
235import android.util.LogPrinter;
236import android.util.MathUtils;
237import android.util.PackageUtils;
238import android.util.Pair;
239import android.util.PrintStreamPrinter;
240import android.util.Slog;
241import android.util.SparseArray;
242import android.util.SparseBooleanArray;
243import android.util.SparseIntArray;
244import android.util.Xml;
245import android.util.jar.StrictJarFile;
246import android.util.proto.ProtoOutputStream;
247import android.view.Display;
248
249import com.android.internal.R;
250import com.android.internal.annotations.GuardedBy;
251import com.android.internal.app.IMediaContainerService;
252import com.android.internal.app.ResolverActivity;
253import com.android.internal.content.NativeLibraryHelper;
254import com.android.internal.content.PackageHelper;
255import com.android.internal.logging.MetricsLogger;
256import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
257import com.android.internal.os.IParcelFileDescriptorFactory;
258import com.android.internal.os.RoSystemProperties;
259import com.android.internal.os.SomeArgs;
260import com.android.internal.os.Zygote;
261import com.android.internal.telephony.CarrierAppUtils;
262import com.android.internal.util.ArrayUtils;
263import com.android.internal.util.ConcurrentUtils;
264import com.android.internal.util.DumpUtils;
265import com.android.internal.util.FastPrintWriter;
266import com.android.internal.util.FastXmlSerializer;
267import com.android.internal.util.IndentingPrintWriter;
268import com.android.internal.util.Preconditions;
269import com.android.internal.util.XmlUtils;
270import com.android.server.AttributeCache;
271import com.android.server.DeviceIdleController;
272import com.android.server.EventLogTags;
273import com.android.server.FgThread;
274import com.android.server.IntentResolver;
275import com.android.server.LocalServices;
276import com.android.server.LockGuard;
277import com.android.server.ServiceThread;
278import com.android.server.SystemConfig;
279import com.android.server.SystemServerInitThreadPool;
280import com.android.server.Watchdog;
281import com.android.server.net.NetworkPolicyManagerInternal;
282import com.android.server.pm.Installer.InstallerException;
283import com.android.server.pm.PermissionsState.PermissionState;
284import com.android.server.pm.Settings.DatabaseVersion;
285import com.android.server.pm.Settings.VersionInfo;
286import com.android.server.pm.dex.DexManager;
287import com.android.server.pm.dex.DexoptOptions;
288import com.android.server.pm.dex.PackageDexUsage;
289import com.android.server.storage.DeviceStorageMonitorInternal;
290
291import dalvik.system.CloseGuard;
292import dalvik.system.DexFile;
293import dalvik.system.VMRuntime;
294
295import libcore.io.IoUtils;
296import libcore.io.Streams;
297import libcore.util.EmptyArray;
298
299import org.xmlpull.v1.XmlPullParser;
300import org.xmlpull.v1.XmlPullParserException;
301import org.xmlpull.v1.XmlSerializer;
302
303import java.io.BufferedOutputStream;
304import java.io.BufferedReader;
305import java.io.ByteArrayInputStream;
306import java.io.ByteArrayOutputStream;
307import java.io.File;
308import java.io.FileDescriptor;
309import java.io.FileInputStream;
310import java.io.FileOutputStream;
311import java.io.FileReader;
312import java.io.FilenameFilter;
313import java.io.IOException;
314import java.io.InputStream;
315import java.io.OutputStream;
316import java.io.PrintWriter;
317import java.lang.annotation.Retention;
318import java.lang.annotation.RetentionPolicy;
319import java.nio.charset.StandardCharsets;
320import java.security.DigestInputStream;
321import java.security.MessageDigest;
322import java.security.NoSuchAlgorithmException;
323import java.security.PublicKey;
324import java.security.SecureRandom;
325import java.security.cert.Certificate;
326import java.security.cert.CertificateEncodingException;
327import java.security.cert.CertificateException;
328import java.text.SimpleDateFormat;
329import java.util.ArrayList;
330import java.util.Arrays;
331import java.util.Collection;
332import java.util.Collections;
333import java.util.Comparator;
334import java.util.Date;
335import java.util.HashMap;
336import java.util.HashSet;
337import java.util.Iterator;
338import java.util.List;
339import java.util.Map;
340import java.util.Objects;
341import java.util.Set;
342import java.util.concurrent.CountDownLatch;
343import java.util.concurrent.Future;
344import java.util.concurrent.TimeUnit;
345import java.util.concurrent.atomic.AtomicBoolean;
346import java.util.concurrent.atomic.AtomicInteger;
347import java.util.zip.GZIPInputStream;
348
349/**
350 * Keep track of all those APKs everywhere.
351 * <p>
352 * Internally there are two important locks:
353 * <ul>
354 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
355 * and other related state. It is a fine-grained lock that should only be held
356 * momentarily, as it's one of the most contended locks in the system.
357 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
358 * operations typically involve heavy lifting of application data on disk. Since
359 * {@code installd} is single-threaded, and it's operations can often be slow,
360 * this lock should never be acquired while already holding {@link #mPackages}.
361 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
362 * holding {@link #mInstallLock}.
363 * </ul>
364 * Many internal methods rely on the caller to hold the appropriate locks, and
365 * this contract is expressed through method name suffixes:
366 * <ul>
367 * <li>fooLI(): the caller must hold {@link #mInstallLock}
368 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
369 * being modified must be frozen
370 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
371 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
372 * </ul>
373 * <p>
374 * Because this class is very central to the platform's security; please run all
375 * CTS and unit tests whenever making modifications:
376 *
377 * <pre>
378 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
379 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
380 * </pre>
381 */
382public class PackageManagerService extends IPackageManager.Stub
383        implements PackageSender {
384    static final String TAG = "PackageManager";
385    static final boolean DEBUG_SETTINGS = false;
386    static final boolean DEBUG_PREFERRED = false;
387    static final boolean DEBUG_UPGRADE = false;
388    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
389    private static final boolean DEBUG_BACKUP = false;
390    private static final boolean DEBUG_INSTALL = false;
391    private static final boolean DEBUG_REMOVE = false;
392    private static final boolean DEBUG_BROADCASTS = false;
393    private static final boolean DEBUG_SHOW_INFO = false;
394    private static final boolean DEBUG_PACKAGE_INFO = false;
395    private static final boolean DEBUG_INTENT_MATCHING = false;
396    private static final boolean DEBUG_PACKAGE_SCANNING = false;
397    private static final boolean DEBUG_VERIFY = false;
398    private static final boolean DEBUG_FILTERS = false;
399    private static final boolean DEBUG_PERMISSIONS = false;
400    private static final boolean DEBUG_SHARED_LIBRARIES = false;
401    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
402
403    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
404    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
405    // user, but by default initialize to this.
406    public static final boolean DEBUG_DEXOPT = false;
407
408    private static final boolean DEBUG_ABI_SELECTION = false;
409    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
410    private static final boolean DEBUG_TRIAGED_MISSING = false;
411    private static final boolean DEBUG_APP_DATA = false;
412
413    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
414    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
415
416    private static final boolean HIDE_EPHEMERAL_APIS = false;
417
418    private static final boolean ENABLE_FREE_CACHE_V2 =
419            SystemProperties.getBoolean("fw.free_cache_v2", true);
420
421    private static final int RADIO_UID = Process.PHONE_UID;
422    private static final int LOG_UID = Process.LOG_UID;
423    private static final int NFC_UID = Process.NFC_UID;
424    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
425    private static final int SHELL_UID = Process.SHELL_UID;
426
427    // Cap the size of permission trees that 3rd party apps can define
428    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
429
430    // Suffix used during package installation when copying/moving
431    // package apks to install directory.
432    private static final String INSTALL_PACKAGE_SUFFIX = "-";
433
434    static final int SCAN_NO_DEX = 1<<1;
435    static final int SCAN_FORCE_DEX = 1<<2;
436    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
437    static final int SCAN_NEW_INSTALL = 1<<4;
438    static final int SCAN_UPDATE_TIME = 1<<5;
439    static final int SCAN_BOOTING = 1<<6;
440    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
441    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
442    static final int SCAN_REPLACING = 1<<9;
443    static final int SCAN_REQUIRE_KNOWN = 1<<10;
444    static final int SCAN_MOVE = 1<<11;
445    static final int SCAN_INITIAL = 1<<12;
446    static final int SCAN_CHECK_ONLY = 1<<13;
447    static final int SCAN_DONT_KILL_APP = 1<<14;
448    static final int SCAN_IGNORE_FROZEN = 1<<15;
449    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
450    static final int SCAN_AS_INSTANT_APP = 1<<17;
451    static final int SCAN_AS_FULL_APP = 1<<18;
452    /** Should not be with the scan flags */
453    static final int FLAGS_REMOVE_CHATTY = 1<<31;
454
455    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
456    /** Extension of the compressed packages */
457    private final static String COMPRESSED_EXTENSION = ".gz";
458
459    private static final int[] EMPTY_INT_ARRAY = new int[0];
460
461    private static final int TYPE_UNKNOWN = 0;
462    private static final int TYPE_ACTIVITY = 1;
463    private static final int TYPE_RECEIVER = 2;
464    private static final int TYPE_SERVICE = 3;
465    private static final int TYPE_PROVIDER = 4;
466    @IntDef(prefix = { "TYPE_" }, value = {
467            TYPE_UNKNOWN,
468            TYPE_ACTIVITY,
469            TYPE_RECEIVER,
470            TYPE_SERVICE,
471            TYPE_PROVIDER,
472    })
473    @Retention(RetentionPolicy.SOURCE)
474    public @interface ComponentType {}
475
476    /**
477     * Timeout (in milliseconds) after which the watchdog should declare that
478     * our handler thread is wedged.  The usual default for such things is one
479     * minute but we sometimes do very lengthy I/O operations on this thread,
480     * such as installing multi-gigabyte applications, so ours needs to be longer.
481     */
482    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
483
484    /**
485     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
486     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
487     * settings entry if available, otherwise we use the hardcoded default.  If it's been
488     * more than this long since the last fstrim, we force one during the boot sequence.
489     *
490     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
491     * one gets run at the next available charging+idle time.  This final mandatory
492     * no-fstrim check kicks in only of the other scheduling criteria is never met.
493     */
494    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
495
496    /**
497     * Whether verification is enabled by default.
498     */
499    private static final boolean DEFAULT_VERIFY_ENABLE = true;
500
501    /**
502     * The default maximum time to wait for the verification agent to return in
503     * milliseconds.
504     */
505    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
506
507    /**
508     * The default response for package verification timeout.
509     *
510     * This can be either PackageManager.VERIFICATION_ALLOW or
511     * PackageManager.VERIFICATION_REJECT.
512     */
513    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
514
515    static final String PLATFORM_PACKAGE_NAME = "android";
516
517    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
518
519    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
520            DEFAULT_CONTAINER_PACKAGE,
521            "com.android.defcontainer.DefaultContainerService");
522
523    private static final String KILL_APP_REASON_GIDS_CHANGED =
524            "permission grant or revoke changed gids";
525
526    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
527            "permissions revoked";
528
529    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
530
531    private static final String PACKAGE_SCHEME = "package";
532
533    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
534
535    /** Permission grant: not grant the permission. */
536    private static final int GRANT_DENIED = 1;
537
538    /** Permission grant: grant the permission as an install permission. */
539    private static final int GRANT_INSTALL = 2;
540
541    /** Permission grant: grant the permission as a runtime one. */
542    private static final int GRANT_RUNTIME = 3;
543
544    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
545    private static final int GRANT_UPGRADE = 4;
546
547    /** Canonical intent used to identify what counts as a "web browser" app */
548    private static final Intent sBrowserIntent;
549    static {
550        sBrowserIntent = new Intent();
551        sBrowserIntent.setAction(Intent.ACTION_VIEW);
552        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
553        sBrowserIntent.setData(Uri.parse("http:"));
554    }
555
556    /**
557     * The set of all protected actions [i.e. those actions for which a high priority
558     * intent filter is disallowed].
559     */
560    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
561    static {
562        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
563        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
564        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
565        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
566    }
567
568    // Compilation reasons.
569    public static final int REASON_FIRST_BOOT = 0;
570    public static final int REASON_BOOT = 1;
571    public static final int REASON_INSTALL = 2;
572    public static final int REASON_BACKGROUND_DEXOPT = 3;
573    public static final int REASON_AB_OTA = 4;
574    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
575
576    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
577
578    /** All dangerous permission names in the same order as the events in MetricsEvent */
579    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
580            Manifest.permission.READ_CALENDAR,
581            Manifest.permission.WRITE_CALENDAR,
582            Manifest.permission.CAMERA,
583            Manifest.permission.READ_CONTACTS,
584            Manifest.permission.WRITE_CONTACTS,
585            Manifest.permission.GET_ACCOUNTS,
586            Manifest.permission.ACCESS_FINE_LOCATION,
587            Manifest.permission.ACCESS_COARSE_LOCATION,
588            Manifest.permission.RECORD_AUDIO,
589            Manifest.permission.READ_PHONE_STATE,
590            Manifest.permission.CALL_PHONE,
591            Manifest.permission.READ_CALL_LOG,
592            Manifest.permission.WRITE_CALL_LOG,
593            Manifest.permission.ADD_VOICEMAIL,
594            Manifest.permission.USE_SIP,
595            Manifest.permission.PROCESS_OUTGOING_CALLS,
596            Manifest.permission.READ_CELL_BROADCASTS,
597            Manifest.permission.BODY_SENSORS,
598            Manifest.permission.SEND_SMS,
599            Manifest.permission.RECEIVE_SMS,
600            Manifest.permission.READ_SMS,
601            Manifest.permission.RECEIVE_WAP_PUSH,
602            Manifest.permission.RECEIVE_MMS,
603            Manifest.permission.READ_EXTERNAL_STORAGE,
604            Manifest.permission.WRITE_EXTERNAL_STORAGE,
605            Manifest.permission.READ_PHONE_NUMBERS,
606            Manifest.permission.ANSWER_PHONE_CALLS);
607
608
609    /**
610     * Version number for the package parser cache. Increment this whenever the format or
611     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
612     */
613    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
614
615    /**
616     * Whether the package parser cache is enabled.
617     */
618    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
619
620    final ServiceThread mHandlerThread;
621
622    final PackageHandler mHandler;
623
624    private final ProcessLoggingHandler mProcessLoggingHandler;
625
626    /**
627     * Messages for {@link #mHandler} that need to wait for system ready before
628     * being dispatched.
629     */
630    private ArrayList<Message> mPostSystemReadyMessages;
631
632    final int mSdkVersion = Build.VERSION.SDK_INT;
633
634    final Context mContext;
635    final boolean mFactoryTest;
636    final boolean mOnlyCore;
637    final DisplayMetrics mMetrics;
638    final int mDefParseFlags;
639    final String[] mSeparateProcesses;
640    final boolean mIsUpgrade;
641    final boolean mIsPreNUpgrade;
642    final boolean mIsPreNMR1Upgrade;
643
644    // Have we told the Activity Manager to whitelist the default container service by uid yet?
645    @GuardedBy("mPackages")
646    boolean mDefaultContainerWhitelisted = false;
647
648    @GuardedBy("mPackages")
649    private boolean mDexOptDialogShown;
650
651    /** The location for ASEC container files on internal storage. */
652    final String mAsecInternalPath;
653
654    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
655    // LOCK HELD.  Can be called with mInstallLock held.
656    @GuardedBy("mInstallLock")
657    final Installer mInstaller;
658
659    /** Directory where installed third-party apps stored */
660    final File mAppInstallDir;
661
662    /**
663     * Directory to which applications installed internally have their
664     * 32 bit native libraries copied.
665     */
666    private File mAppLib32InstallDir;
667
668    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
669    // apps.
670    final File mDrmAppPrivateInstallDir;
671
672    // ----------------------------------------------------------------
673
674    // Lock for state used when installing and doing other long running
675    // operations.  Methods that must be called with this lock held have
676    // the suffix "LI".
677    final Object mInstallLock = new Object();
678
679    // ----------------------------------------------------------------
680
681    // Keys are String (package name), values are Package.  This also serves
682    // as the lock for the global state.  Methods that must be called with
683    // this lock held have the prefix "LP".
684    @GuardedBy("mPackages")
685    final ArrayMap<String, PackageParser.Package> mPackages =
686            new ArrayMap<String, PackageParser.Package>();
687
688    final ArrayMap<String, Set<String>> mKnownCodebase =
689            new ArrayMap<String, Set<String>>();
690
691    // Keys are isolated uids and values are the uid of the application
692    // that created the isolated proccess.
693    @GuardedBy("mPackages")
694    final SparseIntArray mIsolatedOwners = new SparseIntArray();
695
696    /**
697     * Tracks new system packages [received in an OTA] that we expect to
698     * find updated user-installed versions. Keys are package name, values
699     * are package location.
700     */
701    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
702    /**
703     * Tracks high priority intent filters for protected actions. During boot, certain
704     * filter actions are protected and should never be allowed to have a high priority
705     * intent filter for them. However, there is one, and only one exception -- the
706     * setup wizard. It must be able to define a high priority intent filter for these
707     * actions to ensure there are no escapes from the wizard. We need to delay processing
708     * of these during boot as we need to look at all of the system packages in order
709     * to know which component is the setup wizard.
710     */
711    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
712    /**
713     * Whether or not processing protected filters should be deferred.
714     */
715    private boolean mDeferProtectedFilters = true;
716
717    /**
718     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
719     */
720    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
721    /**
722     * Whether or not system app permissions should be promoted from install to runtime.
723     */
724    boolean mPromoteSystemApps;
725
726    @GuardedBy("mPackages")
727    final Settings mSettings;
728
729    /**
730     * Set of package names that are currently "frozen", which means active
731     * surgery is being done on the code/data for that package. The platform
732     * will refuse to launch frozen packages to avoid race conditions.
733     *
734     * @see PackageFreezer
735     */
736    @GuardedBy("mPackages")
737    final ArraySet<String> mFrozenPackages = new ArraySet<>();
738
739    final ProtectedPackages mProtectedPackages;
740
741    @GuardedBy("mLoadedVolumes")
742    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
743
744    boolean mFirstBoot;
745
746    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
747
748    // System configuration read by SystemConfig.
749    final int[] mGlobalGids;
750    final SparseArray<ArraySet<String>> mSystemPermissions;
751    @GuardedBy("mAvailableFeatures")
752    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
753
754    // If mac_permissions.xml was found for seinfo labeling.
755    boolean mFoundPolicyFile;
756
757    private final InstantAppRegistry mInstantAppRegistry;
758
759    @GuardedBy("mPackages")
760    int mChangedPackagesSequenceNumber;
761    /**
762     * List of changed [installed, removed or updated] packages.
763     * mapping from user id -> sequence number -> package name
764     */
765    @GuardedBy("mPackages")
766    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
767    /**
768     * The sequence number of the last change to a package.
769     * mapping from user id -> package name -> sequence number
770     */
771    @GuardedBy("mPackages")
772    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
773
774    class PackageParserCallback implements PackageParser.Callback {
775        @Override public final boolean hasFeature(String feature) {
776            return PackageManagerService.this.hasSystemFeature(feature, 0);
777        }
778
779        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
780                Collection<PackageParser.Package> allPackages, String targetPackageName) {
781            List<PackageParser.Package> overlayPackages = null;
782            for (PackageParser.Package p : allPackages) {
783                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
784                    if (overlayPackages == null) {
785                        overlayPackages = new ArrayList<PackageParser.Package>();
786                    }
787                    overlayPackages.add(p);
788                }
789            }
790            if (overlayPackages != null) {
791                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
792                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
793                        return p1.mOverlayPriority - p2.mOverlayPriority;
794                    }
795                };
796                Collections.sort(overlayPackages, cmp);
797            }
798            return overlayPackages;
799        }
800
801        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
802                String targetPackageName, String targetPath) {
803            if ("android".equals(targetPackageName)) {
804                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
805                // native AssetManager.
806                return null;
807            }
808            List<PackageParser.Package> overlayPackages =
809                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
810            if (overlayPackages == null || overlayPackages.isEmpty()) {
811                return null;
812            }
813            List<String> overlayPathList = null;
814            for (PackageParser.Package overlayPackage : overlayPackages) {
815                if (targetPath == null) {
816                    if (overlayPathList == null) {
817                        overlayPathList = new ArrayList<String>();
818                    }
819                    overlayPathList.add(overlayPackage.baseCodePath);
820                    continue;
821                }
822
823                try {
824                    // Creates idmaps for system to parse correctly the Android manifest of the
825                    // target package.
826                    //
827                    // OverlayManagerService will update each of them with a correct gid from its
828                    // target package app id.
829                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
830                            UserHandle.getSharedAppGid(
831                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
832                    if (overlayPathList == null) {
833                        overlayPathList = new ArrayList<String>();
834                    }
835                    overlayPathList.add(overlayPackage.baseCodePath);
836                } catch (InstallerException e) {
837                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
838                            overlayPackage.baseCodePath);
839                }
840            }
841            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
842        }
843
844        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
845            synchronized (mPackages) {
846                return getStaticOverlayPathsLocked(
847                        mPackages.values(), targetPackageName, targetPath);
848            }
849        }
850
851        @Override public final String[] getOverlayApks(String targetPackageName) {
852            return getStaticOverlayPaths(targetPackageName, null);
853        }
854
855        @Override public final String[] getOverlayPaths(String targetPackageName,
856                String targetPath) {
857            return getStaticOverlayPaths(targetPackageName, targetPath);
858        }
859    };
860
861    class ParallelPackageParserCallback extends PackageParserCallback {
862        List<PackageParser.Package> mOverlayPackages = null;
863
864        void findStaticOverlayPackages() {
865            synchronized (mPackages) {
866                for (PackageParser.Package p : mPackages.values()) {
867                    if (p.mIsStaticOverlay) {
868                        if (mOverlayPackages == null) {
869                            mOverlayPackages = new ArrayList<PackageParser.Package>();
870                        }
871                        mOverlayPackages.add(p);
872                    }
873                }
874            }
875        }
876
877        @Override
878        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
879            // We can trust mOverlayPackages without holding mPackages because package uninstall
880            // can't happen while running parallel parsing.
881            // Moreover holding mPackages on each parsing thread causes dead-lock.
882            return mOverlayPackages == null ? null :
883                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
884        }
885    }
886
887    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
888    final ParallelPackageParserCallback mParallelPackageParserCallback =
889            new ParallelPackageParserCallback();
890
891    public static final class SharedLibraryEntry {
892        public final @Nullable String path;
893        public final @Nullable String apk;
894        public final @NonNull SharedLibraryInfo info;
895
896        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
897                String declaringPackageName, int declaringPackageVersionCode) {
898            path = _path;
899            apk = _apk;
900            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
901                    declaringPackageName, declaringPackageVersionCode), null);
902        }
903    }
904
905    // Currently known shared libraries.
906    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
907    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
908            new ArrayMap<>();
909
910    // All available activities, for your resolving pleasure.
911    final ActivityIntentResolver mActivities =
912            new ActivityIntentResolver();
913
914    // All available receivers, for your resolving pleasure.
915    final ActivityIntentResolver mReceivers =
916            new ActivityIntentResolver();
917
918    // All available services, for your resolving pleasure.
919    final ServiceIntentResolver mServices = new ServiceIntentResolver();
920
921    // All available providers, for your resolving pleasure.
922    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
923
924    // Mapping from provider base names (first directory in content URI codePath)
925    // to the provider information.
926    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
927            new ArrayMap<String, PackageParser.Provider>();
928
929    // Mapping from instrumentation class names to info about them.
930    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
931            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
932
933    // Mapping from permission names to info about them.
934    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
935            new ArrayMap<String, PackageParser.PermissionGroup>();
936
937    // Packages whose data we have transfered into another package, thus
938    // should no longer exist.
939    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
940
941    // Broadcast actions that are only available to the system.
942    @GuardedBy("mProtectedBroadcasts")
943    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
944
945    /** List of packages waiting for verification. */
946    final SparseArray<PackageVerificationState> mPendingVerification
947            = new SparseArray<PackageVerificationState>();
948
949    /** Set of packages associated with each app op permission. */
950    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
951
952    final PackageInstallerService mInstallerService;
953
954    private final PackageDexOptimizer mPackageDexOptimizer;
955    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
956    // is used by other apps).
957    private final DexManager mDexManager;
958
959    private AtomicInteger mNextMoveId = new AtomicInteger();
960    private final MoveCallbacks mMoveCallbacks;
961
962    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
963
964    // Cache of users who need badging.
965    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
966
967    /** Token for keys in mPendingVerification. */
968    private int mPendingVerificationToken = 0;
969
970    volatile boolean mSystemReady;
971    volatile boolean mSafeMode;
972    volatile boolean mHasSystemUidErrors;
973    private volatile boolean mEphemeralAppsDisabled;
974
975    ApplicationInfo mAndroidApplication;
976    final ActivityInfo mResolveActivity = new ActivityInfo();
977    final ResolveInfo mResolveInfo = new ResolveInfo();
978    ComponentName mResolveComponentName;
979    PackageParser.Package mPlatformPackage;
980    ComponentName mCustomResolverComponentName;
981
982    boolean mResolverReplaced = false;
983
984    private final @Nullable ComponentName mIntentFilterVerifierComponent;
985    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
986
987    private int mIntentFilterVerificationToken = 0;
988
989    /** The service connection to the ephemeral resolver */
990    final EphemeralResolverConnection mInstantAppResolverConnection;
991    /** Component used to show resolver settings for Instant Apps */
992    final ComponentName mInstantAppResolverSettingsComponent;
993
994    /** Activity used to install instant applications */
995    ActivityInfo mInstantAppInstallerActivity;
996    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
997
998    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
999            = new SparseArray<IntentFilterVerificationState>();
1000
1001    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1002
1003    // List of packages names to keep cached, even if they are uninstalled for all users
1004    private List<String> mKeepUninstalledPackages;
1005
1006    private UserManagerInternal mUserManagerInternal;
1007
1008    private DeviceIdleController.LocalService mDeviceIdleController;
1009
1010    private File mCacheDir;
1011
1012    private ArraySet<String> mPrivappPermissionsViolations;
1013
1014    private Future<?> mPrepareAppDataFuture;
1015
1016    private static class IFVerificationParams {
1017        PackageParser.Package pkg;
1018        boolean replacing;
1019        int userId;
1020        int verifierUid;
1021
1022        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1023                int _userId, int _verifierUid) {
1024            pkg = _pkg;
1025            replacing = _replacing;
1026            userId = _userId;
1027            replacing = _replacing;
1028            verifierUid = _verifierUid;
1029        }
1030    }
1031
1032    private interface IntentFilterVerifier<T extends IntentFilter> {
1033        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1034                                               T filter, String packageName);
1035        void startVerifications(int userId);
1036        void receiveVerificationResponse(int verificationId);
1037    }
1038
1039    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1040        private Context mContext;
1041        private ComponentName mIntentFilterVerifierComponent;
1042        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1043
1044        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1045            mContext = context;
1046            mIntentFilterVerifierComponent = verifierComponent;
1047        }
1048
1049        private String getDefaultScheme() {
1050            return IntentFilter.SCHEME_HTTPS;
1051        }
1052
1053        @Override
1054        public void startVerifications(int userId) {
1055            // Launch verifications requests
1056            int count = mCurrentIntentFilterVerifications.size();
1057            for (int n=0; n<count; n++) {
1058                int verificationId = mCurrentIntentFilterVerifications.get(n);
1059                final IntentFilterVerificationState ivs =
1060                        mIntentFilterVerificationStates.get(verificationId);
1061
1062                String packageName = ivs.getPackageName();
1063
1064                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1065                final int filterCount = filters.size();
1066                ArraySet<String> domainsSet = new ArraySet<>();
1067                for (int m=0; m<filterCount; m++) {
1068                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1069                    domainsSet.addAll(filter.getHostsList());
1070                }
1071                synchronized (mPackages) {
1072                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1073                            packageName, domainsSet) != null) {
1074                        scheduleWriteSettingsLocked();
1075                    }
1076                }
1077                sendVerificationRequest(verificationId, ivs);
1078            }
1079            mCurrentIntentFilterVerifications.clear();
1080        }
1081
1082        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1083            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1084            verificationIntent.putExtra(
1085                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1086                    verificationId);
1087            verificationIntent.putExtra(
1088                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1089                    getDefaultScheme());
1090            verificationIntent.putExtra(
1091                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1092                    ivs.getHostsString());
1093            verificationIntent.putExtra(
1094                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1095                    ivs.getPackageName());
1096            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1097            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1098
1099            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1100            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1101                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1102                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1103
1104            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1105            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1106                    "Sending IntentFilter verification broadcast");
1107        }
1108
1109        public void receiveVerificationResponse(int verificationId) {
1110            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1111
1112            final boolean verified = ivs.isVerified();
1113
1114            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1115            final int count = filters.size();
1116            if (DEBUG_DOMAIN_VERIFICATION) {
1117                Slog.i(TAG, "Received verification response " + verificationId
1118                        + " for " + count + " filters, verified=" + verified);
1119            }
1120            for (int n=0; n<count; n++) {
1121                PackageParser.ActivityIntentInfo filter = filters.get(n);
1122                filter.setVerified(verified);
1123
1124                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1125                        + " verified with result:" + verified + " and hosts:"
1126                        + ivs.getHostsString());
1127            }
1128
1129            mIntentFilterVerificationStates.remove(verificationId);
1130
1131            final String packageName = ivs.getPackageName();
1132            IntentFilterVerificationInfo ivi = null;
1133
1134            synchronized (mPackages) {
1135                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1136            }
1137            if (ivi == null) {
1138                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1139                        + verificationId + " packageName:" + packageName);
1140                return;
1141            }
1142            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1143                    "Updating IntentFilterVerificationInfo for package " + packageName
1144                            +" verificationId:" + verificationId);
1145
1146            synchronized (mPackages) {
1147                if (verified) {
1148                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1149                } else {
1150                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1151                }
1152                scheduleWriteSettingsLocked();
1153
1154                final int userId = ivs.getUserId();
1155                if (userId != UserHandle.USER_ALL) {
1156                    final int userStatus =
1157                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1158
1159                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1160                    boolean needUpdate = false;
1161
1162                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1163                    // already been set by the User thru the Disambiguation dialog
1164                    switch (userStatus) {
1165                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1166                            if (verified) {
1167                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1168                            } else {
1169                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1170                            }
1171                            needUpdate = true;
1172                            break;
1173
1174                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1175                            if (verified) {
1176                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1177                                needUpdate = true;
1178                            }
1179                            break;
1180
1181                        default:
1182                            // Nothing to do
1183                    }
1184
1185                    if (needUpdate) {
1186                        mSettings.updateIntentFilterVerificationStatusLPw(
1187                                packageName, updatedStatus, userId);
1188                        scheduleWritePackageRestrictionsLocked(userId);
1189                    }
1190                }
1191            }
1192        }
1193
1194        @Override
1195        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1196                    ActivityIntentInfo filter, String packageName) {
1197            if (!hasValidDomains(filter)) {
1198                return false;
1199            }
1200            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1201            if (ivs == null) {
1202                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1203                        packageName);
1204            }
1205            if (DEBUG_DOMAIN_VERIFICATION) {
1206                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1207            }
1208            ivs.addFilter(filter);
1209            return true;
1210        }
1211
1212        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1213                int userId, int verificationId, String packageName) {
1214            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1215                    verifierUid, userId, packageName);
1216            ivs.setPendingState();
1217            synchronized (mPackages) {
1218                mIntentFilterVerificationStates.append(verificationId, ivs);
1219                mCurrentIntentFilterVerifications.add(verificationId);
1220            }
1221            return ivs;
1222        }
1223    }
1224
1225    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1226        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1227                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1228                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1229    }
1230
1231    // Set of pending broadcasts for aggregating enable/disable of components.
1232    static class PendingPackageBroadcasts {
1233        // for each user id, a map of <package name -> components within that package>
1234        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1235
1236        public PendingPackageBroadcasts() {
1237            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1238        }
1239
1240        public ArrayList<String> get(int userId, String packageName) {
1241            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1242            return packages.get(packageName);
1243        }
1244
1245        public void put(int userId, String packageName, ArrayList<String> components) {
1246            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1247            packages.put(packageName, components);
1248        }
1249
1250        public void remove(int userId, String packageName) {
1251            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1252            if (packages != null) {
1253                packages.remove(packageName);
1254            }
1255        }
1256
1257        public void remove(int userId) {
1258            mUidMap.remove(userId);
1259        }
1260
1261        public int userIdCount() {
1262            return mUidMap.size();
1263        }
1264
1265        public int userIdAt(int n) {
1266            return mUidMap.keyAt(n);
1267        }
1268
1269        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1270            return mUidMap.get(userId);
1271        }
1272
1273        public int size() {
1274            // total number of pending broadcast entries across all userIds
1275            int num = 0;
1276            for (int i = 0; i< mUidMap.size(); i++) {
1277                num += mUidMap.valueAt(i).size();
1278            }
1279            return num;
1280        }
1281
1282        public void clear() {
1283            mUidMap.clear();
1284        }
1285
1286        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1287            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1288            if (map == null) {
1289                map = new ArrayMap<String, ArrayList<String>>();
1290                mUidMap.put(userId, map);
1291            }
1292            return map;
1293        }
1294    }
1295    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1296
1297    // Service Connection to remote media container service to copy
1298    // package uri's from external media onto secure containers
1299    // or internal storage.
1300    private IMediaContainerService mContainerService = null;
1301
1302    static final int SEND_PENDING_BROADCAST = 1;
1303    static final int MCS_BOUND = 3;
1304    static final int END_COPY = 4;
1305    static final int INIT_COPY = 5;
1306    static final int MCS_UNBIND = 6;
1307    static final int START_CLEANING_PACKAGE = 7;
1308    static final int FIND_INSTALL_LOC = 8;
1309    static final int POST_INSTALL = 9;
1310    static final int MCS_RECONNECT = 10;
1311    static final int MCS_GIVE_UP = 11;
1312    static final int UPDATED_MEDIA_STATUS = 12;
1313    static final int WRITE_SETTINGS = 13;
1314    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1315    static final int PACKAGE_VERIFIED = 15;
1316    static final int CHECK_PENDING_VERIFICATION = 16;
1317    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1318    static final int INTENT_FILTER_VERIFIED = 18;
1319    static final int WRITE_PACKAGE_LIST = 19;
1320    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1321
1322    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1323
1324    // Delay time in millisecs
1325    static final int BROADCAST_DELAY = 10 * 1000;
1326
1327    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1328            2 * 60 * 60 * 1000L; /* two hours */
1329
1330    static UserManagerService sUserManager;
1331
1332    // Stores a list of users whose package restrictions file needs to be updated
1333    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1334
1335    final private DefaultContainerConnection mDefContainerConn =
1336            new DefaultContainerConnection();
1337    class DefaultContainerConnection implements ServiceConnection {
1338        public void onServiceConnected(ComponentName name, IBinder service) {
1339            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1340            final IMediaContainerService imcs = IMediaContainerService.Stub
1341                    .asInterface(Binder.allowBlocking(service));
1342            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1343        }
1344
1345        public void onServiceDisconnected(ComponentName name) {
1346            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1347        }
1348    }
1349
1350    // Recordkeeping of restore-after-install operations that are currently in flight
1351    // between the Package Manager and the Backup Manager
1352    static class PostInstallData {
1353        public InstallArgs args;
1354        public PackageInstalledInfo res;
1355
1356        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1357            args = _a;
1358            res = _r;
1359        }
1360    }
1361
1362    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1363    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1364
1365    // XML tags for backup/restore of various bits of state
1366    private static final String TAG_PREFERRED_BACKUP = "pa";
1367    private static final String TAG_DEFAULT_APPS = "da";
1368    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1369
1370    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1371    private static final String TAG_ALL_GRANTS = "rt-grants";
1372    private static final String TAG_GRANT = "grant";
1373    private static final String ATTR_PACKAGE_NAME = "pkg";
1374
1375    private static final String TAG_PERMISSION = "perm";
1376    private static final String ATTR_PERMISSION_NAME = "name";
1377    private static final String ATTR_IS_GRANTED = "g";
1378    private static final String ATTR_USER_SET = "set";
1379    private static final String ATTR_USER_FIXED = "fixed";
1380    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1381
1382    // System/policy permission grants are not backed up
1383    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1384            FLAG_PERMISSION_POLICY_FIXED
1385            | FLAG_PERMISSION_SYSTEM_FIXED
1386            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1387
1388    // And we back up these user-adjusted states
1389    private static final int USER_RUNTIME_GRANT_MASK =
1390            FLAG_PERMISSION_USER_SET
1391            | FLAG_PERMISSION_USER_FIXED
1392            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1393
1394    final @Nullable String mRequiredVerifierPackage;
1395    final @NonNull String mRequiredInstallerPackage;
1396    final @NonNull String mRequiredUninstallerPackage;
1397    final @Nullable String mSetupWizardPackage;
1398    final @Nullable String mStorageManagerPackage;
1399    final @NonNull String mServicesSystemSharedLibraryPackageName;
1400    final @NonNull String mSharedSystemSharedLibraryPackageName;
1401
1402    final boolean mPermissionReviewRequired;
1403
1404    private final PackageUsage mPackageUsage = new PackageUsage();
1405    private final CompilerStats mCompilerStats = new CompilerStats();
1406
1407    class PackageHandler extends Handler {
1408        private boolean mBound = false;
1409        final ArrayList<HandlerParams> mPendingInstalls =
1410            new ArrayList<HandlerParams>();
1411
1412        private boolean connectToService() {
1413            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1414                    " DefaultContainerService");
1415            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1416            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1417            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1418                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1419                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1420                mBound = true;
1421                return true;
1422            }
1423            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1424            return false;
1425        }
1426
1427        private void disconnectService() {
1428            mContainerService = null;
1429            mBound = false;
1430            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1431            mContext.unbindService(mDefContainerConn);
1432            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1433        }
1434
1435        PackageHandler(Looper looper) {
1436            super(looper);
1437        }
1438
1439        public void handleMessage(Message msg) {
1440            try {
1441                doHandleMessage(msg);
1442            } finally {
1443                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1444            }
1445        }
1446
1447        void doHandleMessage(Message msg) {
1448            switch (msg.what) {
1449                case INIT_COPY: {
1450                    HandlerParams params = (HandlerParams) msg.obj;
1451                    int idx = mPendingInstalls.size();
1452                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1453                    // If a bind was already initiated we dont really
1454                    // need to do anything. The pending install
1455                    // will be processed later on.
1456                    if (!mBound) {
1457                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1458                                System.identityHashCode(mHandler));
1459                        // If this is the only one pending we might
1460                        // have to bind to the service again.
1461                        if (!connectToService()) {
1462                            Slog.e(TAG, "Failed to bind to media container service");
1463                            params.serviceError();
1464                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1465                                    System.identityHashCode(mHandler));
1466                            if (params.traceMethod != null) {
1467                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1468                                        params.traceCookie);
1469                            }
1470                            return;
1471                        } else {
1472                            // Once we bind to the service, the first
1473                            // pending request will be processed.
1474                            mPendingInstalls.add(idx, params);
1475                        }
1476                    } else {
1477                        mPendingInstalls.add(idx, params);
1478                        // Already bound to the service. Just make
1479                        // sure we trigger off processing the first request.
1480                        if (idx == 0) {
1481                            mHandler.sendEmptyMessage(MCS_BOUND);
1482                        }
1483                    }
1484                    break;
1485                }
1486                case MCS_BOUND: {
1487                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1488                    if (msg.obj != null) {
1489                        mContainerService = (IMediaContainerService) msg.obj;
1490                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1491                                System.identityHashCode(mHandler));
1492                    }
1493                    if (mContainerService == null) {
1494                        if (!mBound) {
1495                            // Something seriously wrong since we are not bound and we are not
1496                            // waiting for connection. Bail out.
1497                            Slog.e(TAG, "Cannot bind to media container service");
1498                            for (HandlerParams params : mPendingInstalls) {
1499                                // Indicate service bind error
1500                                params.serviceError();
1501                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1502                                        System.identityHashCode(params));
1503                                if (params.traceMethod != null) {
1504                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1505                                            params.traceMethod, params.traceCookie);
1506                                }
1507                                return;
1508                            }
1509                            mPendingInstalls.clear();
1510                        } else {
1511                            Slog.w(TAG, "Waiting to connect to media container service");
1512                        }
1513                    } else if (mPendingInstalls.size() > 0) {
1514                        HandlerParams params = mPendingInstalls.get(0);
1515                        if (params != null) {
1516                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1517                                    System.identityHashCode(params));
1518                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1519                            if (params.startCopy()) {
1520                                // We are done...  look for more work or to
1521                                // go idle.
1522                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1523                                        "Checking for more work or unbind...");
1524                                // Delete pending install
1525                                if (mPendingInstalls.size() > 0) {
1526                                    mPendingInstalls.remove(0);
1527                                }
1528                                if (mPendingInstalls.size() == 0) {
1529                                    if (mBound) {
1530                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1531                                                "Posting delayed MCS_UNBIND");
1532                                        removeMessages(MCS_UNBIND);
1533                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1534                                        // Unbind after a little delay, to avoid
1535                                        // continual thrashing.
1536                                        sendMessageDelayed(ubmsg, 10000);
1537                                    }
1538                                } else {
1539                                    // There are more pending requests in queue.
1540                                    // Just post MCS_BOUND message to trigger processing
1541                                    // of next pending install.
1542                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1543                                            "Posting MCS_BOUND for next work");
1544                                    mHandler.sendEmptyMessage(MCS_BOUND);
1545                                }
1546                            }
1547                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1548                        }
1549                    } else {
1550                        // Should never happen ideally.
1551                        Slog.w(TAG, "Empty queue");
1552                    }
1553                    break;
1554                }
1555                case MCS_RECONNECT: {
1556                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1557                    if (mPendingInstalls.size() > 0) {
1558                        if (mBound) {
1559                            disconnectService();
1560                        }
1561                        if (!connectToService()) {
1562                            Slog.e(TAG, "Failed to bind to media container service");
1563                            for (HandlerParams params : mPendingInstalls) {
1564                                // Indicate service bind error
1565                                params.serviceError();
1566                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1567                                        System.identityHashCode(params));
1568                            }
1569                            mPendingInstalls.clear();
1570                        }
1571                    }
1572                    break;
1573                }
1574                case MCS_UNBIND: {
1575                    // If there is no actual work left, then time to unbind.
1576                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1577
1578                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1579                        if (mBound) {
1580                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1581
1582                            disconnectService();
1583                        }
1584                    } else if (mPendingInstalls.size() > 0) {
1585                        // There are more pending requests in queue.
1586                        // Just post MCS_BOUND message to trigger processing
1587                        // of next pending install.
1588                        mHandler.sendEmptyMessage(MCS_BOUND);
1589                    }
1590
1591                    break;
1592                }
1593                case MCS_GIVE_UP: {
1594                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1595                    HandlerParams params = mPendingInstalls.remove(0);
1596                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1597                            System.identityHashCode(params));
1598                    break;
1599                }
1600                case SEND_PENDING_BROADCAST: {
1601                    String packages[];
1602                    ArrayList<String> components[];
1603                    int size = 0;
1604                    int uids[];
1605                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1606                    synchronized (mPackages) {
1607                        if (mPendingBroadcasts == null) {
1608                            return;
1609                        }
1610                        size = mPendingBroadcasts.size();
1611                        if (size <= 0) {
1612                            // Nothing to be done. Just return
1613                            return;
1614                        }
1615                        packages = new String[size];
1616                        components = new ArrayList[size];
1617                        uids = new int[size];
1618                        int i = 0;  // filling out the above arrays
1619
1620                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1621                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1622                            Iterator<Map.Entry<String, ArrayList<String>>> it
1623                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1624                                            .entrySet().iterator();
1625                            while (it.hasNext() && i < size) {
1626                                Map.Entry<String, ArrayList<String>> ent = it.next();
1627                                packages[i] = ent.getKey();
1628                                components[i] = ent.getValue();
1629                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1630                                uids[i] = (ps != null)
1631                                        ? UserHandle.getUid(packageUserId, ps.appId)
1632                                        : -1;
1633                                i++;
1634                            }
1635                        }
1636                        size = i;
1637                        mPendingBroadcasts.clear();
1638                    }
1639                    // Send broadcasts
1640                    for (int i = 0; i < size; i++) {
1641                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1642                    }
1643                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1644                    break;
1645                }
1646                case START_CLEANING_PACKAGE: {
1647                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1648                    final String packageName = (String)msg.obj;
1649                    final int userId = msg.arg1;
1650                    final boolean andCode = msg.arg2 != 0;
1651                    synchronized (mPackages) {
1652                        if (userId == UserHandle.USER_ALL) {
1653                            int[] users = sUserManager.getUserIds();
1654                            for (int user : users) {
1655                                mSettings.addPackageToCleanLPw(
1656                                        new PackageCleanItem(user, packageName, andCode));
1657                            }
1658                        } else {
1659                            mSettings.addPackageToCleanLPw(
1660                                    new PackageCleanItem(userId, packageName, andCode));
1661                        }
1662                    }
1663                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1664                    startCleaningPackages();
1665                } break;
1666                case POST_INSTALL: {
1667                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1668
1669                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1670                    final boolean didRestore = (msg.arg2 != 0);
1671                    mRunningInstalls.delete(msg.arg1);
1672
1673                    if (data != null) {
1674                        InstallArgs args = data.args;
1675                        PackageInstalledInfo parentRes = data.res;
1676
1677                        final boolean grantPermissions = (args.installFlags
1678                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1679                        final boolean killApp = (args.installFlags
1680                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1681                        final boolean virtualPreload = ((args.installFlags
1682                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1683                        final String[] grantedPermissions = args.installGrantPermissions;
1684
1685                        // Handle the parent package
1686                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1687                                virtualPreload, grantedPermissions, didRestore,
1688                                args.installerPackageName, args.observer);
1689
1690                        // Handle the child packages
1691                        final int childCount = (parentRes.addedChildPackages != null)
1692                                ? parentRes.addedChildPackages.size() : 0;
1693                        for (int i = 0; i < childCount; i++) {
1694                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1695                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1696                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1697                                    args.installerPackageName, args.observer);
1698                        }
1699
1700                        // Log tracing if needed
1701                        if (args.traceMethod != null) {
1702                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1703                                    args.traceCookie);
1704                        }
1705                    } else {
1706                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1707                    }
1708
1709                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1710                } break;
1711                case UPDATED_MEDIA_STATUS: {
1712                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1713                    boolean reportStatus = msg.arg1 == 1;
1714                    boolean doGc = msg.arg2 == 1;
1715                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1716                    if (doGc) {
1717                        // Force a gc to clear up stale containers.
1718                        Runtime.getRuntime().gc();
1719                    }
1720                    if (msg.obj != null) {
1721                        @SuppressWarnings("unchecked")
1722                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1723                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1724                        // Unload containers
1725                        unloadAllContainers(args);
1726                    }
1727                    if (reportStatus) {
1728                        try {
1729                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1730                                    "Invoking StorageManagerService call back");
1731                            PackageHelper.getStorageManager().finishMediaUpdate();
1732                        } catch (RemoteException e) {
1733                            Log.e(TAG, "StorageManagerService not running?");
1734                        }
1735                    }
1736                } break;
1737                case WRITE_SETTINGS: {
1738                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1739                    synchronized (mPackages) {
1740                        removeMessages(WRITE_SETTINGS);
1741                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1742                        mSettings.writeLPr();
1743                        mDirtyUsers.clear();
1744                    }
1745                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1746                } break;
1747                case WRITE_PACKAGE_RESTRICTIONS: {
1748                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1749                    synchronized (mPackages) {
1750                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1751                        for (int userId : mDirtyUsers) {
1752                            mSettings.writePackageRestrictionsLPr(userId);
1753                        }
1754                        mDirtyUsers.clear();
1755                    }
1756                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1757                } break;
1758                case WRITE_PACKAGE_LIST: {
1759                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1760                    synchronized (mPackages) {
1761                        removeMessages(WRITE_PACKAGE_LIST);
1762                        mSettings.writePackageListLPr(msg.arg1);
1763                    }
1764                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1765                } break;
1766                case CHECK_PENDING_VERIFICATION: {
1767                    final int verificationId = msg.arg1;
1768                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1769
1770                    if ((state != null) && !state.timeoutExtended()) {
1771                        final InstallArgs args = state.getInstallArgs();
1772                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1773
1774                        Slog.i(TAG, "Verification timed out for " + originUri);
1775                        mPendingVerification.remove(verificationId);
1776
1777                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1778
1779                        final UserHandle user = args.getUser();
1780                        if (getDefaultVerificationResponse(user)
1781                                == PackageManager.VERIFICATION_ALLOW) {
1782                            Slog.i(TAG, "Continuing with installation of " + originUri);
1783                            state.setVerifierResponse(Binder.getCallingUid(),
1784                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1785                            broadcastPackageVerified(verificationId, originUri,
1786                                    PackageManager.VERIFICATION_ALLOW, user);
1787                            try {
1788                                ret = args.copyApk(mContainerService, true);
1789                            } catch (RemoteException e) {
1790                                Slog.e(TAG, "Could not contact the ContainerService");
1791                            }
1792                        } else {
1793                            broadcastPackageVerified(verificationId, originUri,
1794                                    PackageManager.VERIFICATION_REJECT, user);
1795                        }
1796
1797                        Trace.asyncTraceEnd(
1798                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1799
1800                        processPendingInstall(args, ret);
1801                        mHandler.sendEmptyMessage(MCS_UNBIND);
1802                    }
1803                    break;
1804                }
1805                case PACKAGE_VERIFIED: {
1806                    final int verificationId = msg.arg1;
1807
1808                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1809                    if (state == null) {
1810                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1811                        break;
1812                    }
1813
1814                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1815
1816                    state.setVerifierResponse(response.callerUid, response.code);
1817
1818                    if (state.isVerificationComplete()) {
1819                        mPendingVerification.remove(verificationId);
1820
1821                        final InstallArgs args = state.getInstallArgs();
1822                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1823
1824                        int ret;
1825                        if (state.isInstallAllowed()) {
1826                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1827                            broadcastPackageVerified(verificationId, originUri,
1828                                    response.code, state.getInstallArgs().getUser());
1829                            try {
1830                                ret = args.copyApk(mContainerService, true);
1831                            } catch (RemoteException e) {
1832                                Slog.e(TAG, "Could not contact the ContainerService");
1833                            }
1834                        } else {
1835                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1836                        }
1837
1838                        Trace.asyncTraceEnd(
1839                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1840
1841                        processPendingInstall(args, ret);
1842                        mHandler.sendEmptyMessage(MCS_UNBIND);
1843                    }
1844
1845                    break;
1846                }
1847                case START_INTENT_FILTER_VERIFICATIONS: {
1848                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1849                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1850                            params.replacing, params.pkg);
1851                    break;
1852                }
1853                case INTENT_FILTER_VERIFIED: {
1854                    final int verificationId = msg.arg1;
1855
1856                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1857                            verificationId);
1858                    if (state == null) {
1859                        Slog.w(TAG, "Invalid IntentFilter verification token "
1860                                + verificationId + " received");
1861                        break;
1862                    }
1863
1864                    final int userId = state.getUserId();
1865
1866                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1867                            "Processing IntentFilter verification with token:"
1868                            + verificationId + " and userId:" + userId);
1869
1870                    final IntentFilterVerificationResponse response =
1871                            (IntentFilterVerificationResponse) msg.obj;
1872
1873                    state.setVerifierResponse(response.callerUid, response.code);
1874
1875                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1876                            "IntentFilter verification with token:" + verificationId
1877                            + " and userId:" + userId
1878                            + " is settings verifier response with response code:"
1879                            + response.code);
1880
1881                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1882                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1883                                + response.getFailedDomainsString());
1884                    }
1885
1886                    if (state.isVerificationComplete()) {
1887                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1888                    } else {
1889                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1890                                "IntentFilter verification with token:" + verificationId
1891                                + " was not said to be complete");
1892                    }
1893
1894                    break;
1895                }
1896                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1897                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1898                            mInstantAppResolverConnection,
1899                            (InstantAppRequest) msg.obj,
1900                            mInstantAppInstallerActivity,
1901                            mHandler);
1902                }
1903            }
1904        }
1905    }
1906
1907    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1908            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1909            boolean launchedForRestore, String installerPackage,
1910            IPackageInstallObserver2 installObserver) {
1911        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1912            // Send the removed broadcasts
1913            if (res.removedInfo != null) {
1914                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1915            }
1916
1917            // Now that we successfully installed the package, grant runtime
1918            // permissions if requested before broadcasting the install. Also
1919            // for legacy apps in permission review mode we clear the permission
1920            // review flag which is used to emulate runtime permissions for
1921            // legacy apps.
1922            if (grantPermissions) {
1923                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1924            }
1925
1926            final boolean update = res.removedInfo != null
1927                    && res.removedInfo.removedPackage != null;
1928            final String origInstallerPackageName = res.removedInfo != null
1929                    ? res.removedInfo.installerPackageName : null;
1930
1931            // If this is the first time we have child packages for a disabled privileged
1932            // app that had no children, we grant requested runtime permissions to the new
1933            // children if the parent on the system image had them already granted.
1934            if (res.pkg.parentPackage != null) {
1935                synchronized (mPackages) {
1936                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1937                }
1938            }
1939
1940            synchronized (mPackages) {
1941                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1942            }
1943
1944            final String packageName = res.pkg.applicationInfo.packageName;
1945
1946            // Determine the set of users who are adding this package for
1947            // the first time vs. those who are seeing an update.
1948            int[] firstUsers = EMPTY_INT_ARRAY;
1949            int[] updateUsers = EMPTY_INT_ARRAY;
1950            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1951            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1952            for (int newUser : res.newUsers) {
1953                if (ps.getInstantApp(newUser)) {
1954                    continue;
1955                }
1956                if (allNewUsers) {
1957                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1958                    continue;
1959                }
1960                boolean isNew = true;
1961                for (int origUser : res.origUsers) {
1962                    if (origUser == newUser) {
1963                        isNew = false;
1964                        break;
1965                    }
1966                }
1967                if (isNew) {
1968                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1969                } else {
1970                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1971                }
1972            }
1973
1974            // Send installed broadcasts if the package is not a static shared lib.
1975            if (res.pkg.staticSharedLibName == null) {
1976                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1977
1978                // Send added for users that see the package for the first time
1979                // sendPackageAddedForNewUsers also deals with system apps
1980                int appId = UserHandle.getAppId(res.uid);
1981                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1982                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1983                        virtualPreload /*startReceiver*/, appId, firstUsers);
1984
1985                // Send added for users that don't see the package for the first time
1986                Bundle extras = new Bundle(1);
1987                extras.putInt(Intent.EXTRA_UID, res.uid);
1988                if (update) {
1989                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1990                }
1991                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1992                        extras, 0 /*flags*/,
1993                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1994                if (origInstallerPackageName != null) {
1995                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1996                            extras, 0 /*flags*/,
1997                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1998                }
1999
2000                // Send replaced for users that don't see the package for the first time
2001                if (update) {
2002                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2003                            packageName, extras, 0 /*flags*/,
2004                            null /*targetPackage*/, null /*finishedReceiver*/,
2005                            updateUsers);
2006                    if (origInstallerPackageName != null) {
2007                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2008                                extras, 0 /*flags*/,
2009                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
2010                    }
2011                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2012                            null /*package*/, null /*extras*/, 0 /*flags*/,
2013                            packageName /*targetPackage*/,
2014                            null /*finishedReceiver*/, updateUsers);
2015                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2016                    // First-install and we did a restore, so we're responsible for the
2017                    // first-launch broadcast.
2018                    if (DEBUG_BACKUP) {
2019                        Slog.i(TAG, "Post-restore of " + packageName
2020                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2021                    }
2022                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2023                }
2024
2025                // Send broadcast package appeared if forward locked/external for all users
2026                // treat asec-hosted packages like removable media on upgrade
2027                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2028                    if (DEBUG_INSTALL) {
2029                        Slog.i(TAG, "upgrading pkg " + res.pkg
2030                                + " is ASEC-hosted -> AVAILABLE");
2031                    }
2032                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2033                    ArrayList<String> pkgList = new ArrayList<>(1);
2034                    pkgList.add(packageName);
2035                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2036                }
2037            }
2038
2039            // Work that needs to happen on first install within each user
2040            if (firstUsers != null && firstUsers.length > 0) {
2041                synchronized (mPackages) {
2042                    for (int userId : firstUsers) {
2043                        // If this app is a browser and it's newly-installed for some
2044                        // users, clear any default-browser state in those users. The
2045                        // app's nature doesn't depend on the user, so we can just check
2046                        // its browser nature in any user and generalize.
2047                        if (packageIsBrowser(packageName, userId)) {
2048                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2049                        }
2050
2051                        // We may also need to apply pending (restored) runtime
2052                        // permission grants within these users.
2053                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2054                    }
2055                }
2056            }
2057
2058            // Log current value of "unknown sources" setting
2059            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2060                    getUnknownSourcesSettings());
2061
2062            // Remove the replaced package's older resources safely now
2063            // We delete after a gc for applications  on sdcard.
2064            if (res.removedInfo != null && res.removedInfo.args != null) {
2065                Runtime.getRuntime().gc();
2066                synchronized (mInstallLock) {
2067                    res.removedInfo.args.doPostDeleteLI(true);
2068                }
2069            } else {
2070                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2071                // and not block here.
2072                VMRuntime.getRuntime().requestConcurrentGC();
2073            }
2074
2075            // Notify DexManager that the package was installed for new users.
2076            // The updated users should already be indexed and the package code paths
2077            // should not change.
2078            // Don't notify the manager for ephemeral apps as they are not expected to
2079            // survive long enough to benefit of background optimizations.
2080            for (int userId : firstUsers) {
2081                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2082                // There's a race currently where some install events may interleave with an uninstall.
2083                // This can lead to package info being null (b/36642664).
2084                if (info != null) {
2085                    mDexManager.notifyPackageInstalled(info, userId);
2086                }
2087            }
2088        }
2089
2090        // If someone is watching installs - notify them
2091        if (installObserver != null) {
2092            try {
2093                Bundle extras = extrasForInstallResult(res);
2094                installObserver.onPackageInstalled(res.name, res.returnCode,
2095                        res.returnMsg, extras);
2096            } catch (RemoteException e) {
2097                Slog.i(TAG, "Observer no longer exists.");
2098            }
2099        }
2100    }
2101
2102    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2103            PackageParser.Package pkg) {
2104        if (pkg.parentPackage == null) {
2105            return;
2106        }
2107        if (pkg.requestedPermissions == null) {
2108            return;
2109        }
2110        final PackageSetting disabledSysParentPs = mSettings
2111                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2112        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2113                || !disabledSysParentPs.isPrivileged()
2114                || (disabledSysParentPs.childPackageNames != null
2115                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2116            return;
2117        }
2118        final int[] allUserIds = sUserManager.getUserIds();
2119        final int permCount = pkg.requestedPermissions.size();
2120        for (int i = 0; i < permCount; i++) {
2121            String permission = pkg.requestedPermissions.get(i);
2122            BasePermission bp = mSettings.mPermissions.get(permission);
2123            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2124                continue;
2125            }
2126            for (int userId : allUserIds) {
2127                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2128                        permission, userId)) {
2129                    grantRuntimePermission(pkg.packageName, permission, userId);
2130                }
2131            }
2132        }
2133    }
2134
2135    private StorageEventListener mStorageListener = new StorageEventListener() {
2136        @Override
2137        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2138            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2139                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2140                    final String volumeUuid = vol.getFsUuid();
2141
2142                    // Clean up any users or apps that were removed or recreated
2143                    // while this volume was missing
2144                    sUserManager.reconcileUsers(volumeUuid);
2145                    reconcileApps(volumeUuid);
2146
2147                    // Clean up any install sessions that expired or were
2148                    // cancelled while this volume was missing
2149                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2150
2151                    loadPrivatePackages(vol);
2152
2153                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2154                    unloadPrivatePackages(vol);
2155                }
2156            }
2157
2158            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2159                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2160                    updateExternalMediaStatus(true, false);
2161                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2162                    updateExternalMediaStatus(false, false);
2163                }
2164            }
2165        }
2166
2167        @Override
2168        public void onVolumeForgotten(String fsUuid) {
2169            if (TextUtils.isEmpty(fsUuid)) {
2170                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2171                return;
2172            }
2173
2174            // Remove any apps installed on the forgotten volume
2175            synchronized (mPackages) {
2176                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2177                for (PackageSetting ps : packages) {
2178                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2179                    deletePackageVersioned(new VersionedPackage(ps.name,
2180                            PackageManager.VERSION_CODE_HIGHEST),
2181                            new LegacyPackageDeleteObserver(null).getBinder(),
2182                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2183                    // Try very hard to release any references to this package
2184                    // so we don't risk the system server being killed due to
2185                    // open FDs
2186                    AttributeCache.instance().removePackage(ps.name);
2187                }
2188
2189                mSettings.onVolumeForgotten(fsUuid);
2190                mSettings.writeLPr();
2191            }
2192        }
2193    };
2194
2195    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2196            String[] grantedPermissions) {
2197        for (int userId : userIds) {
2198            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2199        }
2200    }
2201
2202    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2203            String[] grantedPermissions) {
2204        PackageSetting ps = (PackageSetting) pkg.mExtras;
2205        if (ps == null) {
2206            return;
2207        }
2208
2209        PermissionsState permissionsState = ps.getPermissionsState();
2210
2211        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2212                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2213
2214        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2215                >= Build.VERSION_CODES.M;
2216
2217        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2218
2219        for (String permission : pkg.requestedPermissions) {
2220            final BasePermission bp;
2221            synchronized (mPackages) {
2222                bp = mSettings.mPermissions.get(permission);
2223            }
2224            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2225                    && (!instantApp || bp.isInstant())
2226                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2227                    && (grantedPermissions == null
2228                           || ArrayUtils.contains(grantedPermissions, permission))) {
2229                final int flags = permissionsState.getPermissionFlags(permission, userId);
2230                if (supportsRuntimePermissions) {
2231                    // Installer cannot change immutable permissions.
2232                    if ((flags & immutableFlags) == 0) {
2233                        grantRuntimePermission(pkg.packageName, permission, userId);
2234                    }
2235                } else if (mPermissionReviewRequired) {
2236                    // In permission review mode we clear the review flag when we
2237                    // are asked to install the app with all permissions granted.
2238                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2239                        updatePermissionFlags(permission, pkg.packageName,
2240                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2241                    }
2242                }
2243            }
2244        }
2245    }
2246
2247    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2248        Bundle extras = null;
2249        switch (res.returnCode) {
2250            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2251                extras = new Bundle();
2252                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2253                        res.origPermission);
2254                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2255                        res.origPackage);
2256                break;
2257            }
2258            case PackageManager.INSTALL_SUCCEEDED: {
2259                extras = new Bundle();
2260                extras.putBoolean(Intent.EXTRA_REPLACING,
2261                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2262                break;
2263            }
2264        }
2265        return extras;
2266    }
2267
2268    void scheduleWriteSettingsLocked() {
2269        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2270            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2271        }
2272    }
2273
2274    void scheduleWritePackageListLocked(int userId) {
2275        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2276            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2277            msg.arg1 = userId;
2278            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2279        }
2280    }
2281
2282    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2283        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2284        scheduleWritePackageRestrictionsLocked(userId);
2285    }
2286
2287    void scheduleWritePackageRestrictionsLocked(int userId) {
2288        final int[] userIds = (userId == UserHandle.USER_ALL)
2289                ? sUserManager.getUserIds() : new int[]{userId};
2290        for (int nextUserId : userIds) {
2291            if (!sUserManager.exists(nextUserId)) return;
2292            mDirtyUsers.add(nextUserId);
2293            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2294                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2295            }
2296        }
2297    }
2298
2299    public static PackageManagerService main(Context context, Installer installer,
2300            boolean factoryTest, boolean onlyCore) {
2301        // Self-check for initial settings.
2302        PackageManagerServiceCompilerMapping.checkProperties();
2303
2304        PackageManagerService m = new PackageManagerService(context, installer,
2305                factoryTest, onlyCore);
2306        m.enableSystemUserPackages();
2307        ServiceManager.addService("package", m);
2308        final PackageManagerNative pmn = m.new PackageManagerNative();
2309        ServiceManager.addService("package_native", pmn);
2310        return m;
2311    }
2312
2313    private void enableSystemUserPackages() {
2314        if (!UserManager.isSplitSystemUser()) {
2315            return;
2316        }
2317        // For system user, enable apps based on the following conditions:
2318        // - app is whitelisted or belong to one of these groups:
2319        //   -- system app which has no launcher icons
2320        //   -- system app which has INTERACT_ACROSS_USERS permission
2321        //   -- system IME app
2322        // - app is not in the blacklist
2323        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2324        Set<String> enableApps = new ArraySet<>();
2325        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2326                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2327                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2328        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2329        enableApps.addAll(wlApps);
2330        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2331                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2332        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2333        enableApps.removeAll(blApps);
2334        Log.i(TAG, "Applications installed for system user: " + enableApps);
2335        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2336                UserHandle.SYSTEM);
2337        final int allAppsSize = allAps.size();
2338        synchronized (mPackages) {
2339            for (int i = 0; i < allAppsSize; i++) {
2340                String pName = allAps.get(i);
2341                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2342                // Should not happen, but we shouldn't be failing if it does
2343                if (pkgSetting == null) {
2344                    continue;
2345                }
2346                boolean install = enableApps.contains(pName);
2347                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2348                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2349                            + " for system user");
2350                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2351                }
2352            }
2353            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2354        }
2355    }
2356
2357    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2358        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2359                Context.DISPLAY_SERVICE);
2360        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2361    }
2362
2363    /**
2364     * Requests that files preopted on a secondary system partition be copied to the data partition
2365     * if possible.  Note that the actual copying of the files is accomplished by init for security
2366     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2367     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2368     */
2369    private static void requestCopyPreoptedFiles() {
2370        final int WAIT_TIME_MS = 100;
2371        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2372        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2373            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2374            // We will wait for up to 100 seconds.
2375            final long timeStart = SystemClock.uptimeMillis();
2376            final long timeEnd = timeStart + 100 * 1000;
2377            long timeNow = timeStart;
2378            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2379                try {
2380                    Thread.sleep(WAIT_TIME_MS);
2381                } catch (InterruptedException e) {
2382                    // Do nothing
2383                }
2384                timeNow = SystemClock.uptimeMillis();
2385                if (timeNow > timeEnd) {
2386                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2387                    Slog.wtf(TAG, "cppreopt did not finish!");
2388                    break;
2389                }
2390            }
2391
2392            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2393        }
2394    }
2395
2396    public PackageManagerService(Context context, Installer installer,
2397            boolean factoryTest, boolean onlyCore) {
2398        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2399        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2400        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2401                SystemClock.uptimeMillis());
2402
2403        if (mSdkVersion <= 0) {
2404            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2405        }
2406
2407        mContext = context;
2408
2409        mPermissionReviewRequired = context.getResources().getBoolean(
2410                R.bool.config_permissionReviewRequired);
2411
2412        mFactoryTest = factoryTest;
2413        mOnlyCore = onlyCore;
2414        mMetrics = new DisplayMetrics();
2415        mSettings = new Settings(mPackages);
2416        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2417                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2418        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2419                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2420        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2421                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2422        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2423                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2424        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2425                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2426        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2427                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2428
2429        String separateProcesses = SystemProperties.get("debug.separate_processes");
2430        if (separateProcesses != null && separateProcesses.length() > 0) {
2431            if ("*".equals(separateProcesses)) {
2432                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2433                mSeparateProcesses = null;
2434                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2435            } else {
2436                mDefParseFlags = 0;
2437                mSeparateProcesses = separateProcesses.split(",");
2438                Slog.w(TAG, "Running with debug.separate_processes: "
2439                        + separateProcesses);
2440            }
2441        } else {
2442            mDefParseFlags = 0;
2443            mSeparateProcesses = null;
2444        }
2445
2446        mInstaller = installer;
2447        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2448                "*dexopt*");
2449        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2450        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2451
2452        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2453                FgThread.get().getLooper());
2454
2455        getDefaultDisplayMetrics(context, mMetrics);
2456
2457        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2458        SystemConfig systemConfig = SystemConfig.getInstance();
2459        mGlobalGids = systemConfig.getGlobalGids();
2460        mSystemPermissions = systemConfig.getSystemPermissions();
2461        mAvailableFeatures = systemConfig.getAvailableFeatures();
2462        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2463
2464        mProtectedPackages = new ProtectedPackages(mContext);
2465
2466        synchronized (mInstallLock) {
2467        // writer
2468        synchronized (mPackages) {
2469            mHandlerThread = new ServiceThread(TAG,
2470                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2471            mHandlerThread.start();
2472            mHandler = new PackageHandler(mHandlerThread.getLooper());
2473            mProcessLoggingHandler = new ProcessLoggingHandler();
2474            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2475
2476            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2477            mInstantAppRegistry = new InstantAppRegistry(this);
2478
2479            File dataDir = Environment.getDataDirectory();
2480            mAppInstallDir = new File(dataDir, "app");
2481            mAppLib32InstallDir = new File(dataDir, "app-lib");
2482            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2483            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2484            sUserManager = new UserManagerService(context, this,
2485                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2486
2487            // Propagate permission configuration in to package manager.
2488            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2489                    = systemConfig.getPermissions();
2490            for (int i=0; i<permConfig.size(); i++) {
2491                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2492                BasePermission bp = mSettings.mPermissions.get(perm.name);
2493                if (bp == null) {
2494                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2495                    mSettings.mPermissions.put(perm.name, bp);
2496                }
2497                if (perm.gids != null) {
2498                    bp.setGids(perm.gids, perm.perUser);
2499                }
2500            }
2501
2502            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2503            final int builtInLibCount = libConfig.size();
2504            for (int i = 0; i < builtInLibCount; i++) {
2505                String name = libConfig.keyAt(i);
2506                String path = libConfig.valueAt(i);
2507                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2508                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2509            }
2510
2511            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2512
2513            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2514            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2515            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2516
2517            // Clean up orphaned packages for which the code path doesn't exist
2518            // and they are an update to a system app - caused by bug/32321269
2519            final int packageSettingCount = mSettings.mPackages.size();
2520            for (int i = packageSettingCount - 1; i >= 0; i--) {
2521                PackageSetting ps = mSettings.mPackages.valueAt(i);
2522                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2523                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2524                    mSettings.mPackages.removeAt(i);
2525                    mSettings.enableSystemPackageLPw(ps.name);
2526                }
2527            }
2528
2529            if (mFirstBoot) {
2530                requestCopyPreoptedFiles();
2531            }
2532
2533            String customResolverActivity = Resources.getSystem().getString(
2534                    R.string.config_customResolverActivity);
2535            if (TextUtils.isEmpty(customResolverActivity)) {
2536                customResolverActivity = null;
2537            } else {
2538                mCustomResolverComponentName = ComponentName.unflattenFromString(
2539                        customResolverActivity);
2540            }
2541
2542            long startTime = SystemClock.uptimeMillis();
2543
2544            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2545                    startTime);
2546
2547            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2548            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2549
2550            if (bootClassPath == null) {
2551                Slog.w(TAG, "No BOOTCLASSPATH found!");
2552            }
2553
2554            if (systemServerClassPath == null) {
2555                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2556            }
2557
2558            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2559
2560            final VersionInfo ver = mSettings.getInternalVersion();
2561            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2562            if (mIsUpgrade) {
2563                logCriticalInfo(Log.INFO,
2564                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2565            }
2566
2567            // when upgrading from pre-M, promote system app permissions from install to runtime
2568            mPromoteSystemApps =
2569                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2570
2571            // When upgrading from pre-N, we need to handle package extraction like first boot,
2572            // as there is no profiling data available.
2573            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2574
2575            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2576
2577            // save off the names of pre-existing system packages prior to scanning; we don't
2578            // want to automatically grant runtime permissions for new system apps
2579            if (mPromoteSystemApps) {
2580                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2581                while (pkgSettingIter.hasNext()) {
2582                    PackageSetting ps = pkgSettingIter.next();
2583                    if (isSystemApp(ps)) {
2584                        mExistingSystemPackages.add(ps.name);
2585                    }
2586                }
2587            }
2588
2589            mCacheDir = preparePackageParserCache(mIsUpgrade);
2590
2591            // Set flag to monitor and not change apk file paths when
2592            // scanning install directories.
2593            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2594
2595            if (mIsUpgrade || mFirstBoot) {
2596                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2597            }
2598
2599            // Collect vendor overlay packages. (Do this before scanning any apps.)
2600            // For security and version matching reason, only consider
2601            // overlay packages if they reside in the right directory.
2602            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2603                    | PackageParser.PARSE_IS_SYSTEM
2604                    | PackageParser.PARSE_IS_SYSTEM_DIR
2605                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2606
2607            mParallelPackageParserCallback.findStaticOverlayPackages();
2608
2609            // Find base frameworks (resource packages without code).
2610            scanDirTracedLI(frameworkDir, mDefParseFlags
2611                    | PackageParser.PARSE_IS_SYSTEM
2612                    | PackageParser.PARSE_IS_SYSTEM_DIR
2613                    | PackageParser.PARSE_IS_PRIVILEGED,
2614                    scanFlags | SCAN_NO_DEX, 0);
2615
2616            // Collected privileged system packages.
2617            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2618            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2619                    | PackageParser.PARSE_IS_SYSTEM
2620                    | PackageParser.PARSE_IS_SYSTEM_DIR
2621                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2622
2623            // Collect ordinary system packages.
2624            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2625            scanDirTracedLI(systemAppDir, mDefParseFlags
2626                    | PackageParser.PARSE_IS_SYSTEM
2627                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2628
2629            // Collect all vendor packages.
2630            File vendorAppDir = new File("/vendor/app");
2631            try {
2632                vendorAppDir = vendorAppDir.getCanonicalFile();
2633            } catch (IOException e) {
2634                // failed to look up canonical path, continue with original one
2635            }
2636            scanDirTracedLI(vendorAppDir, mDefParseFlags
2637                    | PackageParser.PARSE_IS_SYSTEM
2638                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2639
2640            // Collect all OEM packages.
2641            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2642            scanDirTracedLI(oemAppDir, mDefParseFlags
2643                    | PackageParser.PARSE_IS_SYSTEM
2644                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2645
2646            // Prune any system packages that no longer exist.
2647            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2648            // Stub packages must either be replaced with full versions in the /data
2649            // partition or be disabled.
2650            final List<String> stubSystemApps = new ArrayList<>();
2651            if (!mOnlyCore) {
2652                // do this first before mucking with mPackages for the "expecting better" case
2653                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2654                while (pkgIterator.hasNext()) {
2655                    final PackageParser.Package pkg = pkgIterator.next();
2656                    if (pkg.isStub) {
2657                        stubSystemApps.add(pkg.packageName);
2658                    }
2659                }
2660
2661                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2662                while (psit.hasNext()) {
2663                    PackageSetting ps = psit.next();
2664
2665                    /*
2666                     * If this is not a system app, it can't be a
2667                     * disable system app.
2668                     */
2669                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2670                        continue;
2671                    }
2672
2673                    /*
2674                     * If the package is scanned, it's not erased.
2675                     */
2676                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2677                    if (scannedPkg != null) {
2678                        /*
2679                         * If the system app is both scanned and in the
2680                         * disabled packages list, then it must have been
2681                         * added via OTA. Remove it from the currently
2682                         * scanned package so the previously user-installed
2683                         * application can be scanned.
2684                         */
2685                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2686                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2687                                    + ps.name + "; removing system app.  Last known codePath="
2688                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2689                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2690                                    + scannedPkg.mVersionCode);
2691                            removePackageLI(scannedPkg, true);
2692                            mExpectingBetter.put(ps.name, ps.codePath);
2693                        }
2694
2695                        continue;
2696                    }
2697
2698                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2699                        psit.remove();
2700                        logCriticalInfo(Log.WARN, "System package " + ps.name
2701                                + " no longer exists; it's data will be wiped");
2702                        // Actual deletion of code and data will be handled by later
2703                        // reconciliation step
2704                    } else {
2705                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2706                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2707                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2708                        }
2709                    }
2710                }
2711            }
2712
2713            //look for any incomplete package installations
2714            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2715            for (int i = 0; i < deletePkgsList.size(); i++) {
2716                // Actual deletion of code and data will be handled by later
2717                // reconciliation step
2718                final String packageName = deletePkgsList.get(i).name;
2719                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2720                synchronized (mPackages) {
2721                    mSettings.removePackageLPw(packageName);
2722                }
2723            }
2724
2725            //delete tmp files
2726            deleteTempPackageFiles();
2727
2728            // Remove any shared userIDs that have no associated packages
2729            mSettings.pruneSharedUsersLPw();
2730            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2731            final int systemPackagesCount = mPackages.size();
2732            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2733                    + " ms, packageCount: " + systemPackagesCount
2734                    + " ms, timePerPackage: "
2735                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount));
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 long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2827                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2828                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2829                        + " ms, packageCount: " + dataPackagesCount
2830                        + " ms, timePerPackage: "
2831                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount));
2832                if (mIsUpgrade && dataPackagesCount > 0) {
2833                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2834                            ((int) dataScanTime) / dataPackagesCount);
2835                }
2836            }
2837            mExpectingBetter.clear();
2838
2839            // Resolve the storage manager.
2840            mStorageManagerPackage = getStorageManagerPackageName();
2841
2842            // Resolve protected action filters. Only the setup wizard is allowed to
2843            // have a high priority filter for these actions.
2844            mSetupWizardPackage = getSetupWizardPackageName();
2845            if (mProtectedFilters.size() > 0) {
2846                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2847                    Slog.i(TAG, "No setup wizard;"
2848                        + " All protected intents capped to priority 0");
2849                }
2850                for (ActivityIntentInfo filter : mProtectedFilters) {
2851                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2852                        if (DEBUG_FILTERS) {
2853                            Slog.i(TAG, "Found setup wizard;"
2854                                + " allow priority " + filter.getPriority() + ";"
2855                                + " package: " + filter.activity.info.packageName
2856                                + " activity: " + filter.activity.className
2857                                + " priority: " + filter.getPriority());
2858                        }
2859                        // skip setup wizard; allow it to keep the high priority filter
2860                        continue;
2861                    }
2862                    if (DEBUG_FILTERS) {
2863                        Slog.i(TAG, "Protected action; cap priority to 0;"
2864                                + " package: " + filter.activity.info.packageName
2865                                + " activity: " + filter.activity.className
2866                                + " origPrio: " + filter.getPriority());
2867                    }
2868                    filter.setPriority(0);
2869                }
2870            }
2871            mDeferProtectedFilters = false;
2872            mProtectedFilters.clear();
2873
2874            // Now that we know all of the shared libraries, update all clients to have
2875            // the correct library paths.
2876            updateAllSharedLibrariesLPw(null);
2877
2878            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2879                // NOTE: We ignore potential failures here during a system scan (like
2880                // the rest of the commands above) because there's precious little we
2881                // can do about it. A settings error is reported, though.
2882                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2883            }
2884
2885            // Now that we know all the packages we are keeping,
2886            // read and update their last usage times.
2887            mPackageUsage.read(mPackages);
2888            mCompilerStats.read();
2889
2890            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2891                    SystemClock.uptimeMillis());
2892            Slog.i(TAG, "Time to scan packages: "
2893                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2894                    + " seconds");
2895
2896            // If the platform SDK has changed since the last time we booted,
2897            // we need to re-grant app permission to catch any new ones that
2898            // appear.  This is really a hack, and means that apps can in some
2899            // cases get permissions that the user didn't initially explicitly
2900            // allow...  it would be nice to have some better way to handle
2901            // this situation.
2902            int updateFlags = UPDATE_PERMISSIONS_ALL;
2903            if (ver.sdkVersion != mSdkVersion) {
2904                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2905                        + mSdkVersion + "; regranting permissions for internal storage");
2906                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2907            }
2908            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2909            ver.sdkVersion = mSdkVersion;
2910
2911            // If this is the first boot or an update from pre-M, and it is a normal
2912            // boot, then we need to initialize the default preferred apps across
2913            // all defined users.
2914            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2915                for (UserInfo user : sUserManager.getUsers(true)) {
2916                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2917                    applyFactoryDefaultBrowserLPw(user.id);
2918                    primeDomainVerificationsLPw(user.id);
2919                }
2920            }
2921
2922            // Prepare storage for system user really early during boot,
2923            // since core system apps like SettingsProvider and SystemUI
2924            // can't wait for user to start
2925            final int storageFlags;
2926            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2927                storageFlags = StorageManager.FLAG_STORAGE_DE;
2928            } else {
2929                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2930            }
2931            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2932                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2933                    true /* onlyCoreApps */);
2934            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2935                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2936                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2937                traceLog.traceBegin("AppDataFixup");
2938                try {
2939                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2940                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2941                } catch (InstallerException e) {
2942                    Slog.w(TAG, "Trouble fixing GIDs", e);
2943                }
2944                traceLog.traceEnd();
2945
2946                traceLog.traceBegin("AppDataPrepare");
2947                if (deferPackages == null || deferPackages.isEmpty()) {
2948                    return;
2949                }
2950                int count = 0;
2951                for (String pkgName : deferPackages) {
2952                    PackageParser.Package pkg = null;
2953                    synchronized (mPackages) {
2954                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2955                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2956                            pkg = ps.pkg;
2957                        }
2958                    }
2959                    if (pkg != null) {
2960                        synchronized (mInstallLock) {
2961                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2962                                    true /* maybeMigrateAppData */);
2963                        }
2964                        count++;
2965                    }
2966                }
2967                traceLog.traceEnd();
2968                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2969            }, "prepareAppData");
2970
2971            // If this is first boot after an OTA, and a normal boot, then
2972            // we need to clear code cache directories.
2973            // Note that we do *not* clear the application profiles. These remain valid
2974            // across OTAs and are used to drive profile verification (post OTA) and
2975            // profile compilation (without waiting to collect a fresh set of profiles).
2976            if (mIsUpgrade && !onlyCore) {
2977                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2978                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2979                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2980                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2981                        // No apps are running this early, so no need to freeze
2982                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2983                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2984                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2985                    }
2986                }
2987                ver.fingerprint = Build.FINGERPRINT;
2988            }
2989
2990            checkDefaultBrowser();
2991
2992            // clear only after permissions and other defaults have been updated
2993            mExistingSystemPackages.clear();
2994            mPromoteSystemApps = false;
2995
2996            // All the changes are done during package scanning.
2997            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2998
2999            // can downgrade to reader
3000            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3001            mSettings.writeLPr();
3002            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3003            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3004                    SystemClock.uptimeMillis());
3005
3006            if (!mOnlyCore) {
3007                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3008                mRequiredInstallerPackage = getRequiredInstallerLPr();
3009                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3010                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3011                if (mIntentFilterVerifierComponent != null) {
3012                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3013                            mIntentFilterVerifierComponent);
3014                } else {
3015                    mIntentFilterVerifier = null;
3016                }
3017                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3018                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3019                        SharedLibraryInfo.VERSION_UNDEFINED);
3020                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3021                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3022                        SharedLibraryInfo.VERSION_UNDEFINED);
3023            } else {
3024                mRequiredVerifierPackage = null;
3025                mRequiredInstallerPackage = null;
3026                mRequiredUninstallerPackage = null;
3027                mIntentFilterVerifierComponent = null;
3028                mIntentFilterVerifier = null;
3029                mServicesSystemSharedLibraryPackageName = null;
3030                mSharedSystemSharedLibraryPackageName = null;
3031            }
3032
3033            mInstallerService = new PackageInstallerService(context, this);
3034            final Pair<ComponentName, String> instantAppResolverComponent =
3035                    getInstantAppResolverLPr();
3036            if (instantAppResolverComponent != null) {
3037                if (DEBUG_EPHEMERAL) {
3038                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3039                }
3040                mInstantAppResolverConnection = new EphemeralResolverConnection(
3041                        mContext, instantAppResolverComponent.first,
3042                        instantAppResolverComponent.second);
3043                mInstantAppResolverSettingsComponent =
3044                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3045            } else {
3046                mInstantAppResolverConnection = null;
3047                mInstantAppResolverSettingsComponent = null;
3048            }
3049            updateInstantAppInstallerLocked(null);
3050
3051            // Read and update the usage of dex files.
3052            // Do this at the end of PM init so that all the packages have their
3053            // data directory reconciled.
3054            // At this point we know the code paths of the packages, so we can validate
3055            // the disk file and build the internal cache.
3056            // The usage file is expected to be small so loading and verifying it
3057            // should take a fairly small time compare to the other activities (e.g. package
3058            // scanning).
3059            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3060            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3061            for (int userId : currentUserIds) {
3062                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3063            }
3064            mDexManager.load(userPackages);
3065            if (mIsUpgrade) {
3066                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3067                        (int) (SystemClock.uptimeMillis() - startTime));
3068            }
3069        } // synchronized (mPackages)
3070        } // synchronized (mInstallLock)
3071
3072        // Now after opening every single application zip, make sure they
3073        // are all flushed.  Not really needed, but keeps things nice and
3074        // tidy.
3075        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3076        Runtime.getRuntime().gc();
3077        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3078
3079        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3080        FallbackCategoryProvider.loadFallbacks();
3081        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3082
3083        // The initial scanning above does many calls into installd while
3084        // holding the mPackages lock, but we're mostly interested in yelling
3085        // once we have a booted system.
3086        mInstaller.setWarnIfHeld(mPackages);
3087
3088        // Expose private service for system components to use.
3089        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3090        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3091    }
3092
3093    /**
3094     * Uncompress and install stub applications.
3095     * <p>In order to save space on the system partition, some applications are shipped in a
3096     * compressed form. In addition the compressed bits for the full application, the
3097     * system image contains a tiny stub comprised of only the Android manifest.
3098     * <p>During the first boot, attempt to uncompress and install the full application. If
3099     * the application can't be installed for any reason, disable the stub and prevent
3100     * uncompressing the full application during future boots.
3101     * <p>In order to forcefully attempt an installation of a full application, go to app
3102     * settings and enable the application.
3103     */
3104    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3105        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3106            final String pkgName = stubSystemApps.get(i);
3107            // skip if the system package is already disabled
3108            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3109                stubSystemApps.remove(i);
3110                continue;
3111            }
3112            // skip if the package isn't installed (?!); this should never happen
3113            final PackageParser.Package pkg = mPackages.get(pkgName);
3114            if (pkg == null) {
3115                stubSystemApps.remove(i);
3116                continue;
3117            }
3118            // skip if the package has been disabled by the user
3119            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3120            if (ps != null) {
3121                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3122                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3123                    stubSystemApps.remove(i);
3124                    continue;
3125                }
3126            }
3127
3128            if (DEBUG_COMPRESSION) {
3129                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3130            }
3131
3132            // uncompress the binary to its eventual destination on /data
3133            final File scanFile = decompressPackage(pkg);
3134            if (scanFile == null) {
3135                continue;
3136            }
3137
3138            // install the package to replace the stub on /system
3139            try {
3140                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3141                removePackageLI(pkg, true /*chatty*/);
3142                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3143                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3144                        UserHandle.USER_SYSTEM, "android");
3145                stubSystemApps.remove(i);
3146                continue;
3147            } catch (PackageManagerException e) {
3148                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3149            }
3150
3151            // any failed attempt to install the package will be cleaned up later
3152        }
3153
3154        // disable any stub still left; these failed to install the full application
3155        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3156            final String pkgName = stubSystemApps.get(i);
3157            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3158            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3159                    UserHandle.USER_SYSTEM, "android");
3160            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3161        }
3162    }
3163
3164    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3165        if (DEBUG_COMPRESSION) {
3166            Slog.i(TAG, "Decompress file"
3167                    + "; src: " + srcFile.getAbsolutePath()
3168                    + ", dst: " + dstFile.getAbsolutePath());
3169        }
3170        try (
3171                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3172                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3173        ) {
3174            Streams.copy(fileIn, fileOut);
3175            Os.chmod(dstFile.getAbsolutePath(), 0644);
3176            return PackageManager.INSTALL_SUCCEEDED;
3177        } catch (IOException e) {
3178            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3179                    + "; src: " + srcFile.getAbsolutePath()
3180                    + ", dst: " + dstFile.getAbsolutePath());
3181        }
3182        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3183    }
3184
3185    private File[] getCompressedFiles(String codePath) {
3186        return new File(codePath).listFiles(new FilenameFilter() {
3187            @Override
3188            public boolean accept(File dir, String name) {
3189                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3190            }
3191        });
3192    }
3193
3194    private boolean compressedFileExists(String codePath) {
3195        final File[] compressedFiles = getCompressedFiles(codePath);
3196        return compressedFiles != null && compressedFiles.length > 0;
3197    }
3198
3199    /**
3200     * Decompresses the given package on the system image onto
3201     * the /data partition.
3202     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3203     */
3204    private File decompressPackage(PackageParser.Package pkg) {
3205        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3206        if (compressedFiles == null || compressedFiles.length == 0) {
3207            if (DEBUG_COMPRESSION) {
3208                Slog.i(TAG, "No files to decompress");
3209            }
3210            return null;
3211        }
3212        final File dstCodePath =
3213                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3214        int ret = PackageManager.INSTALL_SUCCEEDED;
3215        try {
3216            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3217            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3218            for (File srcFile : compressedFiles) {
3219                final String srcFileName = srcFile.getName();
3220                final String dstFileName = srcFileName.substring(
3221                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3222                final File dstFile = new File(dstCodePath, dstFileName);
3223                ret = decompressFile(srcFile, dstFile);
3224                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3225                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3226                            + "; pkg: " + pkg.packageName
3227                            + ", file: " + dstFileName);
3228                    break;
3229                }
3230            }
3231        } catch (ErrnoException e) {
3232            logCriticalInfo(Log.ERROR, "Failed to decompress"
3233                    + "; pkg: " + pkg.packageName
3234                    + ", err: " + e.errno);
3235        }
3236        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3237            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3238            NativeLibraryHelper.Handle handle = null;
3239            try {
3240                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3241                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3242                        null /*abiOverride*/);
3243            } catch (IOException e) {
3244                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3245                        + "; pkg: " + pkg.packageName);
3246                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3247            } finally {
3248                IoUtils.closeQuietly(handle);
3249            }
3250        }
3251        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3252            if (dstCodePath == null || !dstCodePath.exists()) {
3253                return null;
3254            }
3255            removeCodePathLI(dstCodePath);
3256            return null;
3257        }
3258        return dstCodePath;
3259    }
3260
3261    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3262        // we're only interested in updating the installer appliction when 1) it's not
3263        // already set or 2) the modified package is the installer
3264        if (mInstantAppInstallerActivity != null
3265                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3266                        .equals(modifiedPackage)) {
3267            return;
3268        }
3269        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3270    }
3271
3272    private static File preparePackageParserCache(boolean isUpgrade) {
3273        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3274            return null;
3275        }
3276
3277        // Disable package parsing on eng builds to allow for faster incremental development.
3278        if (Build.IS_ENG) {
3279            return null;
3280        }
3281
3282        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3283            Slog.i(TAG, "Disabling package parser cache due to system property.");
3284            return null;
3285        }
3286
3287        // The base directory for the package parser cache lives under /data/system/.
3288        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3289                "package_cache");
3290        if (cacheBaseDir == null) {
3291            return null;
3292        }
3293
3294        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3295        // This also serves to "GC" unused entries when the package cache version changes (which
3296        // can only happen during upgrades).
3297        if (isUpgrade) {
3298            FileUtils.deleteContents(cacheBaseDir);
3299        }
3300
3301
3302        // Return the versioned package cache directory. This is something like
3303        // "/data/system/package_cache/1"
3304        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3305
3306        // The following is a workaround to aid development on non-numbered userdebug
3307        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3308        // the system partition is newer.
3309        //
3310        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3311        // that starts with "eng." to signify that this is an engineering build and not
3312        // destined for release.
3313        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3314            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3315
3316            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3317            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3318            // in general and should not be used for production changes. In this specific case,
3319            // we know that they will work.
3320            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3321            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3322                FileUtils.deleteContents(cacheBaseDir);
3323                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3324            }
3325        }
3326
3327        return cacheDir;
3328    }
3329
3330    @Override
3331    public boolean isFirstBoot() {
3332        // allow instant applications
3333        return mFirstBoot;
3334    }
3335
3336    @Override
3337    public boolean isOnlyCoreApps() {
3338        // allow instant applications
3339        return mOnlyCore;
3340    }
3341
3342    @Override
3343    public boolean isUpgrade() {
3344        // allow instant applications
3345        return mIsUpgrade;
3346    }
3347
3348    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3349        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3350
3351        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3352                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3353                UserHandle.USER_SYSTEM);
3354        if (matches.size() == 1) {
3355            return matches.get(0).getComponentInfo().packageName;
3356        } else if (matches.size() == 0) {
3357            Log.e(TAG, "There should probably be a verifier, but, none were found");
3358            return null;
3359        }
3360        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3361    }
3362
3363    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3364        synchronized (mPackages) {
3365            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3366            if (libraryEntry == null) {
3367                throw new IllegalStateException("Missing required shared library:" + name);
3368            }
3369            return libraryEntry.apk;
3370        }
3371    }
3372
3373    private @NonNull String getRequiredInstallerLPr() {
3374        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3375        intent.addCategory(Intent.CATEGORY_DEFAULT);
3376        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3377
3378        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3379                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3380                UserHandle.USER_SYSTEM);
3381        if (matches.size() == 1) {
3382            ResolveInfo resolveInfo = matches.get(0);
3383            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3384                throw new RuntimeException("The installer must be a privileged app");
3385            }
3386            return matches.get(0).getComponentInfo().packageName;
3387        } else {
3388            throw new RuntimeException("There must be exactly one installer; found " + matches);
3389        }
3390    }
3391
3392    private @NonNull String getRequiredUninstallerLPr() {
3393        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3394        intent.addCategory(Intent.CATEGORY_DEFAULT);
3395        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3396
3397        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3398                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3399                UserHandle.USER_SYSTEM);
3400        if (resolveInfo == null ||
3401                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3402            throw new RuntimeException("There must be exactly one uninstaller; found "
3403                    + resolveInfo);
3404        }
3405        return resolveInfo.getComponentInfo().packageName;
3406    }
3407
3408    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3409        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3410
3411        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3412                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3413                UserHandle.USER_SYSTEM);
3414        ResolveInfo best = null;
3415        final int N = matches.size();
3416        for (int i = 0; i < N; i++) {
3417            final ResolveInfo cur = matches.get(i);
3418            final String packageName = cur.getComponentInfo().packageName;
3419            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3420                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3421                continue;
3422            }
3423
3424            if (best == null || cur.priority > best.priority) {
3425                best = cur;
3426            }
3427        }
3428
3429        if (best != null) {
3430            return best.getComponentInfo().getComponentName();
3431        }
3432        Slog.w(TAG, "Intent filter verifier not found");
3433        return null;
3434    }
3435
3436    @Override
3437    public @Nullable ComponentName getInstantAppResolverComponent() {
3438        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3439            return null;
3440        }
3441        synchronized (mPackages) {
3442            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3443            if (instantAppResolver == null) {
3444                return null;
3445            }
3446            return instantAppResolver.first;
3447        }
3448    }
3449
3450    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3451        final String[] packageArray =
3452                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3453        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3454            if (DEBUG_EPHEMERAL) {
3455                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3456            }
3457            return null;
3458        }
3459
3460        final int callingUid = Binder.getCallingUid();
3461        final int resolveFlags =
3462                MATCH_DIRECT_BOOT_AWARE
3463                | MATCH_DIRECT_BOOT_UNAWARE
3464                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3465        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3466        final Intent resolverIntent = new Intent(actionName);
3467        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3468                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3469        // temporarily look for the old action
3470        if (resolvers.size() == 0) {
3471            if (DEBUG_EPHEMERAL) {
3472                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3473            }
3474            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3475            resolverIntent.setAction(actionName);
3476            resolvers = queryIntentServicesInternal(resolverIntent, null,
3477                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3478        }
3479        final int N = resolvers.size();
3480        if (N == 0) {
3481            if (DEBUG_EPHEMERAL) {
3482                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3483            }
3484            return null;
3485        }
3486
3487        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3488        for (int i = 0; i < N; i++) {
3489            final ResolveInfo info = resolvers.get(i);
3490
3491            if (info.serviceInfo == null) {
3492                continue;
3493            }
3494
3495            final String packageName = info.serviceInfo.packageName;
3496            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3497                if (DEBUG_EPHEMERAL) {
3498                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3499                            + " pkg: " + packageName + ", info:" + info);
3500                }
3501                continue;
3502            }
3503
3504            if (DEBUG_EPHEMERAL) {
3505                Slog.v(TAG, "Ephemeral resolver found;"
3506                        + " pkg: " + packageName + ", info:" + info);
3507            }
3508            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3509        }
3510        if (DEBUG_EPHEMERAL) {
3511            Slog.v(TAG, "Ephemeral resolver NOT found");
3512        }
3513        return null;
3514    }
3515
3516    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3517        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3518        intent.addCategory(Intent.CATEGORY_DEFAULT);
3519        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3520
3521        final int resolveFlags =
3522                MATCH_DIRECT_BOOT_AWARE
3523                | MATCH_DIRECT_BOOT_UNAWARE
3524                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3525        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3526                resolveFlags, UserHandle.USER_SYSTEM);
3527        // temporarily look for the old action
3528        if (matches.isEmpty()) {
3529            if (DEBUG_EPHEMERAL) {
3530                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3531            }
3532            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3533            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3534                    resolveFlags, UserHandle.USER_SYSTEM);
3535        }
3536        Iterator<ResolveInfo> iter = matches.iterator();
3537        while (iter.hasNext()) {
3538            final ResolveInfo rInfo = iter.next();
3539            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3540            if (ps != null) {
3541                final PermissionsState permissionsState = ps.getPermissionsState();
3542                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3543                    continue;
3544                }
3545            }
3546            iter.remove();
3547        }
3548        if (matches.size() == 0) {
3549            return null;
3550        } else if (matches.size() == 1) {
3551            return (ActivityInfo) matches.get(0).getComponentInfo();
3552        } else {
3553            throw new RuntimeException(
3554                    "There must be at most one ephemeral installer; found " + matches);
3555        }
3556    }
3557
3558    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3559            @NonNull ComponentName resolver) {
3560        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3561                .addCategory(Intent.CATEGORY_DEFAULT)
3562                .setPackage(resolver.getPackageName());
3563        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3564        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3565                UserHandle.USER_SYSTEM);
3566        // temporarily look for the old action
3567        if (matches.isEmpty()) {
3568            if (DEBUG_EPHEMERAL) {
3569                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3570            }
3571            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3572            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3573                    UserHandle.USER_SYSTEM);
3574        }
3575        if (matches.isEmpty()) {
3576            return null;
3577        }
3578        return matches.get(0).getComponentInfo().getComponentName();
3579    }
3580
3581    private void primeDomainVerificationsLPw(int userId) {
3582        if (DEBUG_DOMAIN_VERIFICATION) {
3583            Slog.d(TAG, "Priming domain verifications in user " + userId);
3584        }
3585
3586        SystemConfig systemConfig = SystemConfig.getInstance();
3587        ArraySet<String> packages = systemConfig.getLinkedApps();
3588
3589        for (String packageName : packages) {
3590            PackageParser.Package pkg = mPackages.get(packageName);
3591            if (pkg != null) {
3592                if (!pkg.isSystemApp()) {
3593                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3594                    continue;
3595                }
3596
3597                ArraySet<String> domains = null;
3598                for (PackageParser.Activity a : pkg.activities) {
3599                    for (ActivityIntentInfo filter : a.intents) {
3600                        if (hasValidDomains(filter)) {
3601                            if (domains == null) {
3602                                domains = new ArraySet<String>();
3603                            }
3604                            domains.addAll(filter.getHostsList());
3605                        }
3606                    }
3607                }
3608
3609                if (domains != null && domains.size() > 0) {
3610                    if (DEBUG_DOMAIN_VERIFICATION) {
3611                        Slog.v(TAG, "      + " + packageName);
3612                    }
3613                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3614                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3615                    // and then 'always' in the per-user state actually used for intent resolution.
3616                    final IntentFilterVerificationInfo ivi;
3617                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3618                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3619                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3620                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3621                } else {
3622                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3623                            + "' does not handle web links");
3624                }
3625            } else {
3626                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3627            }
3628        }
3629
3630        scheduleWritePackageRestrictionsLocked(userId);
3631        scheduleWriteSettingsLocked();
3632    }
3633
3634    private void applyFactoryDefaultBrowserLPw(int userId) {
3635        // The default browser app's package name is stored in a string resource,
3636        // with a product-specific overlay used for vendor customization.
3637        String browserPkg = mContext.getResources().getString(
3638                com.android.internal.R.string.default_browser);
3639        if (!TextUtils.isEmpty(browserPkg)) {
3640            // non-empty string => required to be a known package
3641            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3642            if (ps == null) {
3643                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3644                browserPkg = null;
3645            } else {
3646                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3647            }
3648        }
3649
3650        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3651        // default.  If there's more than one, just leave everything alone.
3652        if (browserPkg == null) {
3653            calculateDefaultBrowserLPw(userId);
3654        }
3655    }
3656
3657    private void calculateDefaultBrowserLPw(int userId) {
3658        List<String> allBrowsers = resolveAllBrowserApps(userId);
3659        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3660        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3661    }
3662
3663    private List<String> resolveAllBrowserApps(int userId) {
3664        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3665        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3666                PackageManager.MATCH_ALL, userId);
3667
3668        final int count = list.size();
3669        List<String> result = new ArrayList<String>(count);
3670        for (int i=0; i<count; i++) {
3671            ResolveInfo info = list.get(i);
3672            if (info.activityInfo == null
3673                    || !info.handleAllWebDataURI
3674                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3675                    || result.contains(info.activityInfo.packageName)) {
3676                continue;
3677            }
3678            result.add(info.activityInfo.packageName);
3679        }
3680
3681        return result;
3682    }
3683
3684    private boolean packageIsBrowser(String packageName, int userId) {
3685        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3686                PackageManager.MATCH_ALL, userId);
3687        final int N = list.size();
3688        for (int i = 0; i < N; i++) {
3689            ResolveInfo info = list.get(i);
3690            if (packageName.equals(info.activityInfo.packageName)) {
3691                return true;
3692            }
3693        }
3694        return false;
3695    }
3696
3697    private void checkDefaultBrowser() {
3698        final int myUserId = UserHandle.myUserId();
3699        final String packageName = getDefaultBrowserPackageName(myUserId);
3700        if (packageName != null) {
3701            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3702            if (info == null) {
3703                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3704                synchronized (mPackages) {
3705                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3706                }
3707            }
3708        }
3709    }
3710
3711    @Override
3712    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3713            throws RemoteException {
3714        try {
3715            return super.onTransact(code, data, reply, flags);
3716        } catch (RuntimeException e) {
3717            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3718                Slog.wtf(TAG, "Package Manager Crash", e);
3719            }
3720            throw e;
3721        }
3722    }
3723
3724    static int[] appendInts(int[] cur, int[] add) {
3725        if (add == null) return cur;
3726        if (cur == null) return add;
3727        final int N = add.length;
3728        for (int i=0; i<N; i++) {
3729            cur = appendInt(cur, add[i]);
3730        }
3731        return cur;
3732    }
3733
3734    /**
3735     * Returns whether or not a full application can see an instant application.
3736     * <p>
3737     * Currently, there are three cases in which this can occur:
3738     * <ol>
3739     * <li>The calling application is a "special" process. The special
3740     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3741     *     and {@code 0}</li>
3742     * <li>The calling application has the permission
3743     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3744     * <li>The calling application is the default launcher on the
3745     *     system partition.</li>
3746     * </ol>
3747     */
3748    private boolean canViewInstantApps(int callingUid, int userId) {
3749        if (callingUid == Process.SYSTEM_UID
3750                || callingUid == Process.SHELL_UID
3751                || callingUid == Process.ROOT_UID) {
3752            return true;
3753        }
3754        if (mContext.checkCallingOrSelfPermission(
3755                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3756            return true;
3757        }
3758        if (mContext.checkCallingOrSelfPermission(
3759                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3760            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3761            if (homeComponent != null
3762                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3763                return true;
3764            }
3765        }
3766        return false;
3767    }
3768
3769    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3770        if (!sUserManager.exists(userId)) return null;
3771        if (ps == null) {
3772            return null;
3773        }
3774        PackageParser.Package p = ps.pkg;
3775        if (p == null) {
3776            return null;
3777        }
3778        final int callingUid = Binder.getCallingUid();
3779        // Filter out ephemeral app metadata:
3780        //   * The system/shell/root can see metadata for any app
3781        //   * An installed app can see metadata for 1) other installed apps
3782        //     and 2) ephemeral apps that have explicitly interacted with it
3783        //   * Ephemeral apps can only see their own data and exposed installed apps
3784        //   * Holding a signature permission allows seeing instant apps
3785        if (filterAppAccessLPr(ps, callingUid, userId)) {
3786            return null;
3787        }
3788
3789        final PermissionsState permissionsState = ps.getPermissionsState();
3790
3791        // Compute GIDs only if requested
3792        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3793                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3794        // Compute granted permissions only if package has requested permissions
3795        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3796                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3797        final PackageUserState state = ps.readUserState(userId);
3798
3799        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3800                && ps.isSystem()) {
3801            flags |= MATCH_ANY_USER;
3802        }
3803
3804        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3805                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3806
3807        if (packageInfo == null) {
3808            return null;
3809        }
3810
3811        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3812                resolveExternalPackageNameLPr(p);
3813
3814        return packageInfo;
3815    }
3816
3817    @Override
3818    public void checkPackageStartable(String packageName, int userId) {
3819        final int callingUid = Binder.getCallingUid();
3820        if (getInstantAppPackageName(callingUid) != null) {
3821            throw new SecurityException("Instant applications don't have access to this method");
3822        }
3823        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3824        synchronized (mPackages) {
3825            final PackageSetting ps = mSettings.mPackages.get(packageName);
3826            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3827                throw new SecurityException("Package " + packageName + " was not found!");
3828            }
3829
3830            if (!ps.getInstalled(userId)) {
3831                throw new SecurityException(
3832                        "Package " + packageName + " was not installed for user " + userId + "!");
3833            }
3834
3835            if (mSafeMode && !ps.isSystem()) {
3836                throw new SecurityException("Package " + packageName + " not a system app!");
3837            }
3838
3839            if (mFrozenPackages.contains(packageName)) {
3840                throw new SecurityException("Package " + packageName + " is currently frozen!");
3841            }
3842
3843            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3844                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3845                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3846            }
3847        }
3848    }
3849
3850    @Override
3851    public boolean isPackageAvailable(String packageName, int userId) {
3852        if (!sUserManager.exists(userId)) return false;
3853        final int callingUid = Binder.getCallingUid();
3854        enforceCrossUserPermission(callingUid, userId,
3855                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3856        synchronized (mPackages) {
3857            PackageParser.Package p = mPackages.get(packageName);
3858            if (p != null) {
3859                final PackageSetting ps = (PackageSetting) p.mExtras;
3860                if (filterAppAccessLPr(ps, callingUid, userId)) {
3861                    return false;
3862                }
3863                if (ps != null) {
3864                    final PackageUserState state = ps.readUserState(userId);
3865                    if (state != null) {
3866                        return PackageParser.isAvailable(state);
3867                    }
3868                }
3869            }
3870        }
3871        return false;
3872    }
3873
3874    @Override
3875    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3876        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3877                flags, Binder.getCallingUid(), userId);
3878    }
3879
3880    @Override
3881    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3882            int flags, int userId) {
3883        return getPackageInfoInternal(versionedPackage.getPackageName(),
3884                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3885    }
3886
3887    /**
3888     * Important: The provided filterCallingUid is used exclusively to filter out packages
3889     * that can be seen based on user state. It's typically the original caller uid prior
3890     * to clearing. Because it can only be provided by trusted code, it's value can be
3891     * trusted and will be used as-is; unlike userId which will be validated by this method.
3892     */
3893    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3894            int flags, int filterCallingUid, int userId) {
3895        if (!sUserManager.exists(userId)) return null;
3896        flags = updateFlagsForPackage(flags, userId, packageName);
3897        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3898                false /* requireFullPermission */, false /* checkShell */, "get package info");
3899
3900        // reader
3901        synchronized (mPackages) {
3902            // Normalize package name to handle renamed packages and static libs
3903            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3904
3905            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3906            if (matchFactoryOnly) {
3907                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3908                if (ps != null) {
3909                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3910                        return null;
3911                    }
3912                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3913                        return null;
3914                    }
3915                    return generatePackageInfo(ps, flags, userId);
3916                }
3917            }
3918
3919            PackageParser.Package p = mPackages.get(packageName);
3920            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3921                return null;
3922            }
3923            if (DEBUG_PACKAGE_INFO)
3924                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3925            if (p != null) {
3926                final PackageSetting ps = (PackageSetting) p.mExtras;
3927                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3928                    return null;
3929                }
3930                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3931                    return null;
3932                }
3933                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3934            }
3935            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3936                final PackageSetting ps = mSettings.mPackages.get(packageName);
3937                if (ps == null) return null;
3938                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3939                    return null;
3940                }
3941                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3942                    return null;
3943                }
3944                return generatePackageInfo(ps, flags, userId);
3945            }
3946        }
3947        return null;
3948    }
3949
3950    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3951        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3952            return true;
3953        }
3954        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3955            return true;
3956        }
3957        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3958            return true;
3959        }
3960        return false;
3961    }
3962
3963    private boolean isComponentVisibleToInstantApp(
3964            @Nullable ComponentName component, @ComponentType int type) {
3965        if (type == TYPE_ACTIVITY) {
3966            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3967            return activity != null
3968                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3969                    : false;
3970        } else if (type == TYPE_RECEIVER) {
3971            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3972            return activity != null
3973                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3974                    : false;
3975        } else if (type == TYPE_SERVICE) {
3976            final PackageParser.Service service = mServices.mServices.get(component);
3977            return service != null
3978                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3979                    : false;
3980        } else if (type == TYPE_PROVIDER) {
3981            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3982            return provider != null
3983                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3984                    : false;
3985        } else if (type == TYPE_UNKNOWN) {
3986            return isComponentVisibleToInstantApp(component);
3987        }
3988        return false;
3989    }
3990
3991    /**
3992     * Returns whether or not access to the application should be filtered.
3993     * <p>
3994     * Access may be limited based upon whether the calling or target applications
3995     * are instant applications.
3996     *
3997     * @see #canAccessInstantApps(int)
3998     */
3999    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4000            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4001        // if we're in an isolated process, get the real calling UID
4002        if (Process.isIsolated(callingUid)) {
4003            callingUid = mIsolatedOwners.get(callingUid);
4004        }
4005        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4006        final boolean callerIsInstantApp = instantAppPkgName != null;
4007        if (ps == null) {
4008            if (callerIsInstantApp) {
4009                // pretend the application exists, but, needs to be filtered
4010                return true;
4011            }
4012            return false;
4013        }
4014        // if the target and caller are the same application, don't filter
4015        if (isCallerSameApp(ps.name, callingUid)) {
4016            return false;
4017        }
4018        if (callerIsInstantApp) {
4019            // request for a specific component; if it hasn't been explicitly exposed, filter
4020            if (component != null) {
4021                return !isComponentVisibleToInstantApp(component, componentType);
4022            }
4023            // request for application; if no components have been explicitly exposed, filter
4024            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4025        }
4026        if (ps.getInstantApp(userId)) {
4027            // caller can see all components of all instant applications, don't filter
4028            if (canViewInstantApps(callingUid, userId)) {
4029                return false;
4030            }
4031            // request for a specific instant application component, filter
4032            if (component != null) {
4033                return true;
4034            }
4035            // request for an instant application; if the caller hasn't been granted access, filter
4036            return !mInstantAppRegistry.isInstantAccessGranted(
4037                    userId, UserHandle.getAppId(callingUid), ps.appId);
4038        }
4039        return false;
4040    }
4041
4042    /**
4043     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4044     */
4045    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4046        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4047    }
4048
4049    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4050            int flags) {
4051        // Callers can access only the libs they depend on, otherwise they need to explicitly
4052        // ask for the shared libraries given the caller is allowed to access all static libs.
4053        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4054            // System/shell/root get to see all static libs
4055            final int appId = UserHandle.getAppId(uid);
4056            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4057                    || appId == Process.ROOT_UID) {
4058                return false;
4059            }
4060        }
4061
4062        // No package means no static lib as it is always on internal storage
4063        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4064            return false;
4065        }
4066
4067        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4068                ps.pkg.staticSharedLibVersion);
4069        if (libEntry == null) {
4070            return false;
4071        }
4072
4073        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4074        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4075        if (uidPackageNames == null) {
4076            return true;
4077        }
4078
4079        for (String uidPackageName : uidPackageNames) {
4080            if (ps.name.equals(uidPackageName)) {
4081                return false;
4082            }
4083            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4084            if (uidPs != null) {
4085                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4086                        libEntry.info.getName());
4087                if (index < 0) {
4088                    continue;
4089                }
4090                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4091                    return false;
4092                }
4093            }
4094        }
4095        return true;
4096    }
4097
4098    @Override
4099    public String[] currentToCanonicalPackageNames(String[] names) {
4100        final int callingUid = Binder.getCallingUid();
4101        if (getInstantAppPackageName(callingUid) != null) {
4102            return names;
4103        }
4104        final String[] out = new String[names.length];
4105        // reader
4106        synchronized (mPackages) {
4107            final int callingUserId = UserHandle.getUserId(callingUid);
4108            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4109            for (int i=names.length-1; i>=0; i--) {
4110                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4111                boolean translateName = false;
4112                if (ps != null && ps.realName != null) {
4113                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4114                    translateName = !targetIsInstantApp
4115                            || canViewInstantApps
4116                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4117                                    UserHandle.getAppId(callingUid), ps.appId);
4118                }
4119                out[i] = translateName ? ps.realName : names[i];
4120            }
4121        }
4122        return out;
4123    }
4124
4125    @Override
4126    public String[] canonicalToCurrentPackageNames(String[] names) {
4127        final int callingUid = Binder.getCallingUid();
4128        if (getInstantAppPackageName(callingUid) != null) {
4129            return names;
4130        }
4131        final String[] out = new String[names.length];
4132        // reader
4133        synchronized (mPackages) {
4134            final int callingUserId = UserHandle.getUserId(callingUid);
4135            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4136            for (int i=names.length-1; i>=0; i--) {
4137                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4138                boolean translateName = false;
4139                if (cur != null) {
4140                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4141                    final boolean targetIsInstantApp =
4142                            ps != null && ps.getInstantApp(callingUserId);
4143                    translateName = !targetIsInstantApp
4144                            || canViewInstantApps
4145                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4146                                    UserHandle.getAppId(callingUid), ps.appId);
4147                }
4148                out[i] = translateName ? cur : names[i];
4149            }
4150        }
4151        return out;
4152    }
4153
4154    @Override
4155    public int getPackageUid(String packageName, int flags, int userId) {
4156        if (!sUserManager.exists(userId)) return -1;
4157        final int callingUid = Binder.getCallingUid();
4158        flags = updateFlagsForPackage(flags, userId, packageName);
4159        enforceCrossUserPermission(callingUid, userId,
4160                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4161
4162        // reader
4163        synchronized (mPackages) {
4164            final PackageParser.Package p = mPackages.get(packageName);
4165            if (p != null && p.isMatch(flags)) {
4166                PackageSetting ps = (PackageSetting) p.mExtras;
4167                if (filterAppAccessLPr(ps, callingUid, userId)) {
4168                    return -1;
4169                }
4170                return UserHandle.getUid(userId, p.applicationInfo.uid);
4171            }
4172            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4173                final PackageSetting ps = mSettings.mPackages.get(packageName);
4174                if (ps != null && ps.isMatch(flags)
4175                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4176                    return UserHandle.getUid(userId, ps.appId);
4177                }
4178            }
4179        }
4180
4181        return -1;
4182    }
4183
4184    @Override
4185    public int[] getPackageGids(String packageName, int flags, int userId) {
4186        if (!sUserManager.exists(userId)) return null;
4187        final int callingUid = Binder.getCallingUid();
4188        flags = updateFlagsForPackage(flags, userId, packageName);
4189        enforceCrossUserPermission(callingUid, userId,
4190                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4191
4192        // reader
4193        synchronized (mPackages) {
4194            final PackageParser.Package p = mPackages.get(packageName);
4195            if (p != null && p.isMatch(flags)) {
4196                PackageSetting ps = (PackageSetting) p.mExtras;
4197                if (filterAppAccessLPr(ps, callingUid, userId)) {
4198                    return null;
4199                }
4200                // TODO: Shouldn't this be checking for package installed state for userId and
4201                // return null?
4202                return ps.getPermissionsState().computeGids(userId);
4203            }
4204            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4205                final PackageSetting ps = mSettings.mPackages.get(packageName);
4206                if (ps != null && ps.isMatch(flags)
4207                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4208                    return ps.getPermissionsState().computeGids(userId);
4209                }
4210            }
4211        }
4212
4213        return null;
4214    }
4215
4216    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4217        if (bp.perm != null) {
4218            return PackageParser.generatePermissionInfo(bp.perm, flags);
4219        }
4220        PermissionInfo pi = new PermissionInfo();
4221        pi.name = bp.name;
4222        pi.packageName = bp.sourcePackage;
4223        pi.nonLocalizedLabel = bp.name;
4224        pi.protectionLevel = bp.protectionLevel;
4225        return pi;
4226    }
4227
4228    @Override
4229    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4230        final int callingUid = Binder.getCallingUid();
4231        if (getInstantAppPackageName(callingUid) != null) {
4232            return null;
4233        }
4234        // reader
4235        synchronized (mPackages) {
4236            final BasePermission p = mSettings.mPermissions.get(name);
4237            if (p == null) {
4238                return null;
4239            }
4240            // If the caller is an app that targets pre 26 SDK drop protection flags.
4241            final PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4242            if (permissionInfo != null) {
4243                permissionInfo.protectionLevel = adjustPermissionProtectionFlagsLPr(
4244                        permissionInfo.protectionLevel, packageName, callingUid);
4245            }
4246            return permissionInfo;
4247        }
4248    }
4249
4250    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4251            String packageName, int uid) {
4252        // Signature permission flags area always reported
4253        final int protectionLevelMasked = protectionLevel
4254                & (PermissionInfo.PROTECTION_NORMAL
4255                | PermissionInfo.PROTECTION_DANGEROUS
4256                | PermissionInfo.PROTECTION_SIGNATURE);
4257        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4258            return protectionLevel;
4259        }
4260
4261        // System sees all flags.
4262        final int appId = UserHandle.getAppId(uid);
4263        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4264                || appId == Process.SHELL_UID) {
4265            return protectionLevel;
4266        }
4267
4268        // Normalize package name to handle renamed packages and static libs
4269        packageName = resolveInternalPackageNameLPr(packageName,
4270                PackageManager.VERSION_CODE_HIGHEST);
4271
4272        // Apps that target O see flags for all protection levels.
4273        final PackageSetting ps = mSettings.mPackages.get(packageName);
4274        if (ps == null) {
4275            return protectionLevel;
4276        }
4277        if (ps.appId != appId) {
4278            return protectionLevel;
4279        }
4280
4281        final PackageParser.Package pkg = mPackages.get(packageName);
4282        if (pkg == null) {
4283            return protectionLevel;
4284        }
4285        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4286            return protectionLevelMasked;
4287        }
4288
4289        return protectionLevel;
4290    }
4291
4292    @Override
4293    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4294            int flags) {
4295        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4296            return null;
4297        }
4298        // reader
4299        synchronized (mPackages) {
4300            if (group != null && !mPermissionGroups.containsKey(group)) {
4301                // This is thrown as NameNotFoundException
4302                return null;
4303            }
4304
4305            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4306            for (BasePermission p : mSettings.mPermissions.values()) {
4307                if (group == null) {
4308                    if (p.perm == null || p.perm.info.group == null) {
4309                        out.add(generatePermissionInfo(p, flags));
4310                    }
4311                } else {
4312                    if (p.perm != null && group.equals(p.perm.info.group)) {
4313                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4314                    }
4315                }
4316            }
4317            return new ParceledListSlice<>(out);
4318        }
4319    }
4320
4321    @Override
4322    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4323        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4324            return null;
4325        }
4326        // reader
4327        synchronized (mPackages) {
4328            return PackageParser.generatePermissionGroupInfo(
4329                    mPermissionGroups.get(name), flags);
4330        }
4331    }
4332
4333    @Override
4334    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4335        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4336            return ParceledListSlice.emptyList();
4337        }
4338        // reader
4339        synchronized (mPackages) {
4340            final int N = mPermissionGroups.size();
4341            ArrayList<PermissionGroupInfo> out
4342                    = new ArrayList<PermissionGroupInfo>(N);
4343            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4344                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4345            }
4346            return new ParceledListSlice<>(out);
4347        }
4348    }
4349
4350    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4351            int filterCallingUid, int userId) {
4352        if (!sUserManager.exists(userId)) return null;
4353        PackageSetting ps = mSettings.mPackages.get(packageName);
4354        if (ps != null) {
4355            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4356                return null;
4357            }
4358            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4359                return null;
4360            }
4361            if (ps.pkg == null) {
4362                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4363                if (pInfo != null) {
4364                    return pInfo.applicationInfo;
4365                }
4366                return null;
4367            }
4368            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4369                    ps.readUserState(userId), userId);
4370            if (ai != null) {
4371                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4372            }
4373            return ai;
4374        }
4375        return null;
4376    }
4377
4378    @Override
4379    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4380        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4381    }
4382
4383    /**
4384     * Important: The provided filterCallingUid is used exclusively to filter out applications
4385     * that can be seen based on user state. It's typically the original caller uid prior
4386     * to clearing. Because it can only be provided by trusted code, it's value can be
4387     * trusted and will be used as-is; unlike userId which will be validated by this method.
4388     */
4389    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4390            int filterCallingUid, int userId) {
4391        if (!sUserManager.exists(userId)) return null;
4392        flags = updateFlagsForApplication(flags, userId, packageName);
4393        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4394                false /* requireFullPermission */, false /* checkShell */, "get application info");
4395
4396        // writer
4397        synchronized (mPackages) {
4398            // Normalize package name to handle renamed packages and static libs
4399            packageName = resolveInternalPackageNameLPr(packageName,
4400                    PackageManager.VERSION_CODE_HIGHEST);
4401
4402            PackageParser.Package p = mPackages.get(packageName);
4403            if (DEBUG_PACKAGE_INFO) Log.v(
4404                    TAG, "getApplicationInfo " + packageName
4405                    + ": " + p);
4406            if (p != null) {
4407                PackageSetting ps = mSettings.mPackages.get(packageName);
4408                if (ps == null) return null;
4409                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4410                    return null;
4411                }
4412                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4413                    return null;
4414                }
4415                // Note: isEnabledLP() does not apply here - always return info
4416                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4417                        p, flags, ps.readUserState(userId), userId);
4418                if (ai != null) {
4419                    ai.packageName = resolveExternalPackageNameLPr(p);
4420                }
4421                return ai;
4422            }
4423            if ("android".equals(packageName)||"system".equals(packageName)) {
4424                return mAndroidApplication;
4425            }
4426            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4427                // Already generates the external package name
4428                return generateApplicationInfoFromSettingsLPw(packageName,
4429                        flags, filterCallingUid, userId);
4430            }
4431        }
4432        return null;
4433    }
4434
4435    private String normalizePackageNameLPr(String packageName) {
4436        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4437        return normalizedPackageName != null ? normalizedPackageName : packageName;
4438    }
4439
4440    @Override
4441    public void deletePreloadsFileCache() {
4442        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4443            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4444        }
4445        File dir = Environment.getDataPreloadsFileCacheDirectory();
4446        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4447        FileUtils.deleteContents(dir);
4448    }
4449
4450    @Override
4451    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4452            final int storageFlags, final IPackageDataObserver observer) {
4453        mContext.enforceCallingOrSelfPermission(
4454                android.Manifest.permission.CLEAR_APP_CACHE, null);
4455        mHandler.post(() -> {
4456            boolean success = false;
4457            try {
4458                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4459                success = true;
4460            } catch (IOException e) {
4461                Slog.w(TAG, e);
4462            }
4463            if (observer != null) {
4464                try {
4465                    observer.onRemoveCompleted(null, success);
4466                } catch (RemoteException e) {
4467                    Slog.w(TAG, e);
4468                }
4469            }
4470        });
4471    }
4472
4473    @Override
4474    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4475            final int storageFlags, final IntentSender pi) {
4476        mContext.enforceCallingOrSelfPermission(
4477                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4478        mHandler.post(() -> {
4479            boolean success = false;
4480            try {
4481                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4482                success = true;
4483            } catch (IOException e) {
4484                Slog.w(TAG, e);
4485            }
4486            if (pi != null) {
4487                try {
4488                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4489                } catch (SendIntentException e) {
4490                    Slog.w(TAG, e);
4491                }
4492            }
4493        });
4494    }
4495
4496    /**
4497     * Blocking call to clear various types of cached data across the system
4498     * until the requested bytes are available.
4499     */
4500    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4501        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4502        final File file = storage.findPathForUuid(volumeUuid);
4503        if (file.getUsableSpace() >= bytes) return;
4504
4505        if (ENABLE_FREE_CACHE_V2) {
4506            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4507                    volumeUuid);
4508            final boolean aggressive = (storageFlags
4509                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4510            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4511
4512            // 1. Pre-flight to determine if we have any chance to succeed
4513            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4514            if (internalVolume && (aggressive || SystemProperties
4515                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4516                deletePreloadsFileCache();
4517                if (file.getUsableSpace() >= bytes) return;
4518            }
4519
4520            // 3. Consider parsed APK data (aggressive only)
4521            if (internalVolume && aggressive) {
4522                FileUtils.deleteContents(mCacheDir);
4523                if (file.getUsableSpace() >= bytes) return;
4524            }
4525
4526            // 4. Consider cached app data (above quotas)
4527            try {
4528                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4529                        Installer.FLAG_FREE_CACHE_V2);
4530            } catch (InstallerException ignored) {
4531            }
4532            if (file.getUsableSpace() >= bytes) return;
4533
4534            // 5. Consider shared libraries with refcount=0 and age>min cache period
4535            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4536                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4537                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4538                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4539                return;
4540            }
4541
4542            // 6. Consider dexopt output (aggressive only)
4543            // TODO: Implement
4544
4545            // 7. Consider installed instant apps unused longer than min cache period
4546            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4547                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4548                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4549                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4550                return;
4551            }
4552
4553            // 8. Consider cached app data (below quotas)
4554            try {
4555                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4556                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4557            } catch (InstallerException ignored) {
4558            }
4559            if (file.getUsableSpace() >= bytes) return;
4560
4561            // 9. Consider DropBox entries
4562            // TODO: Implement
4563
4564            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4565            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4566                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4567                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4568                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4569                return;
4570            }
4571        } else {
4572            try {
4573                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4574            } catch (InstallerException ignored) {
4575            }
4576            if (file.getUsableSpace() >= bytes) return;
4577        }
4578
4579        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4580    }
4581
4582    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4583            throws IOException {
4584        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4585        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4586
4587        List<VersionedPackage> packagesToDelete = null;
4588        final long now = System.currentTimeMillis();
4589
4590        synchronized (mPackages) {
4591            final int[] allUsers = sUserManager.getUserIds();
4592            final int libCount = mSharedLibraries.size();
4593            for (int i = 0; i < libCount; i++) {
4594                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4595                if (versionedLib == null) {
4596                    continue;
4597                }
4598                final int versionCount = versionedLib.size();
4599                for (int j = 0; j < versionCount; j++) {
4600                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4601                    // Skip packages that are not static shared libs.
4602                    if (!libInfo.isStatic()) {
4603                        break;
4604                    }
4605                    // Important: We skip static shared libs used for some user since
4606                    // in such a case we need to keep the APK on the device. The check for
4607                    // a lib being used for any user is performed by the uninstall call.
4608                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4609                    // Resolve the package name - we use synthetic package names internally
4610                    final String internalPackageName = resolveInternalPackageNameLPr(
4611                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4612                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4613                    // Skip unused static shared libs cached less than the min period
4614                    // to prevent pruning a lib needed by a subsequently installed package.
4615                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4616                        continue;
4617                    }
4618                    if (packagesToDelete == null) {
4619                        packagesToDelete = new ArrayList<>();
4620                    }
4621                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4622                            declaringPackage.getVersionCode()));
4623                }
4624            }
4625        }
4626
4627        if (packagesToDelete != null) {
4628            final int packageCount = packagesToDelete.size();
4629            for (int i = 0; i < packageCount; i++) {
4630                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4631                // Delete the package synchronously (will fail of the lib used for any user).
4632                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4633                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4634                                == PackageManager.DELETE_SUCCEEDED) {
4635                    if (volume.getUsableSpace() >= neededSpace) {
4636                        return true;
4637                    }
4638                }
4639            }
4640        }
4641
4642        return false;
4643    }
4644
4645    /**
4646     * Update given flags based on encryption status of current user.
4647     */
4648    private int updateFlags(int flags, int userId) {
4649        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4650                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4651            // Caller expressed an explicit opinion about what encryption
4652            // aware/unaware components they want to see, so fall through and
4653            // give them what they want
4654        } else {
4655            // Caller expressed no opinion, so match based on user state
4656            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4657                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4658            } else {
4659                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4660            }
4661        }
4662        return flags;
4663    }
4664
4665    private UserManagerInternal getUserManagerInternal() {
4666        if (mUserManagerInternal == null) {
4667            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4668        }
4669        return mUserManagerInternal;
4670    }
4671
4672    private DeviceIdleController.LocalService getDeviceIdleController() {
4673        if (mDeviceIdleController == null) {
4674            mDeviceIdleController =
4675                    LocalServices.getService(DeviceIdleController.LocalService.class);
4676        }
4677        return mDeviceIdleController;
4678    }
4679
4680    /**
4681     * Update given flags when being used to request {@link PackageInfo}.
4682     */
4683    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4684        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4685        boolean triaged = true;
4686        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4687                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4688            // Caller is asking for component details, so they'd better be
4689            // asking for specific encryption matching behavior, or be triaged
4690            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4691                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4692                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4693                triaged = false;
4694            }
4695        }
4696        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4697                | PackageManager.MATCH_SYSTEM_ONLY
4698                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4699            triaged = false;
4700        }
4701        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4702            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4703                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4704                    + Debug.getCallers(5));
4705        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4706                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4707            // If the caller wants all packages and has a restricted profile associated with it,
4708            // then match all users. This is to make sure that launchers that need to access work
4709            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4710            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4711            flags |= PackageManager.MATCH_ANY_USER;
4712        }
4713        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4714            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4715                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4716        }
4717        return updateFlags(flags, userId);
4718    }
4719
4720    /**
4721     * Update given flags when being used to request {@link ApplicationInfo}.
4722     */
4723    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4724        return updateFlagsForPackage(flags, userId, cookie);
4725    }
4726
4727    /**
4728     * Update given flags when being used to request {@link ComponentInfo}.
4729     */
4730    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4731        if (cookie instanceof Intent) {
4732            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4733                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4734            }
4735        }
4736
4737        boolean triaged = true;
4738        // Caller is asking for component details, so they'd better be
4739        // asking for specific encryption matching behavior, or be triaged
4740        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4741                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4742                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4743            triaged = false;
4744        }
4745        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4746            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4747                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4748        }
4749
4750        return updateFlags(flags, userId);
4751    }
4752
4753    /**
4754     * Update given intent when being used to request {@link ResolveInfo}.
4755     */
4756    private Intent updateIntentForResolve(Intent intent) {
4757        if (intent.getSelector() != null) {
4758            intent = intent.getSelector();
4759        }
4760        if (DEBUG_PREFERRED) {
4761            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4762        }
4763        return intent;
4764    }
4765
4766    /**
4767     * Update given flags when being used to request {@link ResolveInfo}.
4768     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4769     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4770     * flag set. However, this flag is only honoured in three circumstances:
4771     * <ul>
4772     * <li>when called from a system process</li>
4773     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4774     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4775     * action and a {@code android.intent.category.BROWSABLE} category</li>
4776     * </ul>
4777     */
4778    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4779        return updateFlagsForResolve(flags, userId, intent, callingUid,
4780                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4781    }
4782    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4783            boolean wantInstantApps) {
4784        return updateFlagsForResolve(flags, userId, intent, callingUid,
4785                wantInstantApps, false /*onlyExposedExplicitly*/);
4786    }
4787    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4788            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4789        // Safe mode means we shouldn't match any third-party components
4790        if (mSafeMode) {
4791            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4792        }
4793        if (getInstantAppPackageName(callingUid) != null) {
4794            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4795            if (onlyExposedExplicitly) {
4796                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4797            }
4798            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4799            flags |= PackageManager.MATCH_INSTANT;
4800        } else {
4801            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4802            final boolean allowMatchInstant =
4803                    (wantInstantApps
4804                            && Intent.ACTION_VIEW.equals(intent.getAction())
4805                            && hasWebURI(intent))
4806                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4807            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4808                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4809            if (!allowMatchInstant) {
4810                flags &= ~PackageManager.MATCH_INSTANT;
4811            }
4812        }
4813        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4814    }
4815
4816    @Override
4817    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4818        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4819    }
4820
4821    /**
4822     * Important: The provided filterCallingUid is used exclusively to filter out activities
4823     * that can be seen based on user state. It's typically the original caller uid prior
4824     * to clearing. Because it can only be provided by trusted code, it's value can be
4825     * trusted and will be used as-is; unlike userId which will be validated by this method.
4826     */
4827    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4828            int filterCallingUid, int userId) {
4829        if (!sUserManager.exists(userId)) return null;
4830        flags = updateFlagsForComponent(flags, userId, component);
4831        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4832                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4833        synchronized (mPackages) {
4834            PackageParser.Activity a = mActivities.mActivities.get(component);
4835
4836            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4837            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4838                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4839                if (ps == null) return null;
4840                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4841                    return null;
4842                }
4843                return PackageParser.generateActivityInfo(
4844                        a, flags, ps.readUserState(userId), userId);
4845            }
4846            if (mResolveComponentName.equals(component)) {
4847                return PackageParser.generateActivityInfo(
4848                        mResolveActivity, flags, new PackageUserState(), userId);
4849            }
4850        }
4851        return null;
4852    }
4853
4854    @Override
4855    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4856            String resolvedType) {
4857        synchronized (mPackages) {
4858            if (component.equals(mResolveComponentName)) {
4859                // The resolver supports EVERYTHING!
4860                return true;
4861            }
4862            final int callingUid = Binder.getCallingUid();
4863            final int callingUserId = UserHandle.getUserId(callingUid);
4864            PackageParser.Activity a = mActivities.mActivities.get(component);
4865            if (a == null) {
4866                return false;
4867            }
4868            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4869            if (ps == null) {
4870                return false;
4871            }
4872            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4873                return false;
4874            }
4875            for (int i=0; i<a.intents.size(); i++) {
4876                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4877                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4878                    return true;
4879                }
4880            }
4881            return false;
4882        }
4883    }
4884
4885    @Override
4886    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4887        if (!sUserManager.exists(userId)) return null;
4888        final int callingUid = Binder.getCallingUid();
4889        flags = updateFlagsForComponent(flags, userId, component);
4890        enforceCrossUserPermission(callingUid, userId,
4891                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4892        synchronized (mPackages) {
4893            PackageParser.Activity a = mReceivers.mActivities.get(component);
4894            if (DEBUG_PACKAGE_INFO) Log.v(
4895                TAG, "getReceiverInfo " + component + ": " + a);
4896            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4897                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4898                if (ps == null) return null;
4899                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4900                    return null;
4901                }
4902                return PackageParser.generateActivityInfo(
4903                        a, flags, ps.readUserState(userId), userId);
4904            }
4905        }
4906        return null;
4907    }
4908
4909    @Override
4910    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4911            int flags, int userId) {
4912        if (!sUserManager.exists(userId)) return null;
4913        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4914        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4915            return null;
4916        }
4917
4918        flags = updateFlagsForPackage(flags, userId, null);
4919
4920        final boolean canSeeStaticLibraries =
4921                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4922                        == PERMISSION_GRANTED
4923                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4924                        == PERMISSION_GRANTED
4925                || canRequestPackageInstallsInternal(packageName,
4926                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4927                        false  /* throwIfPermNotDeclared*/)
4928                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4929                        == PERMISSION_GRANTED;
4930
4931        synchronized (mPackages) {
4932            List<SharedLibraryInfo> result = null;
4933
4934            final int libCount = mSharedLibraries.size();
4935            for (int i = 0; i < libCount; i++) {
4936                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4937                if (versionedLib == null) {
4938                    continue;
4939                }
4940
4941                final int versionCount = versionedLib.size();
4942                for (int j = 0; j < versionCount; j++) {
4943                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4944                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4945                        break;
4946                    }
4947                    final long identity = Binder.clearCallingIdentity();
4948                    try {
4949                        PackageInfo packageInfo = getPackageInfoVersioned(
4950                                libInfo.getDeclaringPackage(), flags
4951                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4952                        if (packageInfo == null) {
4953                            continue;
4954                        }
4955                    } finally {
4956                        Binder.restoreCallingIdentity(identity);
4957                    }
4958
4959                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4960                            libInfo.getVersion(), libInfo.getType(),
4961                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4962                            flags, userId));
4963
4964                    if (result == null) {
4965                        result = new ArrayList<>();
4966                    }
4967                    result.add(resLibInfo);
4968                }
4969            }
4970
4971            return result != null ? new ParceledListSlice<>(result) : null;
4972        }
4973    }
4974
4975    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4976            SharedLibraryInfo libInfo, int flags, int userId) {
4977        List<VersionedPackage> versionedPackages = null;
4978        final int packageCount = mSettings.mPackages.size();
4979        for (int i = 0; i < packageCount; i++) {
4980            PackageSetting ps = mSettings.mPackages.valueAt(i);
4981
4982            if (ps == null) {
4983                continue;
4984            }
4985
4986            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4987                continue;
4988            }
4989
4990            final String libName = libInfo.getName();
4991            if (libInfo.isStatic()) {
4992                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4993                if (libIdx < 0) {
4994                    continue;
4995                }
4996                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4997                    continue;
4998                }
4999                if (versionedPackages == null) {
5000                    versionedPackages = new ArrayList<>();
5001                }
5002                // If the dependent is a static shared lib, use the public package name
5003                String dependentPackageName = ps.name;
5004                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5005                    dependentPackageName = ps.pkg.manifestPackageName;
5006                }
5007                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5008            } else if (ps.pkg != null) {
5009                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5010                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5011                    if (versionedPackages == null) {
5012                        versionedPackages = new ArrayList<>();
5013                    }
5014                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5015                }
5016            }
5017        }
5018
5019        return versionedPackages;
5020    }
5021
5022    @Override
5023    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5024        if (!sUserManager.exists(userId)) return null;
5025        final int callingUid = Binder.getCallingUid();
5026        flags = updateFlagsForComponent(flags, userId, component);
5027        enforceCrossUserPermission(callingUid, userId,
5028                false /* requireFullPermission */, false /* checkShell */, "get service info");
5029        synchronized (mPackages) {
5030            PackageParser.Service s = mServices.mServices.get(component);
5031            if (DEBUG_PACKAGE_INFO) Log.v(
5032                TAG, "getServiceInfo " + component + ": " + s);
5033            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5034                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5035                if (ps == null) return null;
5036                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5037                    return null;
5038                }
5039                return PackageParser.generateServiceInfo(
5040                        s, flags, ps.readUserState(userId), userId);
5041            }
5042        }
5043        return null;
5044    }
5045
5046    @Override
5047    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5048        if (!sUserManager.exists(userId)) return null;
5049        final int callingUid = Binder.getCallingUid();
5050        flags = updateFlagsForComponent(flags, userId, component);
5051        enforceCrossUserPermission(callingUid, userId,
5052                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5053        synchronized (mPackages) {
5054            PackageParser.Provider p = mProviders.mProviders.get(component);
5055            if (DEBUG_PACKAGE_INFO) Log.v(
5056                TAG, "getProviderInfo " + component + ": " + p);
5057            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5058                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5059                if (ps == null) return null;
5060                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5061                    return null;
5062                }
5063                return PackageParser.generateProviderInfo(
5064                        p, flags, ps.readUserState(userId), userId);
5065            }
5066        }
5067        return null;
5068    }
5069
5070    @Override
5071    public String[] getSystemSharedLibraryNames() {
5072        // allow instant applications
5073        synchronized (mPackages) {
5074            Set<String> libs = null;
5075            final int libCount = mSharedLibraries.size();
5076            for (int i = 0; i < libCount; i++) {
5077                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5078                if (versionedLib == null) {
5079                    continue;
5080                }
5081                final int versionCount = versionedLib.size();
5082                for (int j = 0; j < versionCount; j++) {
5083                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5084                    if (!libEntry.info.isStatic()) {
5085                        if (libs == null) {
5086                            libs = new ArraySet<>();
5087                        }
5088                        libs.add(libEntry.info.getName());
5089                        break;
5090                    }
5091                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5092                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5093                            UserHandle.getUserId(Binder.getCallingUid()),
5094                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5095                        if (libs == null) {
5096                            libs = new ArraySet<>();
5097                        }
5098                        libs.add(libEntry.info.getName());
5099                        break;
5100                    }
5101                }
5102            }
5103
5104            if (libs != null) {
5105                String[] libsArray = new String[libs.size()];
5106                libs.toArray(libsArray);
5107                return libsArray;
5108            }
5109
5110            return null;
5111        }
5112    }
5113
5114    @Override
5115    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5116        // allow instant applications
5117        synchronized (mPackages) {
5118            return mServicesSystemSharedLibraryPackageName;
5119        }
5120    }
5121
5122    @Override
5123    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5124        // allow instant applications
5125        synchronized (mPackages) {
5126            return mSharedSystemSharedLibraryPackageName;
5127        }
5128    }
5129
5130    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5131        for (int i = userList.length - 1; i >= 0; --i) {
5132            final int userId = userList[i];
5133            // don't add instant app to the list of updates
5134            if (pkgSetting.getInstantApp(userId)) {
5135                continue;
5136            }
5137            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5138            if (changedPackages == null) {
5139                changedPackages = new SparseArray<>();
5140                mChangedPackages.put(userId, changedPackages);
5141            }
5142            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5143            if (sequenceNumbers == null) {
5144                sequenceNumbers = new HashMap<>();
5145                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5146            }
5147            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5148            if (sequenceNumber != null) {
5149                changedPackages.remove(sequenceNumber);
5150            }
5151            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5152            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5153        }
5154        mChangedPackagesSequenceNumber++;
5155    }
5156
5157    @Override
5158    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5159        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5160            return null;
5161        }
5162        synchronized (mPackages) {
5163            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5164                return null;
5165            }
5166            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5167            if (changedPackages == null) {
5168                return null;
5169            }
5170            final List<String> packageNames =
5171                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5172            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5173                final String packageName = changedPackages.get(i);
5174                if (packageName != null) {
5175                    packageNames.add(packageName);
5176                }
5177            }
5178            return packageNames.isEmpty()
5179                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5180        }
5181    }
5182
5183    @Override
5184    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5185        // allow instant applications
5186        ArrayList<FeatureInfo> res;
5187        synchronized (mAvailableFeatures) {
5188            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5189            res.addAll(mAvailableFeatures.values());
5190        }
5191        final FeatureInfo fi = new FeatureInfo();
5192        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5193                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5194        res.add(fi);
5195
5196        return new ParceledListSlice<>(res);
5197    }
5198
5199    @Override
5200    public boolean hasSystemFeature(String name, int version) {
5201        // allow instant applications
5202        synchronized (mAvailableFeatures) {
5203            final FeatureInfo feat = mAvailableFeatures.get(name);
5204            if (feat == null) {
5205                return false;
5206            } else {
5207                return feat.version >= version;
5208            }
5209        }
5210    }
5211
5212    @Override
5213    public int checkPermission(String permName, String pkgName, int userId) {
5214        if (!sUserManager.exists(userId)) {
5215            return PackageManager.PERMISSION_DENIED;
5216        }
5217        final int callingUid = Binder.getCallingUid();
5218
5219        synchronized (mPackages) {
5220            final PackageParser.Package p = mPackages.get(pkgName);
5221            if (p != null && p.mExtras != null) {
5222                final PackageSetting ps = (PackageSetting) p.mExtras;
5223                if (filterAppAccessLPr(ps, callingUid, userId)) {
5224                    return PackageManager.PERMISSION_DENIED;
5225                }
5226                final boolean instantApp = ps.getInstantApp(userId);
5227                final PermissionsState permissionsState = ps.getPermissionsState();
5228                if (permissionsState.hasPermission(permName, userId)) {
5229                    if (instantApp) {
5230                        BasePermission bp = mSettings.mPermissions.get(permName);
5231                        if (bp != null && bp.isInstant()) {
5232                            return PackageManager.PERMISSION_GRANTED;
5233                        }
5234                    } else {
5235                        return PackageManager.PERMISSION_GRANTED;
5236                    }
5237                }
5238                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5239                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5240                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5241                    return PackageManager.PERMISSION_GRANTED;
5242                }
5243            }
5244        }
5245
5246        return PackageManager.PERMISSION_DENIED;
5247    }
5248
5249    @Override
5250    public int checkUidPermission(String permName, int uid) {
5251        final int callingUid = Binder.getCallingUid();
5252        final int callingUserId = UserHandle.getUserId(callingUid);
5253        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5254        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5255        final int userId = UserHandle.getUserId(uid);
5256        if (!sUserManager.exists(userId)) {
5257            return PackageManager.PERMISSION_DENIED;
5258        }
5259
5260        synchronized (mPackages) {
5261            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5262            if (obj != null) {
5263                if (obj instanceof SharedUserSetting) {
5264                    if (isCallerInstantApp) {
5265                        return PackageManager.PERMISSION_DENIED;
5266                    }
5267                } else if (obj instanceof PackageSetting) {
5268                    final PackageSetting ps = (PackageSetting) obj;
5269                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5270                        return PackageManager.PERMISSION_DENIED;
5271                    }
5272                }
5273                final SettingBase settingBase = (SettingBase) obj;
5274                final PermissionsState permissionsState = settingBase.getPermissionsState();
5275                if (permissionsState.hasPermission(permName, userId)) {
5276                    if (isUidInstantApp) {
5277                        BasePermission bp = mSettings.mPermissions.get(permName);
5278                        if (bp != null && bp.isInstant()) {
5279                            return PackageManager.PERMISSION_GRANTED;
5280                        }
5281                    } else {
5282                        return PackageManager.PERMISSION_GRANTED;
5283                    }
5284                }
5285                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5286                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5287                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5288                    return PackageManager.PERMISSION_GRANTED;
5289                }
5290            } else {
5291                ArraySet<String> perms = mSystemPermissions.get(uid);
5292                if (perms != null) {
5293                    if (perms.contains(permName)) {
5294                        return PackageManager.PERMISSION_GRANTED;
5295                    }
5296                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5297                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5298                        return PackageManager.PERMISSION_GRANTED;
5299                    }
5300                }
5301            }
5302        }
5303
5304        return PackageManager.PERMISSION_DENIED;
5305    }
5306
5307    @Override
5308    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5309        if (UserHandle.getCallingUserId() != userId) {
5310            mContext.enforceCallingPermission(
5311                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5312                    "isPermissionRevokedByPolicy for user " + userId);
5313        }
5314
5315        if (checkPermission(permission, packageName, userId)
5316                == PackageManager.PERMISSION_GRANTED) {
5317            return false;
5318        }
5319
5320        final int callingUid = Binder.getCallingUid();
5321        if (getInstantAppPackageName(callingUid) != null) {
5322            if (!isCallerSameApp(packageName, callingUid)) {
5323                return false;
5324            }
5325        } else {
5326            if (isInstantApp(packageName, userId)) {
5327                return false;
5328            }
5329        }
5330
5331        final long identity = Binder.clearCallingIdentity();
5332        try {
5333            final int flags = getPermissionFlags(permission, packageName, userId);
5334            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5335        } finally {
5336            Binder.restoreCallingIdentity(identity);
5337        }
5338    }
5339
5340    @Override
5341    public String getPermissionControllerPackageName() {
5342        synchronized (mPackages) {
5343            return mRequiredInstallerPackage;
5344        }
5345    }
5346
5347    /**
5348     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5349     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5350     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5351     * @param message the message to log on security exception
5352     */
5353    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5354            boolean checkShell, String message) {
5355        if (userId < 0) {
5356            throw new IllegalArgumentException("Invalid userId " + userId);
5357        }
5358        if (checkShell) {
5359            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5360        }
5361        if (userId == UserHandle.getUserId(callingUid)) return;
5362        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5363            if (requireFullPermission) {
5364                mContext.enforceCallingOrSelfPermission(
5365                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5366            } else {
5367                try {
5368                    mContext.enforceCallingOrSelfPermission(
5369                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5370                } catch (SecurityException se) {
5371                    mContext.enforceCallingOrSelfPermission(
5372                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5373                }
5374            }
5375        }
5376    }
5377
5378    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5379        if (callingUid == Process.SHELL_UID) {
5380            if (userHandle >= 0
5381                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5382                throw new SecurityException("Shell does not have permission to access user "
5383                        + userHandle);
5384            } else if (userHandle < 0) {
5385                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5386                        + Debug.getCallers(3));
5387            }
5388        }
5389    }
5390
5391    private BasePermission findPermissionTreeLP(String permName) {
5392        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5393            if (permName.startsWith(bp.name) &&
5394                    permName.length() > bp.name.length() &&
5395                    permName.charAt(bp.name.length()) == '.') {
5396                return bp;
5397            }
5398        }
5399        return null;
5400    }
5401
5402    private BasePermission checkPermissionTreeLP(String permName) {
5403        if (permName != null) {
5404            BasePermission bp = findPermissionTreeLP(permName);
5405            if (bp != null) {
5406                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5407                    return bp;
5408                }
5409                throw new SecurityException("Calling uid "
5410                        + Binder.getCallingUid()
5411                        + " is not allowed to add to permission tree "
5412                        + bp.name + " owned by uid " + bp.uid);
5413            }
5414        }
5415        throw new SecurityException("No permission tree found for " + permName);
5416    }
5417
5418    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5419        if (s1 == null) {
5420            return s2 == null;
5421        }
5422        if (s2 == null) {
5423            return false;
5424        }
5425        if (s1.getClass() != s2.getClass()) {
5426            return false;
5427        }
5428        return s1.equals(s2);
5429    }
5430
5431    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5432        if (pi1.icon != pi2.icon) return false;
5433        if (pi1.logo != pi2.logo) return false;
5434        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5435        if (!compareStrings(pi1.name, pi2.name)) return false;
5436        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5437        // We'll take care of setting this one.
5438        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5439        // These are not currently stored in settings.
5440        //if (!compareStrings(pi1.group, pi2.group)) return false;
5441        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5442        //if (pi1.labelRes != pi2.labelRes) return false;
5443        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5444        return true;
5445    }
5446
5447    int permissionInfoFootprint(PermissionInfo info) {
5448        int size = info.name.length();
5449        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5450        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5451        return size;
5452    }
5453
5454    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5455        int size = 0;
5456        for (BasePermission perm : mSettings.mPermissions.values()) {
5457            if (perm.uid == tree.uid) {
5458                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5459            }
5460        }
5461        return size;
5462    }
5463
5464    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5465        // We calculate the max size of permissions defined by this uid and throw
5466        // if that plus the size of 'info' would exceed our stated maximum.
5467        if (tree.uid != Process.SYSTEM_UID) {
5468            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5469            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5470                throw new SecurityException("Permission tree size cap exceeded");
5471            }
5472        }
5473    }
5474
5475    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5476        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5477            throw new SecurityException("Instant apps can't add permissions");
5478        }
5479        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5480            throw new SecurityException("Label must be specified in permission");
5481        }
5482        BasePermission tree = checkPermissionTreeLP(info.name);
5483        BasePermission bp = mSettings.mPermissions.get(info.name);
5484        boolean added = bp == null;
5485        boolean changed = true;
5486        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5487        if (added) {
5488            enforcePermissionCapLocked(info, tree);
5489            bp = new BasePermission(info.name, tree.sourcePackage,
5490                    BasePermission.TYPE_DYNAMIC);
5491        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5492            throw new SecurityException(
5493                    "Not allowed to modify non-dynamic permission "
5494                    + info.name);
5495        } else {
5496            if (bp.protectionLevel == fixedLevel
5497                    && bp.perm.owner.equals(tree.perm.owner)
5498                    && bp.uid == tree.uid
5499                    && comparePermissionInfos(bp.perm.info, info)) {
5500                changed = false;
5501            }
5502        }
5503        bp.protectionLevel = fixedLevel;
5504        info = new PermissionInfo(info);
5505        info.protectionLevel = fixedLevel;
5506        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5507        bp.perm.info.packageName = tree.perm.info.packageName;
5508        bp.uid = tree.uid;
5509        if (added) {
5510            mSettings.mPermissions.put(info.name, bp);
5511        }
5512        if (changed) {
5513            if (!async) {
5514                mSettings.writeLPr();
5515            } else {
5516                scheduleWriteSettingsLocked();
5517            }
5518        }
5519        return added;
5520    }
5521
5522    @Override
5523    public boolean addPermission(PermissionInfo info) {
5524        synchronized (mPackages) {
5525            return addPermissionLocked(info, false);
5526        }
5527    }
5528
5529    @Override
5530    public boolean addPermissionAsync(PermissionInfo info) {
5531        synchronized (mPackages) {
5532            return addPermissionLocked(info, true);
5533        }
5534    }
5535
5536    @Override
5537    public void removePermission(String name) {
5538        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5539            throw new SecurityException("Instant applications don't have access to this method");
5540        }
5541        synchronized (mPackages) {
5542            checkPermissionTreeLP(name);
5543            BasePermission bp = mSettings.mPermissions.get(name);
5544            if (bp != null) {
5545                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5546                    throw new SecurityException(
5547                            "Not allowed to modify non-dynamic permission "
5548                            + name);
5549                }
5550                mSettings.mPermissions.remove(name);
5551                mSettings.writeLPr();
5552            }
5553        }
5554    }
5555
5556    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5557            PackageParser.Package pkg, BasePermission bp) {
5558        int index = pkg.requestedPermissions.indexOf(bp.name);
5559        if (index == -1) {
5560            throw new SecurityException("Package " + pkg.packageName
5561                    + " has not requested permission " + bp.name);
5562        }
5563        if (!bp.isRuntime() && !bp.isDevelopment()) {
5564            throw new SecurityException("Permission " + bp.name
5565                    + " is not a changeable permission type");
5566        }
5567    }
5568
5569    @Override
5570    public void grantRuntimePermission(String packageName, String name, final int userId) {
5571        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5572    }
5573
5574    private void grantRuntimePermission(String packageName, String name, final int userId,
5575            boolean overridePolicy) {
5576        if (!sUserManager.exists(userId)) {
5577            Log.e(TAG, "No such user:" + userId);
5578            return;
5579        }
5580        final int callingUid = Binder.getCallingUid();
5581
5582        mContext.enforceCallingOrSelfPermission(
5583                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5584                "grantRuntimePermission");
5585
5586        enforceCrossUserPermission(callingUid, userId,
5587                true /* requireFullPermission */, true /* checkShell */,
5588                "grantRuntimePermission");
5589
5590        final int uid;
5591        final PackageSetting ps;
5592
5593        synchronized (mPackages) {
5594            final PackageParser.Package pkg = mPackages.get(packageName);
5595            if (pkg == null) {
5596                throw new IllegalArgumentException("Unknown package: " + packageName);
5597            }
5598            final BasePermission bp = mSettings.mPermissions.get(name);
5599            if (bp == null) {
5600                throw new IllegalArgumentException("Unknown permission: " + name);
5601            }
5602            ps = (PackageSetting) pkg.mExtras;
5603            if (ps == null
5604                    || filterAppAccessLPr(ps, callingUid, userId)) {
5605                throw new IllegalArgumentException("Unknown package: " + packageName);
5606            }
5607
5608            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5609
5610            // If a permission review is required for legacy apps we represent
5611            // their permissions as always granted runtime ones since we need
5612            // to keep the review required permission flag per user while an
5613            // install permission's state is shared across all users.
5614            if (mPermissionReviewRequired
5615                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5616                    && bp.isRuntime()) {
5617                return;
5618            }
5619
5620            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5621
5622            final PermissionsState permissionsState = ps.getPermissionsState();
5623
5624            final int flags = permissionsState.getPermissionFlags(name, userId);
5625            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5626                throw new SecurityException("Cannot grant system fixed permission "
5627                        + name + " for package " + packageName);
5628            }
5629            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5630                throw new SecurityException("Cannot grant policy fixed permission "
5631                        + name + " for package " + packageName);
5632            }
5633
5634            if (bp.isDevelopment()) {
5635                // Development permissions must be handled specially, since they are not
5636                // normal runtime permissions.  For now they apply to all users.
5637                if (permissionsState.grantInstallPermission(bp) !=
5638                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5639                    scheduleWriteSettingsLocked();
5640                }
5641                return;
5642            }
5643
5644            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5645                throw new SecurityException("Cannot grant non-ephemeral permission"
5646                        + name + " for package " + packageName);
5647            }
5648
5649            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5650                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5651                return;
5652            }
5653
5654            final int result = permissionsState.grantRuntimePermission(bp, userId);
5655            switch (result) {
5656                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5657                    return;
5658                }
5659
5660                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5661                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5662                    mHandler.post(new Runnable() {
5663                        @Override
5664                        public void run() {
5665                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5666                        }
5667                    });
5668                }
5669                break;
5670            }
5671
5672            if (bp.isRuntime()) {
5673                logPermissionGranted(mContext, name, packageName);
5674            }
5675
5676            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5677
5678            // Not critical if that is lost - app has to request again.
5679            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5680        }
5681
5682        // Only need to do this if user is initialized. Otherwise it's a new user
5683        // and there are no processes running as the user yet and there's no need
5684        // to make an expensive call to remount processes for the changed permissions.
5685        if (READ_EXTERNAL_STORAGE.equals(name)
5686                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5687            final long token = Binder.clearCallingIdentity();
5688            try {
5689                if (sUserManager.isInitialized(userId)) {
5690                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5691                            StorageManagerInternal.class);
5692                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5693                }
5694            } finally {
5695                Binder.restoreCallingIdentity(token);
5696            }
5697        }
5698    }
5699
5700    @Override
5701    public void revokeRuntimePermission(String packageName, String name, int userId) {
5702        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5703    }
5704
5705    private void revokeRuntimePermission(String packageName, String name, int userId,
5706            boolean overridePolicy) {
5707        if (!sUserManager.exists(userId)) {
5708            Log.e(TAG, "No such user:" + userId);
5709            return;
5710        }
5711
5712        mContext.enforceCallingOrSelfPermission(
5713                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5714                "revokeRuntimePermission");
5715
5716        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5717                true /* requireFullPermission */, true /* checkShell */,
5718                "revokeRuntimePermission");
5719
5720        final int appId;
5721
5722        synchronized (mPackages) {
5723            final PackageParser.Package pkg = mPackages.get(packageName);
5724            if (pkg == null) {
5725                throw new IllegalArgumentException("Unknown package: " + packageName);
5726            }
5727            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5728            if (ps == null
5729                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5730                throw new IllegalArgumentException("Unknown package: " + packageName);
5731            }
5732            final BasePermission bp = mSettings.mPermissions.get(name);
5733            if (bp == null) {
5734                throw new IllegalArgumentException("Unknown permission: " + name);
5735            }
5736
5737            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5738
5739            // If a permission review is required for legacy apps we represent
5740            // their permissions as always granted runtime ones since we need
5741            // to keep the review required permission flag per user while an
5742            // install permission's state is shared across all users.
5743            if (mPermissionReviewRequired
5744                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5745                    && bp.isRuntime()) {
5746                return;
5747            }
5748
5749            final PermissionsState permissionsState = ps.getPermissionsState();
5750
5751            final int flags = permissionsState.getPermissionFlags(name, userId);
5752            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5753                throw new SecurityException("Cannot revoke system fixed permission "
5754                        + name + " for package " + packageName);
5755            }
5756            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5757                throw new SecurityException("Cannot revoke policy fixed permission "
5758                        + name + " for package " + packageName);
5759            }
5760
5761            if (bp.isDevelopment()) {
5762                // Development permissions must be handled specially, since they are not
5763                // normal runtime permissions.  For now they apply to all users.
5764                if (permissionsState.revokeInstallPermission(bp) !=
5765                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5766                    scheduleWriteSettingsLocked();
5767                }
5768                return;
5769            }
5770
5771            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5772                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5773                return;
5774            }
5775
5776            if (bp.isRuntime()) {
5777                logPermissionRevoked(mContext, name, packageName);
5778            }
5779
5780            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5781
5782            // Critical, after this call app should never have the permission.
5783            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5784
5785            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5786        }
5787
5788        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5789    }
5790
5791    /**
5792     * Get the first event id for the permission.
5793     *
5794     * <p>There are four events for each permission: <ul>
5795     *     <li>Request permission: first id + 0</li>
5796     *     <li>Grant permission: first id + 1</li>
5797     *     <li>Request for permission denied: first id + 2</li>
5798     *     <li>Revoke permission: first id + 3</li>
5799     * </ul></p>
5800     *
5801     * @param name name of the permission
5802     *
5803     * @return The first event id for the permission
5804     */
5805    private static int getBaseEventId(@NonNull String name) {
5806        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5807
5808        if (eventIdIndex == -1) {
5809            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5810                    || Build.IS_USER) {
5811                Log.i(TAG, "Unknown permission " + name);
5812
5813                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5814            } else {
5815                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5816                //
5817                // Also update
5818                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5819                // - metrics_constants.proto
5820                throw new IllegalStateException("Unknown permission " + name);
5821            }
5822        }
5823
5824        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5825    }
5826
5827    /**
5828     * Log that a permission was revoked.
5829     *
5830     * @param context Context of the caller
5831     * @param name name of the permission
5832     * @param packageName package permission if for
5833     */
5834    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5835            @NonNull String packageName) {
5836        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5837    }
5838
5839    /**
5840     * Log that a permission request was granted.
5841     *
5842     * @param context Context of the caller
5843     * @param name name of the permission
5844     * @param packageName package permission if for
5845     */
5846    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5847            @NonNull String packageName) {
5848        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5849    }
5850
5851    @Override
5852    public void resetRuntimePermissions() {
5853        mContext.enforceCallingOrSelfPermission(
5854                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5855                "revokeRuntimePermission");
5856
5857        int callingUid = Binder.getCallingUid();
5858        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5859            mContext.enforceCallingOrSelfPermission(
5860                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5861                    "resetRuntimePermissions");
5862        }
5863
5864        synchronized (mPackages) {
5865            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5866            for (int userId : UserManagerService.getInstance().getUserIds()) {
5867                final int packageCount = mPackages.size();
5868                for (int i = 0; i < packageCount; i++) {
5869                    PackageParser.Package pkg = mPackages.valueAt(i);
5870                    if (!(pkg.mExtras instanceof PackageSetting)) {
5871                        continue;
5872                    }
5873                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5874                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5875                }
5876            }
5877        }
5878    }
5879
5880    @Override
5881    public int getPermissionFlags(String name, String packageName, int userId) {
5882        if (!sUserManager.exists(userId)) {
5883            return 0;
5884        }
5885
5886        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5887
5888        final int callingUid = Binder.getCallingUid();
5889        enforceCrossUserPermission(callingUid, userId,
5890                true /* requireFullPermission */, false /* checkShell */,
5891                "getPermissionFlags");
5892
5893        synchronized (mPackages) {
5894            final PackageParser.Package pkg = mPackages.get(packageName);
5895            if (pkg == null) {
5896                return 0;
5897            }
5898            final BasePermission bp = mSettings.mPermissions.get(name);
5899            if (bp == null) {
5900                return 0;
5901            }
5902            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5903            if (ps == null
5904                    || filterAppAccessLPr(ps, callingUid, userId)) {
5905                return 0;
5906            }
5907            PermissionsState permissionsState = ps.getPermissionsState();
5908            return permissionsState.getPermissionFlags(name, userId);
5909        }
5910    }
5911
5912    @Override
5913    public void updatePermissionFlags(String name, String packageName, int flagMask,
5914            int flagValues, int userId) {
5915        if (!sUserManager.exists(userId)) {
5916            return;
5917        }
5918
5919        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5920
5921        final int callingUid = Binder.getCallingUid();
5922        enforceCrossUserPermission(callingUid, userId,
5923                true /* requireFullPermission */, true /* checkShell */,
5924                "updatePermissionFlags");
5925
5926        // Only the system can change these flags and nothing else.
5927        if (getCallingUid() != Process.SYSTEM_UID) {
5928            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5929            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5930            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5931            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5932            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5933        }
5934
5935        synchronized (mPackages) {
5936            final PackageParser.Package pkg = mPackages.get(packageName);
5937            if (pkg == null) {
5938                throw new IllegalArgumentException("Unknown package: " + packageName);
5939            }
5940            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5941            if (ps == null
5942                    || filterAppAccessLPr(ps, callingUid, userId)) {
5943                throw new IllegalArgumentException("Unknown package: " + packageName);
5944            }
5945
5946            final BasePermission bp = mSettings.mPermissions.get(name);
5947            if (bp == null) {
5948                throw new IllegalArgumentException("Unknown permission: " + name);
5949            }
5950
5951            PermissionsState permissionsState = ps.getPermissionsState();
5952
5953            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5954
5955            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5956                // Install and runtime permissions are stored in different places,
5957                // so figure out what permission changed and persist the change.
5958                if (permissionsState.getInstallPermissionState(name) != null) {
5959                    scheduleWriteSettingsLocked();
5960                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5961                        || hadState) {
5962                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5963                }
5964            }
5965        }
5966    }
5967
5968    /**
5969     * Update the permission flags for all packages and runtime permissions of a user in order
5970     * to allow device or profile owner to remove POLICY_FIXED.
5971     */
5972    @Override
5973    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5974        if (!sUserManager.exists(userId)) {
5975            return;
5976        }
5977
5978        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5979
5980        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5981                true /* requireFullPermission */, true /* checkShell */,
5982                "updatePermissionFlagsForAllApps");
5983
5984        // Only the system can change system fixed flags.
5985        if (getCallingUid() != Process.SYSTEM_UID) {
5986            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5987            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5988        }
5989
5990        synchronized (mPackages) {
5991            boolean changed = false;
5992            final int packageCount = mPackages.size();
5993            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5994                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5995                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5996                if (ps == null) {
5997                    continue;
5998                }
5999                PermissionsState permissionsState = ps.getPermissionsState();
6000                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6001                        userId, flagMask, flagValues);
6002            }
6003            if (changed) {
6004                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6005            }
6006        }
6007    }
6008
6009    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6010        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6011                != PackageManager.PERMISSION_GRANTED
6012            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6013                != PackageManager.PERMISSION_GRANTED) {
6014            throw new SecurityException(message + " requires "
6015                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6016                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6017        }
6018    }
6019
6020    @Override
6021    public boolean shouldShowRequestPermissionRationale(String permissionName,
6022            String packageName, int userId) {
6023        if (UserHandle.getCallingUserId() != userId) {
6024            mContext.enforceCallingPermission(
6025                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6026                    "canShowRequestPermissionRationale for user " + userId);
6027        }
6028
6029        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6030        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6031            return false;
6032        }
6033
6034        if (checkPermission(permissionName, packageName, userId)
6035                == PackageManager.PERMISSION_GRANTED) {
6036            return false;
6037        }
6038
6039        final int flags;
6040
6041        final long identity = Binder.clearCallingIdentity();
6042        try {
6043            flags = getPermissionFlags(permissionName,
6044                    packageName, userId);
6045        } finally {
6046            Binder.restoreCallingIdentity(identity);
6047        }
6048
6049        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6050                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6051                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6052
6053        if ((flags & fixedFlags) != 0) {
6054            return false;
6055        }
6056
6057        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6058    }
6059
6060    @Override
6061    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6062        mContext.enforceCallingOrSelfPermission(
6063                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6064                "addOnPermissionsChangeListener");
6065
6066        synchronized (mPackages) {
6067            mOnPermissionChangeListeners.addListenerLocked(listener);
6068        }
6069    }
6070
6071    @Override
6072    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6073        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6074            throw new SecurityException("Instant applications don't have access to this method");
6075        }
6076        synchronized (mPackages) {
6077            mOnPermissionChangeListeners.removeListenerLocked(listener);
6078        }
6079    }
6080
6081    @Override
6082    public boolean isProtectedBroadcast(String actionName) {
6083        // allow instant applications
6084        synchronized (mProtectedBroadcasts) {
6085            if (mProtectedBroadcasts.contains(actionName)) {
6086                return true;
6087            } else if (actionName != null) {
6088                // TODO: remove these terrible hacks
6089                if (actionName.startsWith("android.net.netmon.lingerExpired")
6090                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6091                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6092                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6093                    return true;
6094                }
6095            }
6096        }
6097        return false;
6098    }
6099
6100    @Override
6101    public int checkSignatures(String pkg1, String pkg2) {
6102        synchronized (mPackages) {
6103            final PackageParser.Package p1 = mPackages.get(pkg1);
6104            final PackageParser.Package p2 = mPackages.get(pkg2);
6105            if (p1 == null || p1.mExtras == null
6106                    || p2 == null || p2.mExtras == null) {
6107                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6108            }
6109            final int callingUid = Binder.getCallingUid();
6110            final int callingUserId = UserHandle.getUserId(callingUid);
6111            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6112            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6113            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6114                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6115                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6116            }
6117            return compareSignatures(p1.mSignatures, p2.mSignatures);
6118        }
6119    }
6120
6121    @Override
6122    public int checkUidSignatures(int uid1, int uid2) {
6123        final int callingUid = Binder.getCallingUid();
6124        final int callingUserId = UserHandle.getUserId(callingUid);
6125        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6126        // Map to base uids.
6127        uid1 = UserHandle.getAppId(uid1);
6128        uid2 = UserHandle.getAppId(uid2);
6129        // reader
6130        synchronized (mPackages) {
6131            Signature[] s1;
6132            Signature[] s2;
6133            Object obj = mSettings.getUserIdLPr(uid1);
6134            if (obj != null) {
6135                if (obj instanceof SharedUserSetting) {
6136                    if (isCallerInstantApp) {
6137                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6138                    }
6139                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6140                } else if (obj instanceof PackageSetting) {
6141                    final PackageSetting ps = (PackageSetting) obj;
6142                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6143                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6144                    }
6145                    s1 = ps.signatures.mSignatures;
6146                } else {
6147                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6148                }
6149            } else {
6150                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6151            }
6152            obj = mSettings.getUserIdLPr(uid2);
6153            if (obj != null) {
6154                if (obj instanceof SharedUserSetting) {
6155                    if (isCallerInstantApp) {
6156                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6157                    }
6158                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6159                } else if (obj instanceof PackageSetting) {
6160                    final PackageSetting ps = (PackageSetting) obj;
6161                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6162                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6163                    }
6164                    s2 = ps.signatures.mSignatures;
6165                } else {
6166                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6167                }
6168            } else {
6169                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6170            }
6171            return compareSignatures(s1, s2);
6172        }
6173    }
6174
6175    /**
6176     * This method should typically only be used when granting or revoking
6177     * permissions, since the app may immediately restart after this call.
6178     * <p>
6179     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6180     * guard your work against the app being relaunched.
6181     */
6182    private void killUid(int appId, int userId, String reason) {
6183        final long identity = Binder.clearCallingIdentity();
6184        try {
6185            IActivityManager am = ActivityManager.getService();
6186            if (am != null) {
6187                try {
6188                    am.killUid(appId, userId, reason);
6189                } catch (RemoteException e) {
6190                    /* ignore - same process */
6191                }
6192            }
6193        } finally {
6194            Binder.restoreCallingIdentity(identity);
6195        }
6196    }
6197
6198    /**
6199     * Compares two sets of signatures. Returns:
6200     * <br />
6201     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6202     * <br />
6203     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6204     * <br />
6205     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6206     * <br />
6207     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6208     * <br />
6209     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6210     */
6211    static int compareSignatures(Signature[] s1, Signature[] s2) {
6212        if (s1 == null) {
6213            return s2 == null
6214                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6215                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6216        }
6217
6218        if (s2 == null) {
6219            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6220        }
6221
6222        if (s1.length != s2.length) {
6223            return PackageManager.SIGNATURE_NO_MATCH;
6224        }
6225
6226        // Since both signature sets are of size 1, we can compare without HashSets.
6227        if (s1.length == 1) {
6228            return s1[0].equals(s2[0]) ?
6229                    PackageManager.SIGNATURE_MATCH :
6230                    PackageManager.SIGNATURE_NO_MATCH;
6231        }
6232
6233        ArraySet<Signature> set1 = new ArraySet<Signature>();
6234        for (Signature sig : s1) {
6235            set1.add(sig);
6236        }
6237        ArraySet<Signature> set2 = new ArraySet<Signature>();
6238        for (Signature sig : s2) {
6239            set2.add(sig);
6240        }
6241        // Make sure s2 contains all signatures in s1.
6242        if (set1.equals(set2)) {
6243            return PackageManager.SIGNATURE_MATCH;
6244        }
6245        return PackageManager.SIGNATURE_NO_MATCH;
6246    }
6247
6248    /**
6249     * If the database version for this type of package (internal storage or
6250     * external storage) is less than the version where package signatures
6251     * were updated, return true.
6252     */
6253    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6254        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6255        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6256    }
6257
6258    /**
6259     * Used for backward compatibility to make sure any packages with
6260     * certificate chains get upgraded to the new style. {@code existingSigs}
6261     * will be in the old format (since they were stored on disk from before the
6262     * system upgrade) and {@code scannedSigs} will be in the newer format.
6263     */
6264    private int compareSignaturesCompat(PackageSignatures existingSigs,
6265            PackageParser.Package scannedPkg) {
6266        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6267            return PackageManager.SIGNATURE_NO_MATCH;
6268        }
6269
6270        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6271        for (Signature sig : existingSigs.mSignatures) {
6272            existingSet.add(sig);
6273        }
6274        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6275        for (Signature sig : scannedPkg.mSignatures) {
6276            try {
6277                Signature[] chainSignatures = sig.getChainSignatures();
6278                for (Signature chainSig : chainSignatures) {
6279                    scannedCompatSet.add(chainSig);
6280                }
6281            } catch (CertificateEncodingException e) {
6282                scannedCompatSet.add(sig);
6283            }
6284        }
6285        /*
6286         * Make sure the expanded scanned set contains all signatures in the
6287         * existing one.
6288         */
6289        if (scannedCompatSet.equals(existingSet)) {
6290            // Migrate the old signatures to the new scheme.
6291            existingSigs.assignSignatures(scannedPkg.mSignatures);
6292            // The new KeySets will be re-added later in the scanning process.
6293            synchronized (mPackages) {
6294                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6295            }
6296            return PackageManager.SIGNATURE_MATCH;
6297        }
6298        return PackageManager.SIGNATURE_NO_MATCH;
6299    }
6300
6301    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6302        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6303        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6304    }
6305
6306    private int compareSignaturesRecover(PackageSignatures existingSigs,
6307            PackageParser.Package scannedPkg) {
6308        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6309            return PackageManager.SIGNATURE_NO_MATCH;
6310        }
6311
6312        String msg = null;
6313        try {
6314            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6315                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6316                        + scannedPkg.packageName);
6317                return PackageManager.SIGNATURE_MATCH;
6318            }
6319        } catch (CertificateException e) {
6320            msg = e.getMessage();
6321        }
6322
6323        logCriticalInfo(Log.INFO,
6324                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6325        return PackageManager.SIGNATURE_NO_MATCH;
6326    }
6327
6328    @Override
6329    public List<String> getAllPackages() {
6330        final int callingUid = Binder.getCallingUid();
6331        final int callingUserId = UserHandle.getUserId(callingUid);
6332        synchronized (mPackages) {
6333            if (canViewInstantApps(callingUid, callingUserId)) {
6334                return new ArrayList<String>(mPackages.keySet());
6335            }
6336            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6337            final List<String> result = new ArrayList<>();
6338            if (instantAppPkgName != null) {
6339                // caller is an instant application; filter unexposed applications
6340                for (PackageParser.Package pkg : mPackages.values()) {
6341                    if (!pkg.visibleToInstantApps) {
6342                        continue;
6343                    }
6344                    result.add(pkg.packageName);
6345                }
6346            } else {
6347                // caller is a normal application; filter instant applications
6348                for (PackageParser.Package pkg : mPackages.values()) {
6349                    final PackageSetting ps =
6350                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6351                    if (ps != null
6352                            && ps.getInstantApp(callingUserId)
6353                            && !mInstantAppRegistry.isInstantAccessGranted(
6354                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6355                        continue;
6356                    }
6357                    result.add(pkg.packageName);
6358                }
6359            }
6360            return result;
6361        }
6362    }
6363
6364    @Override
6365    public String[] getPackagesForUid(int uid) {
6366        final int callingUid = Binder.getCallingUid();
6367        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6368        final int userId = UserHandle.getUserId(uid);
6369        uid = UserHandle.getAppId(uid);
6370        // reader
6371        synchronized (mPackages) {
6372            Object obj = mSettings.getUserIdLPr(uid);
6373            if (obj instanceof SharedUserSetting) {
6374                if (isCallerInstantApp) {
6375                    return null;
6376                }
6377                final SharedUserSetting sus = (SharedUserSetting) obj;
6378                final int N = sus.packages.size();
6379                String[] res = new String[N];
6380                final Iterator<PackageSetting> it = sus.packages.iterator();
6381                int i = 0;
6382                while (it.hasNext()) {
6383                    PackageSetting ps = it.next();
6384                    if (ps.getInstalled(userId)) {
6385                        res[i++] = ps.name;
6386                    } else {
6387                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6388                    }
6389                }
6390                return res;
6391            } else if (obj instanceof PackageSetting) {
6392                final PackageSetting ps = (PackageSetting) obj;
6393                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6394                    return new String[]{ps.name};
6395                }
6396            }
6397        }
6398        return null;
6399    }
6400
6401    @Override
6402    public String getNameForUid(int uid) {
6403        final int callingUid = Binder.getCallingUid();
6404        if (getInstantAppPackageName(callingUid) != null) {
6405            return null;
6406        }
6407        synchronized (mPackages) {
6408            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6409            if (obj instanceof SharedUserSetting) {
6410                final SharedUserSetting sus = (SharedUserSetting) obj;
6411                return sus.name + ":" + sus.userId;
6412            } else if (obj instanceof PackageSetting) {
6413                final PackageSetting ps = (PackageSetting) obj;
6414                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6415                    return null;
6416                }
6417                return ps.name;
6418            }
6419            return null;
6420        }
6421    }
6422
6423    @Override
6424    public String[] getNamesForUids(int[] uids) {
6425        if (uids == null || uids.length == 0) {
6426            return null;
6427        }
6428        final int callingUid = Binder.getCallingUid();
6429        if (getInstantAppPackageName(callingUid) != null) {
6430            return null;
6431        }
6432        final String[] names = new String[uids.length];
6433        synchronized (mPackages) {
6434            for (int i = uids.length - 1; i >= 0; i--) {
6435                final int uid = uids[i];
6436                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6437                if (obj instanceof SharedUserSetting) {
6438                    final SharedUserSetting sus = (SharedUserSetting) obj;
6439                    names[i] = "shared:" + sus.name;
6440                } else if (obj instanceof PackageSetting) {
6441                    final PackageSetting ps = (PackageSetting) obj;
6442                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6443                        names[i] = null;
6444                    } else {
6445                        names[i] = ps.name;
6446                    }
6447                } else {
6448                    names[i] = null;
6449                }
6450            }
6451        }
6452        return names;
6453    }
6454
6455    @Override
6456    public int getUidForSharedUser(String sharedUserName) {
6457        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6458            return -1;
6459        }
6460        if (sharedUserName == null) {
6461            return -1;
6462        }
6463        // reader
6464        synchronized (mPackages) {
6465            SharedUserSetting suid;
6466            try {
6467                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6468                if (suid != null) {
6469                    return suid.userId;
6470                }
6471            } catch (PackageManagerException ignore) {
6472                // can't happen, but, still need to catch it
6473            }
6474            return -1;
6475        }
6476    }
6477
6478    @Override
6479    public int getFlagsForUid(int uid) {
6480        final int callingUid = Binder.getCallingUid();
6481        if (getInstantAppPackageName(callingUid) != null) {
6482            return 0;
6483        }
6484        synchronized (mPackages) {
6485            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6486            if (obj instanceof SharedUserSetting) {
6487                final SharedUserSetting sus = (SharedUserSetting) obj;
6488                return sus.pkgFlags;
6489            } else if (obj instanceof PackageSetting) {
6490                final PackageSetting ps = (PackageSetting) obj;
6491                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6492                    return 0;
6493                }
6494                return ps.pkgFlags;
6495            }
6496        }
6497        return 0;
6498    }
6499
6500    @Override
6501    public int getPrivateFlagsForUid(int uid) {
6502        final int callingUid = Binder.getCallingUid();
6503        if (getInstantAppPackageName(callingUid) != null) {
6504            return 0;
6505        }
6506        synchronized (mPackages) {
6507            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6508            if (obj instanceof SharedUserSetting) {
6509                final SharedUserSetting sus = (SharedUserSetting) obj;
6510                return sus.pkgPrivateFlags;
6511            } else if (obj instanceof PackageSetting) {
6512                final PackageSetting ps = (PackageSetting) obj;
6513                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6514                    return 0;
6515                }
6516                return ps.pkgPrivateFlags;
6517            }
6518        }
6519        return 0;
6520    }
6521
6522    @Override
6523    public boolean isUidPrivileged(int uid) {
6524        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6525            return false;
6526        }
6527        uid = UserHandle.getAppId(uid);
6528        // reader
6529        synchronized (mPackages) {
6530            Object obj = mSettings.getUserIdLPr(uid);
6531            if (obj instanceof SharedUserSetting) {
6532                final SharedUserSetting sus = (SharedUserSetting) obj;
6533                final Iterator<PackageSetting> it = sus.packages.iterator();
6534                while (it.hasNext()) {
6535                    if (it.next().isPrivileged()) {
6536                        return true;
6537                    }
6538                }
6539            } else if (obj instanceof PackageSetting) {
6540                final PackageSetting ps = (PackageSetting) obj;
6541                return ps.isPrivileged();
6542            }
6543        }
6544        return false;
6545    }
6546
6547    @Override
6548    public String[] getAppOpPermissionPackages(String permissionName) {
6549        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6550            return null;
6551        }
6552        synchronized (mPackages) {
6553            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6554            if (pkgs == null) {
6555                return null;
6556            }
6557            return pkgs.toArray(new String[pkgs.size()]);
6558        }
6559    }
6560
6561    @Override
6562    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6563            int flags, int userId) {
6564        return resolveIntentInternal(
6565                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6566    }
6567
6568    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6569            int flags, int userId, boolean resolveForStart) {
6570        try {
6571            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6572
6573            if (!sUserManager.exists(userId)) return null;
6574            final int callingUid = Binder.getCallingUid();
6575            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6576            enforceCrossUserPermission(callingUid, userId,
6577                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6578
6579            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6580            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6581                    flags, callingUid, userId, resolveForStart);
6582            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6583
6584            final ResolveInfo bestChoice =
6585                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6586            return bestChoice;
6587        } finally {
6588            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6589        }
6590    }
6591
6592    @Override
6593    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6594        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6595            throw new SecurityException(
6596                    "findPersistentPreferredActivity can only be run by the system");
6597        }
6598        if (!sUserManager.exists(userId)) {
6599            return null;
6600        }
6601        final int callingUid = Binder.getCallingUid();
6602        intent = updateIntentForResolve(intent);
6603        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6604        final int flags = updateFlagsForResolve(
6605                0, userId, intent, callingUid, false /*includeInstantApps*/);
6606        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6607                userId);
6608        synchronized (mPackages) {
6609            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6610                    userId);
6611        }
6612    }
6613
6614    @Override
6615    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6616            IntentFilter filter, int match, ComponentName activity) {
6617        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6618            return;
6619        }
6620        final int userId = UserHandle.getCallingUserId();
6621        if (DEBUG_PREFERRED) {
6622            Log.v(TAG, "setLastChosenActivity intent=" + intent
6623                + " resolvedType=" + resolvedType
6624                + " flags=" + flags
6625                + " filter=" + filter
6626                + " match=" + match
6627                + " activity=" + activity);
6628            filter.dump(new PrintStreamPrinter(System.out), "    ");
6629        }
6630        intent.setComponent(null);
6631        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6632                userId);
6633        // Find any earlier preferred or last chosen entries and nuke them
6634        findPreferredActivity(intent, resolvedType,
6635                flags, query, 0, false, true, false, userId);
6636        // Add the new activity as the last chosen for this filter
6637        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6638                "Setting last chosen");
6639    }
6640
6641    @Override
6642    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6643        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6644            return null;
6645        }
6646        final int userId = UserHandle.getCallingUserId();
6647        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6648        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6649                userId);
6650        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6651                false, false, false, userId);
6652    }
6653
6654    /**
6655     * Returns whether or not instant apps have been disabled remotely.
6656     */
6657    private boolean isEphemeralDisabled() {
6658        return mEphemeralAppsDisabled;
6659    }
6660
6661    private boolean isInstantAppAllowed(
6662            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6663            boolean skipPackageCheck) {
6664        if (mInstantAppResolverConnection == null) {
6665            return false;
6666        }
6667        if (mInstantAppInstallerActivity == null) {
6668            return false;
6669        }
6670        if (intent.getComponent() != null) {
6671            return false;
6672        }
6673        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6674            return false;
6675        }
6676        if (!skipPackageCheck && intent.getPackage() != null) {
6677            return false;
6678        }
6679        final boolean isWebUri = hasWebURI(intent);
6680        if (!isWebUri || intent.getData().getHost() == null) {
6681            return false;
6682        }
6683        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6684        // Or if there's already an ephemeral app installed that handles the action
6685        synchronized (mPackages) {
6686            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6687            for (int n = 0; n < count; n++) {
6688                final ResolveInfo info = resolvedActivities.get(n);
6689                final String packageName = info.activityInfo.packageName;
6690                final PackageSetting ps = mSettings.mPackages.get(packageName);
6691                if (ps != null) {
6692                    // only check domain verification status if the app is not a browser
6693                    if (!info.handleAllWebDataURI) {
6694                        // Try to get the status from User settings first
6695                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6696                        final int status = (int) (packedStatus >> 32);
6697                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6698                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6699                            if (DEBUG_EPHEMERAL) {
6700                                Slog.v(TAG, "DENY instant app;"
6701                                    + " pkg: " + packageName + ", status: " + status);
6702                            }
6703                            return false;
6704                        }
6705                    }
6706                    if (ps.getInstantApp(userId)) {
6707                        if (DEBUG_EPHEMERAL) {
6708                            Slog.v(TAG, "DENY instant app installed;"
6709                                    + " pkg: " + packageName);
6710                        }
6711                        return false;
6712                    }
6713                }
6714            }
6715        }
6716        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6717        return true;
6718    }
6719
6720    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6721            Intent origIntent, String resolvedType, String callingPackage,
6722            Bundle verificationBundle, int userId) {
6723        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6724                new InstantAppRequest(responseObj, origIntent, resolvedType,
6725                        callingPackage, userId, verificationBundle));
6726        mHandler.sendMessage(msg);
6727    }
6728
6729    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6730            int flags, List<ResolveInfo> query, int userId) {
6731        if (query != null) {
6732            final int N = query.size();
6733            if (N == 1) {
6734                return query.get(0);
6735            } else if (N > 1) {
6736                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6737                // If there is more than one activity with the same priority,
6738                // then let the user decide between them.
6739                ResolveInfo r0 = query.get(0);
6740                ResolveInfo r1 = query.get(1);
6741                if (DEBUG_INTENT_MATCHING || debug) {
6742                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6743                            + r1.activityInfo.name + "=" + r1.priority);
6744                }
6745                // If the first activity has a higher priority, or a different
6746                // default, then it is always desirable to pick it.
6747                if (r0.priority != r1.priority
6748                        || r0.preferredOrder != r1.preferredOrder
6749                        || r0.isDefault != r1.isDefault) {
6750                    return query.get(0);
6751                }
6752                // If we have saved a preference for a preferred activity for
6753                // this Intent, use that.
6754                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6755                        flags, query, r0.priority, true, false, debug, userId);
6756                if (ri != null) {
6757                    return ri;
6758                }
6759                // If we have an ephemeral app, use it
6760                for (int i = 0; i < N; i++) {
6761                    ri = query.get(i);
6762                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6763                        final String packageName = ri.activityInfo.packageName;
6764                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6765                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6766                        final int status = (int)(packedStatus >> 32);
6767                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6768                            return ri;
6769                        }
6770                    }
6771                }
6772                ri = new ResolveInfo(mResolveInfo);
6773                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6774                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6775                // If all of the options come from the same package, show the application's
6776                // label and icon instead of the generic resolver's.
6777                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6778                // and then throw away the ResolveInfo itself, meaning that the caller loses
6779                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6780                // a fallback for this case; we only set the target package's resources on
6781                // the ResolveInfo, not the ActivityInfo.
6782                final String intentPackage = intent.getPackage();
6783                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6784                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6785                    ri.resolvePackageName = intentPackage;
6786                    if (userNeedsBadging(userId)) {
6787                        ri.noResourceId = true;
6788                    } else {
6789                        ri.icon = appi.icon;
6790                    }
6791                    ri.iconResourceId = appi.icon;
6792                    ri.labelRes = appi.labelRes;
6793                }
6794                ri.activityInfo.applicationInfo = new ApplicationInfo(
6795                        ri.activityInfo.applicationInfo);
6796                if (userId != 0) {
6797                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6798                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6799                }
6800                // Make sure that the resolver is displayable in car mode
6801                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6802                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6803                return ri;
6804            }
6805        }
6806        return null;
6807    }
6808
6809    /**
6810     * Return true if the given list is not empty and all of its contents have
6811     * an activityInfo with the given package name.
6812     */
6813    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6814        if (ArrayUtils.isEmpty(list)) {
6815            return false;
6816        }
6817        for (int i = 0, N = list.size(); i < N; i++) {
6818            final ResolveInfo ri = list.get(i);
6819            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6820            if (ai == null || !packageName.equals(ai.packageName)) {
6821                return false;
6822            }
6823        }
6824        return true;
6825    }
6826
6827    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6828            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6829        final int N = query.size();
6830        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6831                .get(userId);
6832        // Get the list of persistent preferred activities that handle the intent
6833        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6834        List<PersistentPreferredActivity> pprefs = ppir != null
6835                ? ppir.queryIntent(intent, resolvedType,
6836                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6837                        userId)
6838                : null;
6839        if (pprefs != null && pprefs.size() > 0) {
6840            final int M = pprefs.size();
6841            for (int i=0; i<M; i++) {
6842                final PersistentPreferredActivity ppa = pprefs.get(i);
6843                if (DEBUG_PREFERRED || debug) {
6844                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6845                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6846                            + "\n  component=" + ppa.mComponent);
6847                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6848                }
6849                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6850                        flags | MATCH_DISABLED_COMPONENTS, userId);
6851                if (DEBUG_PREFERRED || debug) {
6852                    Slog.v(TAG, "Found persistent preferred activity:");
6853                    if (ai != null) {
6854                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6855                    } else {
6856                        Slog.v(TAG, "  null");
6857                    }
6858                }
6859                if (ai == null) {
6860                    // This previously registered persistent preferred activity
6861                    // component is no longer known. Ignore it and do NOT remove it.
6862                    continue;
6863                }
6864                for (int j=0; j<N; j++) {
6865                    final ResolveInfo ri = query.get(j);
6866                    if (!ri.activityInfo.applicationInfo.packageName
6867                            .equals(ai.applicationInfo.packageName)) {
6868                        continue;
6869                    }
6870                    if (!ri.activityInfo.name.equals(ai.name)) {
6871                        continue;
6872                    }
6873                    //  Found a persistent preference that can handle the intent.
6874                    if (DEBUG_PREFERRED || debug) {
6875                        Slog.v(TAG, "Returning persistent preferred activity: " +
6876                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6877                    }
6878                    return ri;
6879                }
6880            }
6881        }
6882        return null;
6883    }
6884
6885    // TODO: handle preferred activities missing while user has amnesia
6886    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6887            List<ResolveInfo> query, int priority, boolean always,
6888            boolean removeMatches, boolean debug, int userId) {
6889        if (!sUserManager.exists(userId)) return null;
6890        final int callingUid = Binder.getCallingUid();
6891        flags = updateFlagsForResolve(
6892                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6893        intent = updateIntentForResolve(intent);
6894        // writer
6895        synchronized (mPackages) {
6896            // Try to find a matching persistent preferred activity.
6897            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6898                    debug, userId);
6899
6900            // If a persistent preferred activity matched, use it.
6901            if (pri != null) {
6902                return pri;
6903            }
6904
6905            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6906            // Get the list of preferred activities that handle the intent
6907            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6908            List<PreferredActivity> prefs = pir != null
6909                    ? pir.queryIntent(intent, resolvedType,
6910                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6911                            userId)
6912                    : null;
6913            if (prefs != null && prefs.size() > 0) {
6914                boolean changed = false;
6915                try {
6916                    // First figure out how good the original match set is.
6917                    // We will only allow preferred activities that came
6918                    // from the same match quality.
6919                    int match = 0;
6920
6921                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6922
6923                    final int N = query.size();
6924                    for (int j=0; j<N; j++) {
6925                        final ResolveInfo ri = query.get(j);
6926                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6927                                + ": 0x" + Integer.toHexString(match));
6928                        if (ri.match > match) {
6929                            match = ri.match;
6930                        }
6931                    }
6932
6933                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6934                            + Integer.toHexString(match));
6935
6936                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6937                    final int M = prefs.size();
6938                    for (int i=0; i<M; i++) {
6939                        final PreferredActivity pa = prefs.get(i);
6940                        if (DEBUG_PREFERRED || debug) {
6941                            Slog.v(TAG, "Checking PreferredActivity ds="
6942                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6943                                    + "\n  component=" + pa.mPref.mComponent);
6944                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6945                        }
6946                        if (pa.mPref.mMatch != match) {
6947                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6948                                    + Integer.toHexString(pa.mPref.mMatch));
6949                            continue;
6950                        }
6951                        // If it's not an "always" type preferred activity and that's what we're
6952                        // looking for, skip it.
6953                        if (always && !pa.mPref.mAlways) {
6954                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6955                            continue;
6956                        }
6957                        final ActivityInfo ai = getActivityInfo(
6958                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6959                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6960                                userId);
6961                        if (DEBUG_PREFERRED || debug) {
6962                            Slog.v(TAG, "Found preferred activity:");
6963                            if (ai != null) {
6964                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6965                            } else {
6966                                Slog.v(TAG, "  null");
6967                            }
6968                        }
6969                        if (ai == null) {
6970                            // This previously registered preferred activity
6971                            // component is no longer known.  Most likely an update
6972                            // to the app was installed and in the new version this
6973                            // component no longer exists.  Clean it up by removing
6974                            // it from the preferred activities list, and skip it.
6975                            Slog.w(TAG, "Removing dangling preferred activity: "
6976                                    + pa.mPref.mComponent);
6977                            pir.removeFilter(pa);
6978                            changed = true;
6979                            continue;
6980                        }
6981                        for (int j=0; j<N; j++) {
6982                            final ResolveInfo ri = query.get(j);
6983                            if (!ri.activityInfo.applicationInfo.packageName
6984                                    .equals(ai.applicationInfo.packageName)) {
6985                                continue;
6986                            }
6987                            if (!ri.activityInfo.name.equals(ai.name)) {
6988                                continue;
6989                            }
6990
6991                            if (removeMatches) {
6992                                pir.removeFilter(pa);
6993                                changed = true;
6994                                if (DEBUG_PREFERRED) {
6995                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6996                                }
6997                                break;
6998                            }
6999
7000                            // Okay we found a previously set preferred or last chosen app.
7001                            // If the result set is different from when this
7002                            // was created, we need to clear it and re-ask the
7003                            // user their preference, if we're looking for an "always" type entry.
7004                            if (always && !pa.mPref.sameSet(query)) {
7005                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
7006                                        + intent + " type " + resolvedType);
7007                                if (DEBUG_PREFERRED) {
7008                                    Slog.v(TAG, "Removing preferred activity since set changed "
7009                                            + pa.mPref.mComponent);
7010                                }
7011                                pir.removeFilter(pa);
7012                                // Re-add the filter as a "last chosen" entry (!always)
7013                                PreferredActivity lastChosen = new PreferredActivity(
7014                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7015                                pir.addFilter(lastChosen);
7016                                changed = true;
7017                                return null;
7018                            }
7019
7020                            // Yay! Either the set matched or we're looking for the last chosen
7021                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7022                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7023                            return ri;
7024                        }
7025                    }
7026                } finally {
7027                    if (changed) {
7028                        if (DEBUG_PREFERRED) {
7029                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7030                        }
7031                        scheduleWritePackageRestrictionsLocked(userId);
7032                    }
7033                }
7034            }
7035        }
7036        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7037        return null;
7038    }
7039
7040    /*
7041     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7042     */
7043    @Override
7044    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7045            int targetUserId) {
7046        mContext.enforceCallingOrSelfPermission(
7047                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7048        List<CrossProfileIntentFilter> matches =
7049                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7050        if (matches != null) {
7051            int size = matches.size();
7052            for (int i = 0; i < size; i++) {
7053                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7054            }
7055        }
7056        if (hasWebURI(intent)) {
7057            // cross-profile app linking works only towards the parent.
7058            final int callingUid = Binder.getCallingUid();
7059            final UserInfo parent = getProfileParent(sourceUserId);
7060            synchronized(mPackages) {
7061                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7062                        false /*includeInstantApps*/);
7063                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7064                        intent, resolvedType, flags, sourceUserId, parent.id);
7065                return xpDomainInfo != null;
7066            }
7067        }
7068        return false;
7069    }
7070
7071    private UserInfo getProfileParent(int userId) {
7072        final long identity = Binder.clearCallingIdentity();
7073        try {
7074            return sUserManager.getProfileParent(userId);
7075        } finally {
7076            Binder.restoreCallingIdentity(identity);
7077        }
7078    }
7079
7080    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7081            String resolvedType, int userId) {
7082        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7083        if (resolver != null) {
7084            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7085        }
7086        return null;
7087    }
7088
7089    @Override
7090    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7091            String resolvedType, int flags, int userId) {
7092        try {
7093            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7094
7095            return new ParceledListSlice<>(
7096                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7097        } finally {
7098            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7099        }
7100    }
7101
7102    /**
7103     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7104     * instant, returns {@code null}.
7105     */
7106    private String getInstantAppPackageName(int callingUid) {
7107        synchronized (mPackages) {
7108            // If the caller is an isolated app use the owner's uid for the lookup.
7109            if (Process.isIsolated(callingUid)) {
7110                callingUid = mIsolatedOwners.get(callingUid);
7111            }
7112            final int appId = UserHandle.getAppId(callingUid);
7113            final Object obj = mSettings.getUserIdLPr(appId);
7114            if (obj instanceof PackageSetting) {
7115                final PackageSetting ps = (PackageSetting) obj;
7116                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7117                return isInstantApp ? ps.pkg.packageName : null;
7118            }
7119        }
7120        return null;
7121    }
7122
7123    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7124            String resolvedType, int flags, int userId) {
7125        return queryIntentActivitiesInternal(
7126                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
7127    }
7128
7129    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7130            String resolvedType, int flags, int filterCallingUid, int userId,
7131            boolean resolveForStart) {
7132        if (!sUserManager.exists(userId)) return Collections.emptyList();
7133        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7134        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7135                false /* requireFullPermission */, false /* checkShell */,
7136                "query intent activities");
7137        final String pkgName = intent.getPackage();
7138        ComponentName comp = intent.getComponent();
7139        if (comp == null) {
7140            if (intent.getSelector() != null) {
7141                intent = intent.getSelector();
7142                comp = intent.getComponent();
7143            }
7144        }
7145
7146        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7147                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7148        if (comp != null) {
7149            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7150            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7151            if (ai != null) {
7152                // When specifying an explicit component, we prevent the activity from being
7153                // used when either 1) the calling package is normal and the activity is within
7154                // an ephemeral application or 2) the calling package is ephemeral and the
7155                // activity is not visible to ephemeral applications.
7156                final boolean matchInstantApp =
7157                        (flags & PackageManager.MATCH_INSTANT) != 0;
7158                final boolean matchVisibleToInstantAppOnly =
7159                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7160                final boolean matchExplicitlyVisibleOnly =
7161                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7162                final boolean isCallerInstantApp =
7163                        instantAppPkgName != null;
7164                final boolean isTargetSameInstantApp =
7165                        comp.getPackageName().equals(instantAppPkgName);
7166                final boolean isTargetInstantApp =
7167                        (ai.applicationInfo.privateFlags
7168                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7169                final boolean isTargetVisibleToInstantApp =
7170                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7171                final boolean isTargetExplicitlyVisibleToInstantApp =
7172                        isTargetVisibleToInstantApp
7173                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7174                final boolean isTargetHiddenFromInstantApp =
7175                        !isTargetVisibleToInstantApp
7176                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7177                final boolean blockResolution =
7178                        !isTargetSameInstantApp
7179                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7180                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7181                                        && isTargetHiddenFromInstantApp));
7182                if (!blockResolution) {
7183                    final ResolveInfo ri = new ResolveInfo();
7184                    ri.activityInfo = ai;
7185                    list.add(ri);
7186                }
7187            }
7188            return applyPostResolutionFilter(list, instantAppPkgName);
7189        }
7190
7191        // reader
7192        boolean sortResult = false;
7193        boolean addEphemeral = false;
7194        List<ResolveInfo> result;
7195        final boolean ephemeralDisabled = isEphemeralDisabled();
7196        synchronized (mPackages) {
7197            if (pkgName == null) {
7198                List<CrossProfileIntentFilter> matchingFilters =
7199                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7200                // Check for results that need to skip the current profile.
7201                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7202                        resolvedType, flags, userId);
7203                if (xpResolveInfo != null) {
7204                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7205                    xpResult.add(xpResolveInfo);
7206                    return applyPostResolutionFilter(
7207                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
7208                }
7209
7210                // Check for results in the current profile.
7211                result = filterIfNotSystemUser(mActivities.queryIntent(
7212                        intent, resolvedType, flags, userId), userId);
7213                addEphemeral = !ephemeralDisabled
7214                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7215                // Check for cross profile results.
7216                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7217                xpResolveInfo = queryCrossProfileIntents(
7218                        matchingFilters, intent, resolvedType, flags, userId,
7219                        hasNonNegativePriorityResult);
7220                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7221                    boolean isVisibleToUser = filterIfNotSystemUser(
7222                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7223                    if (isVisibleToUser) {
7224                        result.add(xpResolveInfo);
7225                        sortResult = true;
7226                    }
7227                }
7228                if (hasWebURI(intent)) {
7229                    CrossProfileDomainInfo xpDomainInfo = null;
7230                    final UserInfo parent = getProfileParent(userId);
7231                    if (parent != null) {
7232                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7233                                flags, userId, parent.id);
7234                    }
7235                    if (xpDomainInfo != null) {
7236                        if (xpResolveInfo != null) {
7237                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7238                            // in the result.
7239                            result.remove(xpResolveInfo);
7240                        }
7241                        if (result.size() == 0 && !addEphemeral) {
7242                            // No result in current profile, but found candidate in parent user.
7243                            // And we are not going to add emphemeral app, so we can return the
7244                            // result straight away.
7245                            result.add(xpDomainInfo.resolveInfo);
7246                            return applyPostResolutionFilter(result, instantAppPkgName);
7247                        }
7248                    } else if (result.size() <= 1 && !addEphemeral) {
7249                        // No result in parent user and <= 1 result in current profile, and we
7250                        // are not going to add emphemeral app, so we can return the result without
7251                        // further processing.
7252                        return applyPostResolutionFilter(result, instantAppPkgName);
7253                    }
7254                    // We have more than one candidate (combining results from current and parent
7255                    // profile), so we need filtering and sorting.
7256                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7257                            intent, flags, result, xpDomainInfo, userId);
7258                    sortResult = true;
7259                }
7260            } else {
7261                final PackageParser.Package pkg = mPackages.get(pkgName);
7262                result = null;
7263                if (pkg != null) {
7264                    result = filterIfNotSystemUser(
7265                            mActivities.queryIntentForPackage(
7266                                    intent, resolvedType, flags, pkg.activities, userId),
7267                            userId);
7268                }
7269                if (result == null || result.size() == 0) {
7270                    // the caller wants to resolve for a particular package; however, there
7271                    // were no installed results, so, try to find an ephemeral result
7272                    addEphemeral = !ephemeralDisabled
7273                            && isInstantAppAllowed(
7274                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7275                    if (result == null) {
7276                        result = new ArrayList<>();
7277                    }
7278                }
7279            }
7280        }
7281        if (addEphemeral) {
7282            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7283        }
7284        if (sortResult) {
7285            Collections.sort(result, mResolvePrioritySorter);
7286        }
7287        return applyPostResolutionFilter(result, instantAppPkgName);
7288    }
7289
7290    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7291            String resolvedType, int flags, int userId) {
7292        // first, check to see if we've got an instant app already installed
7293        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7294        ResolveInfo localInstantApp = null;
7295        boolean blockResolution = false;
7296        if (!alreadyResolvedLocally) {
7297            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7298                    flags
7299                        | PackageManager.GET_RESOLVED_FILTER
7300                        | PackageManager.MATCH_INSTANT
7301                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7302                    userId);
7303            for (int i = instantApps.size() - 1; i >= 0; --i) {
7304                final ResolveInfo info = instantApps.get(i);
7305                final String packageName = info.activityInfo.packageName;
7306                final PackageSetting ps = mSettings.mPackages.get(packageName);
7307                if (ps.getInstantApp(userId)) {
7308                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7309                    final int status = (int)(packedStatus >> 32);
7310                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7311                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7312                        // there's a local instant application installed, but, the user has
7313                        // chosen to never use it; skip resolution and don't acknowledge
7314                        // an instant application is even available
7315                        if (DEBUG_EPHEMERAL) {
7316                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7317                        }
7318                        blockResolution = true;
7319                        break;
7320                    } else {
7321                        // we have a locally installed instant application; skip resolution
7322                        // but acknowledge there's an instant application available
7323                        if (DEBUG_EPHEMERAL) {
7324                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7325                        }
7326                        localInstantApp = info;
7327                        break;
7328                    }
7329                }
7330            }
7331        }
7332        // no app installed, let's see if one's available
7333        AuxiliaryResolveInfo auxiliaryResponse = null;
7334        if (!blockResolution) {
7335            if (localInstantApp == null) {
7336                // we don't have an instant app locally, resolve externally
7337                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7338                final InstantAppRequest requestObject = new InstantAppRequest(
7339                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7340                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7341                auxiliaryResponse =
7342                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7343                                mContext, mInstantAppResolverConnection, requestObject);
7344                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7345            } else {
7346                // we have an instant application locally, but, we can't admit that since
7347                // callers shouldn't be able to determine prior browsing. create a dummy
7348                // auxiliary response so the downstream code behaves as if there's an
7349                // instant application available externally. when it comes time to start
7350                // the instant application, we'll do the right thing.
7351                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7352                auxiliaryResponse = new AuxiliaryResolveInfo(
7353                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7354            }
7355        }
7356        if (auxiliaryResponse != null) {
7357            if (DEBUG_EPHEMERAL) {
7358                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7359            }
7360            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7361            final PackageSetting ps =
7362                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7363            if (ps != null) {
7364                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7365                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7366                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7367                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7368                // make sure this resolver is the default
7369                ephemeralInstaller.isDefault = true;
7370                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7371                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7372                // add a non-generic filter
7373                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7374                ephemeralInstaller.filter.addDataPath(
7375                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7376                ephemeralInstaller.isInstantAppAvailable = true;
7377                result.add(ephemeralInstaller);
7378            }
7379        }
7380        return result;
7381    }
7382
7383    private static class CrossProfileDomainInfo {
7384        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7385        ResolveInfo resolveInfo;
7386        /* Best domain verification status of the activities found in the other profile */
7387        int bestDomainVerificationStatus;
7388    }
7389
7390    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7391            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7392        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7393                sourceUserId)) {
7394            return null;
7395        }
7396        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7397                resolvedType, flags, parentUserId);
7398
7399        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7400            return null;
7401        }
7402        CrossProfileDomainInfo result = null;
7403        int size = resultTargetUser.size();
7404        for (int i = 0; i < size; i++) {
7405            ResolveInfo riTargetUser = resultTargetUser.get(i);
7406            // Intent filter verification is only for filters that specify a host. So don't return
7407            // those that handle all web uris.
7408            if (riTargetUser.handleAllWebDataURI) {
7409                continue;
7410            }
7411            String packageName = riTargetUser.activityInfo.packageName;
7412            PackageSetting ps = mSettings.mPackages.get(packageName);
7413            if (ps == null) {
7414                continue;
7415            }
7416            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7417            int status = (int)(verificationState >> 32);
7418            if (result == null) {
7419                result = new CrossProfileDomainInfo();
7420                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7421                        sourceUserId, parentUserId);
7422                result.bestDomainVerificationStatus = status;
7423            } else {
7424                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7425                        result.bestDomainVerificationStatus);
7426            }
7427        }
7428        // Don't consider matches with status NEVER across profiles.
7429        if (result != null && result.bestDomainVerificationStatus
7430                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7431            return null;
7432        }
7433        return result;
7434    }
7435
7436    /**
7437     * Verification statuses are ordered from the worse to the best, except for
7438     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7439     */
7440    private int bestDomainVerificationStatus(int status1, int status2) {
7441        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7442            return status2;
7443        }
7444        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7445            return status1;
7446        }
7447        return (int) MathUtils.max(status1, status2);
7448    }
7449
7450    private boolean isUserEnabled(int userId) {
7451        long callingId = Binder.clearCallingIdentity();
7452        try {
7453            UserInfo userInfo = sUserManager.getUserInfo(userId);
7454            return userInfo != null && userInfo.isEnabled();
7455        } finally {
7456            Binder.restoreCallingIdentity(callingId);
7457        }
7458    }
7459
7460    /**
7461     * Filter out activities with systemUserOnly flag set, when current user is not System.
7462     *
7463     * @return filtered list
7464     */
7465    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7466        if (userId == UserHandle.USER_SYSTEM) {
7467            return resolveInfos;
7468        }
7469        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7470            ResolveInfo info = resolveInfos.get(i);
7471            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7472                resolveInfos.remove(i);
7473            }
7474        }
7475        return resolveInfos;
7476    }
7477
7478    /**
7479     * Filters out ephemeral activities.
7480     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7481     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7482     *
7483     * @param resolveInfos The pre-filtered list of resolved activities
7484     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7485     *          is performed.
7486     * @return A filtered list of resolved activities.
7487     */
7488    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7489            String ephemeralPkgName) {
7490        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7491            final ResolveInfo info = resolveInfos.get(i);
7492            // TODO: When adding on-demand split support for non-instant apps, remove this check
7493            // and always apply post filtering
7494            // allow activities that are defined in the provided package
7495            if (info.activityInfo.splitName != null
7496                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7497                            info.activityInfo.splitName)) {
7498                // requested activity is defined in a split that hasn't been installed yet.
7499                // add the installer to the resolve list
7500                if (DEBUG_INSTALL) {
7501                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7502                }
7503                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7504                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7505                        info.activityInfo.packageName, info.activityInfo.splitName,
7506                        info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7507                // make sure this resolver is the default
7508                installerInfo.isDefault = true;
7509                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7510                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7511                // add a non-generic filter
7512                installerInfo.filter = new IntentFilter();
7513                // load resources from the correct package
7514                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7515                resolveInfos.set(i, installerInfo);
7516                continue;
7517            }
7518            // caller is a full app, don't need to apply any other filtering
7519            if (ephemeralPkgName == null) {
7520                continue;
7521            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7522                // caller is same app; don't need to apply any other filtering
7523                continue;
7524            }
7525            // allow activities that have been explicitly exposed to ephemeral apps
7526            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7527            if (!isEphemeralApp
7528                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7529                continue;
7530            }
7531            resolveInfos.remove(i);
7532        }
7533        return resolveInfos;
7534    }
7535
7536    /**
7537     * @param resolveInfos list of resolve infos in descending priority order
7538     * @return if the list contains a resolve info with non-negative priority
7539     */
7540    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7541        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7542    }
7543
7544    private static boolean hasWebURI(Intent intent) {
7545        if (intent.getData() == null) {
7546            return false;
7547        }
7548        final String scheme = intent.getScheme();
7549        if (TextUtils.isEmpty(scheme)) {
7550            return false;
7551        }
7552        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7553    }
7554
7555    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7556            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7557            int userId) {
7558        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7559
7560        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7561            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7562                    candidates.size());
7563        }
7564
7565        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7566        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7567        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7568        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7569        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7570        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7571
7572        synchronized (mPackages) {
7573            final int count = candidates.size();
7574            // First, try to use linked apps. Partition the candidates into four lists:
7575            // one for the final results, one for the "do not use ever", one for "undefined status"
7576            // and finally one for "browser app type".
7577            for (int n=0; n<count; n++) {
7578                ResolveInfo info = candidates.get(n);
7579                String packageName = info.activityInfo.packageName;
7580                PackageSetting ps = mSettings.mPackages.get(packageName);
7581                if (ps != null) {
7582                    // Add to the special match all list (Browser use case)
7583                    if (info.handleAllWebDataURI) {
7584                        matchAllList.add(info);
7585                        continue;
7586                    }
7587                    // Try to get the status from User settings first
7588                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7589                    int status = (int)(packedStatus >> 32);
7590                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7591                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7592                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7593                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7594                                    + " : linkgen=" + linkGeneration);
7595                        }
7596                        // Use link-enabled generation as preferredOrder, i.e.
7597                        // prefer newly-enabled over earlier-enabled.
7598                        info.preferredOrder = linkGeneration;
7599                        alwaysList.add(info);
7600                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7601                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7602                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7603                        }
7604                        neverList.add(info);
7605                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7606                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7607                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7608                        }
7609                        alwaysAskList.add(info);
7610                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7611                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7612                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7613                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7614                        }
7615                        undefinedList.add(info);
7616                    }
7617                }
7618            }
7619
7620            // We'll want to include browser possibilities in a few cases
7621            boolean includeBrowser = false;
7622
7623            // First try to add the "always" resolution(s) for the current user, if any
7624            if (alwaysList.size() > 0) {
7625                result.addAll(alwaysList);
7626            } else {
7627                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7628                result.addAll(undefinedList);
7629                // Maybe add one for the other profile.
7630                if (xpDomainInfo != null && (
7631                        xpDomainInfo.bestDomainVerificationStatus
7632                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7633                    result.add(xpDomainInfo.resolveInfo);
7634                }
7635                includeBrowser = true;
7636            }
7637
7638            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7639            // If there were 'always' entries their preferred order has been set, so we also
7640            // back that off to make the alternatives equivalent
7641            if (alwaysAskList.size() > 0) {
7642                for (ResolveInfo i : result) {
7643                    i.preferredOrder = 0;
7644                }
7645                result.addAll(alwaysAskList);
7646                includeBrowser = true;
7647            }
7648
7649            if (includeBrowser) {
7650                // Also add browsers (all of them or only the default one)
7651                if (DEBUG_DOMAIN_VERIFICATION) {
7652                    Slog.v(TAG, "   ...including browsers in candidate set");
7653                }
7654                if ((matchFlags & MATCH_ALL) != 0) {
7655                    result.addAll(matchAllList);
7656                } else {
7657                    // Browser/generic handling case.  If there's a default browser, go straight
7658                    // to that (but only if there is no other higher-priority match).
7659                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7660                    int maxMatchPrio = 0;
7661                    ResolveInfo defaultBrowserMatch = null;
7662                    final int numCandidates = matchAllList.size();
7663                    for (int n = 0; n < numCandidates; n++) {
7664                        ResolveInfo info = matchAllList.get(n);
7665                        // track the highest overall match priority...
7666                        if (info.priority > maxMatchPrio) {
7667                            maxMatchPrio = info.priority;
7668                        }
7669                        // ...and the highest-priority default browser match
7670                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7671                            if (defaultBrowserMatch == null
7672                                    || (defaultBrowserMatch.priority < info.priority)) {
7673                                if (debug) {
7674                                    Slog.v(TAG, "Considering default browser match " + info);
7675                                }
7676                                defaultBrowserMatch = info;
7677                            }
7678                        }
7679                    }
7680                    if (defaultBrowserMatch != null
7681                            && defaultBrowserMatch.priority >= maxMatchPrio
7682                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7683                    {
7684                        if (debug) {
7685                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7686                        }
7687                        result.add(defaultBrowserMatch);
7688                    } else {
7689                        result.addAll(matchAllList);
7690                    }
7691                }
7692
7693                // If there is nothing selected, add all candidates and remove the ones that the user
7694                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7695                if (result.size() == 0) {
7696                    result.addAll(candidates);
7697                    result.removeAll(neverList);
7698                }
7699            }
7700        }
7701        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7702            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7703                    result.size());
7704            for (ResolveInfo info : result) {
7705                Slog.v(TAG, "  + " + info.activityInfo);
7706            }
7707        }
7708        return result;
7709    }
7710
7711    // Returns a packed value as a long:
7712    //
7713    // high 'int'-sized word: link status: undefined/ask/never/always.
7714    // low 'int'-sized word: relative priority among 'always' results.
7715    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7716        long result = ps.getDomainVerificationStatusForUser(userId);
7717        // if none available, get the master status
7718        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7719            if (ps.getIntentFilterVerificationInfo() != null) {
7720                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7721            }
7722        }
7723        return result;
7724    }
7725
7726    private ResolveInfo querySkipCurrentProfileIntents(
7727            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7728            int flags, int sourceUserId) {
7729        if (matchingFilters != null) {
7730            int size = matchingFilters.size();
7731            for (int i = 0; i < size; i ++) {
7732                CrossProfileIntentFilter filter = matchingFilters.get(i);
7733                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7734                    // Checking if there are activities in the target user that can handle the
7735                    // intent.
7736                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7737                            resolvedType, flags, sourceUserId);
7738                    if (resolveInfo != null) {
7739                        return resolveInfo;
7740                    }
7741                }
7742            }
7743        }
7744        return null;
7745    }
7746
7747    // Return matching ResolveInfo in target user if any.
7748    private ResolveInfo queryCrossProfileIntents(
7749            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7750            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7751        if (matchingFilters != null) {
7752            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7753            // match the same intent. For performance reasons, it is better not to
7754            // run queryIntent twice for the same userId
7755            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7756            int size = matchingFilters.size();
7757            for (int i = 0; i < size; i++) {
7758                CrossProfileIntentFilter filter = matchingFilters.get(i);
7759                int targetUserId = filter.getTargetUserId();
7760                boolean skipCurrentProfile =
7761                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7762                boolean skipCurrentProfileIfNoMatchFound =
7763                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7764                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7765                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7766                    // Checking if there are activities in the target user that can handle the
7767                    // intent.
7768                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7769                            resolvedType, flags, sourceUserId);
7770                    if (resolveInfo != null) return resolveInfo;
7771                    alreadyTriedUserIds.put(targetUserId, true);
7772                }
7773            }
7774        }
7775        return null;
7776    }
7777
7778    /**
7779     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7780     * will forward the intent to the filter's target user.
7781     * Otherwise, returns null.
7782     */
7783    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7784            String resolvedType, int flags, int sourceUserId) {
7785        int targetUserId = filter.getTargetUserId();
7786        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7787                resolvedType, flags, targetUserId);
7788        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7789            // If all the matches in the target profile are suspended, return null.
7790            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7791                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7792                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7793                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7794                            targetUserId);
7795                }
7796            }
7797        }
7798        return null;
7799    }
7800
7801    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7802            int sourceUserId, int targetUserId) {
7803        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7804        long ident = Binder.clearCallingIdentity();
7805        boolean targetIsProfile;
7806        try {
7807            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7808        } finally {
7809            Binder.restoreCallingIdentity(ident);
7810        }
7811        String className;
7812        if (targetIsProfile) {
7813            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7814        } else {
7815            className = FORWARD_INTENT_TO_PARENT;
7816        }
7817        ComponentName forwardingActivityComponentName = new ComponentName(
7818                mAndroidApplication.packageName, className);
7819        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7820                sourceUserId);
7821        if (!targetIsProfile) {
7822            forwardingActivityInfo.showUserIcon = targetUserId;
7823            forwardingResolveInfo.noResourceId = true;
7824        }
7825        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7826        forwardingResolveInfo.priority = 0;
7827        forwardingResolveInfo.preferredOrder = 0;
7828        forwardingResolveInfo.match = 0;
7829        forwardingResolveInfo.isDefault = true;
7830        forwardingResolveInfo.filter = filter;
7831        forwardingResolveInfo.targetUserId = targetUserId;
7832        return forwardingResolveInfo;
7833    }
7834
7835    @Override
7836    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7837            Intent[] specifics, String[] specificTypes, Intent intent,
7838            String resolvedType, int flags, int userId) {
7839        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7840                specificTypes, intent, resolvedType, flags, userId));
7841    }
7842
7843    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7844            Intent[] specifics, String[] specificTypes, Intent intent,
7845            String resolvedType, int flags, int userId) {
7846        if (!sUserManager.exists(userId)) return Collections.emptyList();
7847        final int callingUid = Binder.getCallingUid();
7848        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7849                false /*includeInstantApps*/);
7850        enforceCrossUserPermission(callingUid, userId,
7851                false /*requireFullPermission*/, false /*checkShell*/,
7852                "query intent activity options");
7853        final String resultsAction = intent.getAction();
7854
7855        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7856                | PackageManager.GET_RESOLVED_FILTER, userId);
7857
7858        if (DEBUG_INTENT_MATCHING) {
7859            Log.v(TAG, "Query " + intent + ": " + results);
7860        }
7861
7862        int specificsPos = 0;
7863        int N;
7864
7865        // todo: note that the algorithm used here is O(N^2).  This
7866        // isn't a problem in our current environment, but if we start running
7867        // into situations where we have more than 5 or 10 matches then this
7868        // should probably be changed to something smarter...
7869
7870        // First we go through and resolve each of the specific items
7871        // that were supplied, taking care of removing any corresponding
7872        // duplicate items in the generic resolve list.
7873        if (specifics != null) {
7874            for (int i=0; i<specifics.length; i++) {
7875                final Intent sintent = specifics[i];
7876                if (sintent == null) {
7877                    continue;
7878                }
7879
7880                if (DEBUG_INTENT_MATCHING) {
7881                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7882                }
7883
7884                String action = sintent.getAction();
7885                if (resultsAction != null && resultsAction.equals(action)) {
7886                    // If this action was explicitly requested, then don't
7887                    // remove things that have it.
7888                    action = null;
7889                }
7890
7891                ResolveInfo ri = null;
7892                ActivityInfo ai = null;
7893
7894                ComponentName comp = sintent.getComponent();
7895                if (comp == null) {
7896                    ri = resolveIntent(
7897                        sintent,
7898                        specificTypes != null ? specificTypes[i] : null,
7899                            flags, userId);
7900                    if (ri == null) {
7901                        continue;
7902                    }
7903                    if (ri == mResolveInfo) {
7904                        // ACK!  Must do something better with this.
7905                    }
7906                    ai = ri.activityInfo;
7907                    comp = new ComponentName(ai.applicationInfo.packageName,
7908                            ai.name);
7909                } else {
7910                    ai = getActivityInfo(comp, flags, userId);
7911                    if (ai == null) {
7912                        continue;
7913                    }
7914                }
7915
7916                // Look for any generic query activities that are duplicates
7917                // of this specific one, and remove them from the results.
7918                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7919                N = results.size();
7920                int j;
7921                for (j=specificsPos; j<N; j++) {
7922                    ResolveInfo sri = results.get(j);
7923                    if ((sri.activityInfo.name.equals(comp.getClassName())
7924                            && sri.activityInfo.applicationInfo.packageName.equals(
7925                                    comp.getPackageName()))
7926                        || (action != null && sri.filter.matchAction(action))) {
7927                        results.remove(j);
7928                        if (DEBUG_INTENT_MATCHING) Log.v(
7929                            TAG, "Removing duplicate item from " + j
7930                            + " due to specific " + specificsPos);
7931                        if (ri == null) {
7932                            ri = sri;
7933                        }
7934                        j--;
7935                        N--;
7936                    }
7937                }
7938
7939                // Add this specific item to its proper place.
7940                if (ri == null) {
7941                    ri = new ResolveInfo();
7942                    ri.activityInfo = ai;
7943                }
7944                results.add(specificsPos, ri);
7945                ri.specificIndex = i;
7946                specificsPos++;
7947            }
7948        }
7949
7950        // Now we go through the remaining generic results and remove any
7951        // duplicate actions that are found here.
7952        N = results.size();
7953        for (int i=specificsPos; i<N-1; i++) {
7954            final ResolveInfo rii = results.get(i);
7955            if (rii.filter == null) {
7956                continue;
7957            }
7958
7959            // Iterate over all of the actions of this result's intent
7960            // filter...  typically this should be just one.
7961            final Iterator<String> it = rii.filter.actionsIterator();
7962            if (it == null) {
7963                continue;
7964            }
7965            while (it.hasNext()) {
7966                final String action = it.next();
7967                if (resultsAction != null && resultsAction.equals(action)) {
7968                    // If this action was explicitly requested, then don't
7969                    // remove things that have it.
7970                    continue;
7971                }
7972                for (int j=i+1; j<N; j++) {
7973                    final ResolveInfo rij = results.get(j);
7974                    if (rij.filter != null && rij.filter.hasAction(action)) {
7975                        results.remove(j);
7976                        if (DEBUG_INTENT_MATCHING) Log.v(
7977                            TAG, "Removing duplicate item from " + j
7978                            + " due to action " + action + " at " + i);
7979                        j--;
7980                        N--;
7981                    }
7982                }
7983            }
7984
7985            // If the caller didn't request filter information, drop it now
7986            // so we don't have to marshall/unmarshall it.
7987            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7988                rii.filter = null;
7989            }
7990        }
7991
7992        // Filter out the caller activity if so requested.
7993        if (caller != null) {
7994            N = results.size();
7995            for (int i=0; i<N; i++) {
7996                ActivityInfo ainfo = results.get(i).activityInfo;
7997                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7998                        && caller.getClassName().equals(ainfo.name)) {
7999                    results.remove(i);
8000                    break;
8001                }
8002            }
8003        }
8004
8005        // If the caller didn't request filter information,
8006        // drop them now so we don't have to
8007        // marshall/unmarshall it.
8008        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8009            N = results.size();
8010            for (int i=0; i<N; i++) {
8011                results.get(i).filter = null;
8012            }
8013        }
8014
8015        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8016        return results;
8017    }
8018
8019    @Override
8020    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8021            String resolvedType, int flags, int userId) {
8022        return new ParceledListSlice<>(
8023                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
8024    }
8025
8026    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8027            String resolvedType, int flags, int userId) {
8028        if (!sUserManager.exists(userId)) return Collections.emptyList();
8029        final int callingUid = Binder.getCallingUid();
8030        enforceCrossUserPermission(callingUid, userId,
8031                false /*requireFullPermission*/, false /*checkShell*/,
8032                "query intent receivers");
8033        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8034        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8035                false /*includeInstantApps*/);
8036        ComponentName comp = intent.getComponent();
8037        if (comp == null) {
8038            if (intent.getSelector() != null) {
8039                intent = intent.getSelector();
8040                comp = intent.getComponent();
8041            }
8042        }
8043        if (comp != null) {
8044            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8045            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8046            if (ai != null) {
8047                // When specifying an explicit component, we prevent the activity from being
8048                // used when either 1) the calling package is normal and the activity is within
8049                // an instant application or 2) the calling package is ephemeral and the
8050                // activity is not visible to instant applications.
8051                final boolean matchInstantApp =
8052                        (flags & PackageManager.MATCH_INSTANT) != 0;
8053                final boolean matchVisibleToInstantAppOnly =
8054                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8055                final boolean matchExplicitlyVisibleOnly =
8056                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8057                final boolean isCallerInstantApp =
8058                        instantAppPkgName != null;
8059                final boolean isTargetSameInstantApp =
8060                        comp.getPackageName().equals(instantAppPkgName);
8061                final boolean isTargetInstantApp =
8062                        (ai.applicationInfo.privateFlags
8063                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8064                final boolean isTargetVisibleToInstantApp =
8065                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8066                final boolean isTargetExplicitlyVisibleToInstantApp =
8067                        isTargetVisibleToInstantApp
8068                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8069                final boolean isTargetHiddenFromInstantApp =
8070                        !isTargetVisibleToInstantApp
8071                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8072                final boolean blockResolution =
8073                        !isTargetSameInstantApp
8074                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8075                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8076                                        && isTargetHiddenFromInstantApp));
8077                if (!blockResolution) {
8078                    ResolveInfo ri = new ResolveInfo();
8079                    ri.activityInfo = ai;
8080                    list.add(ri);
8081                }
8082            }
8083            return applyPostResolutionFilter(list, instantAppPkgName);
8084        }
8085
8086        // reader
8087        synchronized (mPackages) {
8088            String pkgName = intent.getPackage();
8089            if (pkgName == null) {
8090                final List<ResolveInfo> result =
8091                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8092                return applyPostResolutionFilter(result, instantAppPkgName);
8093            }
8094            final PackageParser.Package pkg = mPackages.get(pkgName);
8095            if (pkg != null) {
8096                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8097                        intent, resolvedType, flags, pkg.receivers, userId);
8098                return applyPostResolutionFilter(result, instantAppPkgName);
8099            }
8100            return Collections.emptyList();
8101        }
8102    }
8103
8104    @Override
8105    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8106        final int callingUid = Binder.getCallingUid();
8107        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8108    }
8109
8110    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8111            int userId, int callingUid) {
8112        if (!sUserManager.exists(userId)) return null;
8113        flags = updateFlagsForResolve(
8114                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8115        List<ResolveInfo> query = queryIntentServicesInternal(
8116                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8117        if (query != null) {
8118            if (query.size() >= 1) {
8119                // If there is more than one service with the same priority,
8120                // just arbitrarily pick the first one.
8121                return query.get(0);
8122            }
8123        }
8124        return null;
8125    }
8126
8127    @Override
8128    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8129            String resolvedType, int flags, int userId) {
8130        final int callingUid = Binder.getCallingUid();
8131        return new ParceledListSlice<>(queryIntentServicesInternal(
8132                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8133    }
8134
8135    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8136            String resolvedType, int flags, int userId, int callingUid,
8137            boolean includeInstantApps) {
8138        if (!sUserManager.exists(userId)) return Collections.emptyList();
8139        enforceCrossUserPermission(callingUid, userId,
8140                false /*requireFullPermission*/, false /*checkShell*/,
8141                "query intent receivers");
8142        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8143        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8144        ComponentName comp = intent.getComponent();
8145        if (comp == null) {
8146            if (intent.getSelector() != null) {
8147                intent = intent.getSelector();
8148                comp = intent.getComponent();
8149            }
8150        }
8151        if (comp != null) {
8152            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8153            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8154            if (si != null) {
8155                // When specifying an explicit component, we prevent the service from being
8156                // used when either 1) the service is in an instant application and the
8157                // caller is not the same instant application or 2) the calling package is
8158                // ephemeral and the activity is not visible to ephemeral applications.
8159                final boolean matchInstantApp =
8160                        (flags & PackageManager.MATCH_INSTANT) != 0;
8161                final boolean matchVisibleToInstantAppOnly =
8162                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8163                final boolean isCallerInstantApp =
8164                        instantAppPkgName != null;
8165                final boolean isTargetSameInstantApp =
8166                        comp.getPackageName().equals(instantAppPkgName);
8167                final boolean isTargetInstantApp =
8168                        (si.applicationInfo.privateFlags
8169                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8170                final boolean isTargetHiddenFromInstantApp =
8171                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8172                final boolean blockResolution =
8173                        !isTargetSameInstantApp
8174                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8175                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8176                                        && isTargetHiddenFromInstantApp));
8177                if (!blockResolution) {
8178                    final ResolveInfo ri = new ResolveInfo();
8179                    ri.serviceInfo = si;
8180                    list.add(ri);
8181                }
8182            }
8183            return list;
8184        }
8185
8186        // reader
8187        synchronized (mPackages) {
8188            String pkgName = intent.getPackage();
8189            if (pkgName == null) {
8190                return applyPostServiceResolutionFilter(
8191                        mServices.queryIntent(intent, resolvedType, flags, userId),
8192                        instantAppPkgName);
8193            }
8194            final PackageParser.Package pkg = mPackages.get(pkgName);
8195            if (pkg != null) {
8196                return applyPostServiceResolutionFilter(
8197                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8198                                userId),
8199                        instantAppPkgName);
8200            }
8201            return Collections.emptyList();
8202        }
8203    }
8204
8205    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8206            String instantAppPkgName) {
8207        // TODO: When adding on-demand split support for non-instant apps, remove this check
8208        // and always apply post filtering
8209        if (instantAppPkgName == null) {
8210            return resolveInfos;
8211        }
8212        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8213            final ResolveInfo info = resolveInfos.get(i);
8214            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8215            // allow services that are defined in the provided package
8216            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8217                if (info.serviceInfo.splitName != null
8218                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8219                                info.serviceInfo.splitName)) {
8220                    // requested service is defined in a split that hasn't been installed yet.
8221                    // add the installer to the resolve list
8222                    if (DEBUG_EPHEMERAL) {
8223                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8224                    }
8225                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8226                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8227                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8228                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
8229                    // make sure this resolver is the default
8230                    installerInfo.isDefault = true;
8231                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8232                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8233                    // add a non-generic filter
8234                    installerInfo.filter = new IntentFilter();
8235                    // load resources from the correct package
8236                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8237                    resolveInfos.set(i, installerInfo);
8238                }
8239                continue;
8240            }
8241            // allow services that have been explicitly exposed to ephemeral apps
8242            if (!isEphemeralApp
8243                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8244                continue;
8245            }
8246            resolveInfos.remove(i);
8247        }
8248        return resolveInfos;
8249    }
8250
8251    @Override
8252    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8253            String resolvedType, int flags, int userId) {
8254        return new ParceledListSlice<>(
8255                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8256    }
8257
8258    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8259            Intent intent, String resolvedType, int flags, int userId) {
8260        if (!sUserManager.exists(userId)) return Collections.emptyList();
8261        final int callingUid = Binder.getCallingUid();
8262        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8263        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8264                false /*includeInstantApps*/);
8265        ComponentName comp = intent.getComponent();
8266        if (comp == null) {
8267            if (intent.getSelector() != null) {
8268                intent = intent.getSelector();
8269                comp = intent.getComponent();
8270            }
8271        }
8272        if (comp != null) {
8273            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8274            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8275            if (pi != null) {
8276                // When specifying an explicit component, we prevent the provider from being
8277                // used when either 1) the provider is in an instant application and the
8278                // caller is not the same instant application or 2) the calling package is an
8279                // instant application and the provider is not visible to instant applications.
8280                final boolean matchInstantApp =
8281                        (flags & PackageManager.MATCH_INSTANT) != 0;
8282                final boolean matchVisibleToInstantAppOnly =
8283                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8284                final boolean isCallerInstantApp =
8285                        instantAppPkgName != null;
8286                final boolean isTargetSameInstantApp =
8287                        comp.getPackageName().equals(instantAppPkgName);
8288                final boolean isTargetInstantApp =
8289                        (pi.applicationInfo.privateFlags
8290                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8291                final boolean isTargetHiddenFromInstantApp =
8292                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8293                final boolean blockResolution =
8294                        !isTargetSameInstantApp
8295                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8296                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8297                                        && isTargetHiddenFromInstantApp));
8298                if (!blockResolution) {
8299                    final ResolveInfo ri = new ResolveInfo();
8300                    ri.providerInfo = pi;
8301                    list.add(ri);
8302                }
8303            }
8304            return list;
8305        }
8306
8307        // reader
8308        synchronized (mPackages) {
8309            String pkgName = intent.getPackage();
8310            if (pkgName == null) {
8311                return applyPostContentProviderResolutionFilter(
8312                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8313                        instantAppPkgName);
8314            }
8315            final PackageParser.Package pkg = mPackages.get(pkgName);
8316            if (pkg != null) {
8317                return applyPostContentProviderResolutionFilter(
8318                        mProviders.queryIntentForPackage(
8319                        intent, resolvedType, flags, pkg.providers, userId),
8320                        instantAppPkgName);
8321            }
8322            return Collections.emptyList();
8323        }
8324    }
8325
8326    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8327            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8328        // TODO: When adding on-demand split support for non-instant applications, remove
8329        // this check and always apply post filtering
8330        if (instantAppPkgName == null) {
8331            return resolveInfos;
8332        }
8333        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8334            final ResolveInfo info = resolveInfos.get(i);
8335            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8336            // allow providers that are defined in the provided package
8337            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8338                if (info.providerInfo.splitName != null
8339                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8340                                info.providerInfo.splitName)) {
8341                    // requested provider is defined in a split that hasn't been installed yet.
8342                    // add the installer to the resolve list
8343                    if (DEBUG_EPHEMERAL) {
8344                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8345                    }
8346                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8347                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8348                            info.providerInfo.packageName, info.providerInfo.splitName,
8349                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8350                    // make sure this resolver is the default
8351                    installerInfo.isDefault = true;
8352                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8353                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8354                    // add a non-generic filter
8355                    installerInfo.filter = new IntentFilter();
8356                    // load resources from the correct package
8357                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8358                    resolveInfos.set(i, installerInfo);
8359                }
8360                continue;
8361            }
8362            // allow providers that have been explicitly exposed to instant applications
8363            if (!isEphemeralApp
8364                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8365                continue;
8366            }
8367            resolveInfos.remove(i);
8368        }
8369        return resolveInfos;
8370    }
8371
8372    @Override
8373    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8374        final int callingUid = Binder.getCallingUid();
8375        if (getInstantAppPackageName(callingUid) != null) {
8376            return ParceledListSlice.emptyList();
8377        }
8378        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8379        flags = updateFlagsForPackage(flags, userId, null);
8380        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8381        enforceCrossUserPermission(callingUid, userId,
8382                true /* requireFullPermission */, false /* checkShell */,
8383                "get installed packages");
8384
8385        // writer
8386        synchronized (mPackages) {
8387            ArrayList<PackageInfo> list;
8388            if (listUninstalled) {
8389                list = new ArrayList<>(mSettings.mPackages.size());
8390                for (PackageSetting ps : mSettings.mPackages.values()) {
8391                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8392                        continue;
8393                    }
8394                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8395                        return null;
8396                    }
8397                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8398                    if (pi != null) {
8399                        list.add(pi);
8400                    }
8401                }
8402            } else {
8403                list = new ArrayList<>(mPackages.size());
8404                for (PackageParser.Package p : mPackages.values()) {
8405                    final PackageSetting ps = (PackageSetting) p.mExtras;
8406                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8407                        continue;
8408                    }
8409                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8410                        return null;
8411                    }
8412                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8413                            p.mExtras, flags, userId);
8414                    if (pi != null) {
8415                        list.add(pi);
8416                    }
8417                }
8418            }
8419
8420            return new ParceledListSlice<>(list);
8421        }
8422    }
8423
8424    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8425            String[] permissions, boolean[] tmp, int flags, int userId) {
8426        int numMatch = 0;
8427        final PermissionsState permissionsState = ps.getPermissionsState();
8428        for (int i=0; i<permissions.length; i++) {
8429            final String permission = permissions[i];
8430            if (permissionsState.hasPermission(permission, userId)) {
8431                tmp[i] = true;
8432                numMatch++;
8433            } else {
8434                tmp[i] = false;
8435            }
8436        }
8437        if (numMatch == 0) {
8438            return;
8439        }
8440        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8441
8442        // The above might return null in cases of uninstalled apps or install-state
8443        // skew across users/profiles.
8444        if (pi != null) {
8445            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8446                if (numMatch == permissions.length) {
8447                    pi.requestedPermissions = permissions;
8448                } else {
8449                    pi.requestedPermissions = new String[numMatch];
8450                    numMatch = 0;
8451                    for (int i=0; i<permissions.length; i++) {
8452                        if (tmp[i]) {
8453                            pi.requestedPermissions[numMatch] = permissions[i];
8454                            numMatch++;
8455                        }
8456                    }
8457                }
8458            }
8459            list.add(pi);
8460        }
8461    }
8462
8463    @Override
8464    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8465            String[] permissions, int flags, int userId) {
8466        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8467        flags = updateFlagsForPackage(flags, userId, permissions);
8468        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8469                true /* requireFullPermission */, false /* checkShell */,
8470                "get packages holding permissions");
8471        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8472
8473        // writer
8474        synchronized (mPackages) {
8475            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8476            boolean[] tmpBools = new boolean[permissions.length];
8477            if (listUninstalled) {
8478                for (PackageSetting ps : mSettings.mPackages.values()) {
8479                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8480                            userId);
8481                }
8482            } else {
8483                for (PackageParser.Package pkg : mPackages.values()) {
8484                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8485                    if (ps != null) {
8486                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8487                                userId);
8488                    }
8489                }
8490            }
8491
8492            return new ParceledListSlice<PackageInfo>(list);
8493        }
8494    }
8495
8496    @Override
8497    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8498        final int callingUid = Binder.getCallingUid();
8499        if (getInstantAppPackageName(callingUid) != null) {
8500            return ParceledListSlice.emptyList();
8501        }
8502        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8503        flags = updateFlagsForApplication(flags, userId, null);
8504        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8505
8506        // writer
8507        synchronized (mPackages) {
8508            ArrayList<ApplicationInfo> list;
8509            if (listUninstalled) {
8510                list = new ArrayList<>(mSettings.mPackages.size());
8511                for (PackageSetting ps : mSettings.mPackages.values()) {
8512                    ApplicationInfo ai;
8513                    int effectiveFlags = flags;
8514                    if (ps.isSystem()) {
8515                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8516                    }
8517                    if (ps.pkg != null) {
8518                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8519                            continue;
8520                        }
8521                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8522                            return null;
8523                        }
8524                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8525                                ps.readUserState(userId), userId);
8526                        if (ai != null) {
8527                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8528                        }
8529                    } else {
8530                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8531                        // and already converts to externally visible package name
8532                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8533                                callingUid, effectiveFlags, userId);
8534                    }
8535                    if (ai != null) {
8536                        list.add(ai);
8537                    }
8538                }
8539            } else {
8540                list = new ArrayList<>(mPackages.size());
8541                for (PackageParser.Package p : mPackages.values()) {
8542                    if (p.mExtras != null) {
8543                        PackageSetting ps = (PackageSetting) p.mExtras;
8544                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8545                            continue;
8546                        }
8547                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8548                            return null;
8549                        }
8550                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8551                                ps.readUserState(userId), userId);
8552                        if (ai != null) {
8553                            ai.packageName = resolveExternalPackageNameLPr(p);
8554                            list.add(ai);
8555                        }
8556                    }
8557                }
8558            }
8559
8560            return new ParceledListSlice<>(list);
8561        }
8562    }
8563
8564    @Override
8565    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8566        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8567            return null;
8568        }
8569        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8570            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8571                    "getEphemeralApplications");
8572        }
8573        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8574                true /* requireFullPermission */, false /* checkShell */,
8575                "getEphemeralApplications");
8576        synchronized (mPackages) {
8577            List<InstantAppInfo> instantApps = mInstantAppRegistry
8578                    .getInstantAppsLPr(userId);
8579            if (instantApps != null) {
8580                return new ParceledListSlice<>(instantApps);
8581            }
8582        }
8583        return null;
8584    }
8585
8586    @Override
8587    public boolean isInstantApp(String packageName, int userId) {
8588        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8589                true /* requireFullPermission */, false /* checkShell */,
8590                "isInstantApp");
8591        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8592            return false;
8593        }
8594
8595        synchronized (mPackages) {
8596            int callingUid = Binder.getCallingUid();
8597            if (Process.isIsolated(callingUid)) {
8598                callingUid = mIsolatedOwners.get(callingUid);
8599            }
8600            final PackageSetting ps = mSettings.mPackages.get(packageName);
8601            PackageParser.Package pkg = mPackages.get(packageName);
8602            final boolean returnAllowed =
8603                    ps != null
8604                    && (isCallerSameApp(packageName, callingUid)
8605                            || canViewInstantApps(callingUid, userId)
8606                            || mInstantAppRegistry.isInstantAccessGranted(
8607                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8608            if (returnAllowed) {
8609                return ps.getInstantApp(userId);
8610            }
8611        }
8612        return false;
8613    }
8614
8615    @Override
8616    public byte[] getInstantAppCookie(String packageName, int userId) {
8617        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8618            return null;
8619        }
8620
8621        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8622                true /* requireFullPermission */, false /* checkShell */,
8623                "getInstantAppCookie");
8624        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8625            return null;
8626        }
8627        synchronized (mPackages) {
8628            return mInstantAppRegistry.getInstantAppCookieLPw(
8629                    packageName, userId);
8630        }
8631    }
8632
8633    @Override
8634    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8635        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8636            return true;
8637        }
8638
8639        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8640                true /* requireFullPermission */, true /* checkShell */,
8641                "setInstantAppCookie");
8642        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8643            return false;
8644        }
8645        synchronized (mPackages) {
8646            return mInstantAppRegistry.setInstantAppCookieLPw(
8647                    packageName, cookie, userId);
8648        }
8649    }
8650
8651    @Override
8652    public Bitmap getInstantAppIcon(String packageName, int userId) {
8653        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8654            return null;
8655        }
8656
8657        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8658            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8659                    "getInstantAppIcon");
8660        }
8661        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8662                true /* requireFullPermission */, false /* checkShell */,
8663                "getInstantAppIcon");
8664
8665        synchronized (mPackages) {
8666            return mInstantAppRegistry.getInstantAppIconLPw(
8667                    packageName, userId);
8668        }
8669    }
8670
8671    private boolean isCallerSameApp(String packageName, int uid) {
8672        PackageParser.Package pkg = mPackages.get(packageName);
8673        return pkg != null
8674                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8675    }
8676
8677    @Override
8678    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8679        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8680            return ParceledListSlice.emptyList();
8681        }
8682        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8683    }
8684
8685    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8686        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8687
8688        // reader
8689        synchronized (mPackages) {
8690            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8691            final int userId = UserHandle.getCallingUserId();
8692            while (i.hasNext()) {
8693                final PackageParser.Package p = i.next();
8694                if (p.applicationInfo == null) continue;
8695
8696                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8697                        && !p.applicationInfo.isDirectBootAware();
8698                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8699                        && p.applicationInfo.isDirectBootAware();
8700
8701                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8702                        && (!mSafeMode || isSystemApp(p))
8703                        && (matchesUnaware || matchesAware)) {
8704                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8705                    if (ps != null) {
8706                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8707                                ps.readUserState(userId), userId);
8708                        if (ai != null) {
8709                            finalList.add(ai);
8710                        }
8711                    }
8712                }
8713            }
8714        }
8715
8716        return finalList;
8717    }
8718
8719    @Override
8720    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8721        if (!sUserManager.exists(userId)) return null;
8722        flags = updateFlagsForComponent(flags, userId, name);
8723        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8724        // reader
8725        synchronized (mPackages) {
8726            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8727            PackageSetting ps = provider != null
8728                    ? mSettings.mPackages.get(provider.owner.packageName)
8729                    : null;
8730            if (ps != null) {
8731                final boolean isInstantApp = ps.getInstantApp(userId);
8732                // normal application; filter out instant application provider
8733                if (instantAppPkgName == null && isInstantApp) {
8734                    return null;
8735                }
8736                // instant application; filter out other instant applications
8737                if (instantAppPkgName != null
8738                        && isInstantApp
8739                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8740                    return null;
8741                }
8742                // instant application; filter out non-exposed provider
8743                if (instantAppPkgName != null
8744                        && !isInstantApp
8745                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8746                    return null;
8747                }
8748                // provider not enabled
8749                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8750                    return null;
8751                }
8752                return PackageParser.generateProviderInfo(
8753                        provider, flags, ps.readUserState(userId), userId);
8754            }
8755            return null;
8756        }
8757    }
8758
8759    /**
8760     * @deprecated
8761     */
8762    @Deprecated
8763    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8764        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8765            return;
8766        }
8767        // reader
8768        synchronized (mPackages) {
8769            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8770                    .entrySet().iterator();
8771            final int userId = UserHandle.getCallingUserId();
8772            while (i.hasNext()) {
8773                Map.Entry<String, PackageParser.Provider> entry = i.next();
8774                PackageParser.Provider p = entry.getValue();
8775                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8776
8777                if (ps != null && p.syncable
8778                        && (!mSafeMode || (p.info.applicationInfo.flags
8779                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8780                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8781                            ps.readUserState(userId), userId);
8782                    if (info != null) {
8783                        outNames.add(entry.getKey());
8784                        outInfo.add(info);
8785                    }
8786                }
8787            }
8788        }
8789    }
8790
8791    @Override
8792    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8793            int uid, int flags, String metaDataKey) {
8794        final int callingUid = Binder.getCallingUid();
8795        final int userId = processName != null ? UserHandle.getUserId(uid)
8796                : UserHandle.getCallingUserId();
8797        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8798        flags = updateFlagsForComponent(flags, userId, processName);
8799        ArrayList<ProviderInfo> finalList = null;
8800        // reader
8801        synchronized (mPackages) {
8802            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8803            while (i.hasNext()) {
8804                final PackageParser.Provider p = i.next();
8805                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8806                if (ps != null && p.info.authority != null
8807                        && (processName == null
8808                                || (p.info.processName.equals(processName)
8809                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8810                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8811
8812                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8813                    // parameter.
8814                    if (metaDataKey != null
8815                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8816                        continue;
8817                    }
8818                    final ComponentName component =
8819                            new ComponentName(p.info.packageName, p.info.name);
8820                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8821                        continue;
8822                    }
8823                    if (finalList == null) {
8824                        finalList = new ArrayList<ProviderInfo>(3);
8825                    }
8826                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8827                            ps.readUserState(userId), userId);
8828                    if (info != null) {
8829                        finalList.add(info);
8830                    }
8831                }
8832            }
8833        }
8834
8835        if (finalList != null) {
8836            Collections.sort(finalList, mProviderInitOrderSorter);
8837            return new ParceledListSlice<ProviderInfo>(finalList);
8838        }
8839
8840        return ParceledListSlice.emptyList();
8841    }
8842
8843    @Override
8844    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8845        // reader
8846        synchronized (mPackages) {
8847            final int callingUid = Binder.getCallingUid();
8848            final int callingUserId = UserHandle.getUserId(callingUid);
8849            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8850            if (ps == null) return null;
8851            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8852                return null;
8853            }
8854            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8855            return PackageParser.generateInstrumentationInfo(i, flags);
8856        }
8857    }
8858
8859    @Override
8860    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8861            String targetPackage, int flags) {
8862        final int callingUid = Binder.getCallingUid();
8863        final int callingUserId = UserHandle.getUserId(callingUid);
8864        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8865        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8866            return ParceledListSlice.emptyList();
8867        }
8868        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8869    }
8870
8871    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8872            int flags) {
8873        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8874
8875        // reader
8876        synchronized (mPackages) {
8877            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8878            while (i.hasNext()) {
8879                final PackageParser.Instrumentation p = i.next();
8880                if (targetPackage == null
8881                        || targetPackage.equals(p.info.targetPackage)) {
8882                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8883                            flags);
8884                    if (ii != null) {
8885                        finalList.add(ii);
8886                    }
8887                }
8888            }
8889        }
8890
8891        return finalList;
8892    }
8893
8894    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8895        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8896        try {
8897            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8898        } finally {
8899            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8900        }
8901    }
8902
8903    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8904        final File[] files = dir.listFiles();
8905        if (ArrayUtils.isEmpty(files)) {
8906            Log.d(TAG, "No files in app dir " + dir);
8907            return;
8908        }
8909
8910        if (DEBUG_PACKAGE_SCANNING) {
8911            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8912                    + " flags=0x" + Integer.toHexString(parseFlags));
8913        }
8914        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8915                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8916                mParallelPackageParserCallback);
8917
8918        // Submit files for parsing in parallel
8919        int fileCount = 0;
8920        for (File file : files) {
8921            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8922                    && !PackageInstallerService.isStageName(file.getName());
8923            if (!isPackage) {
8924                // Ignore entries which are not packages
8925                continue;
8926            }
8927            parallelPackageParser.submit(file, parseFlags);
8928            fileCount++;
8929        }
8930
8931        // Process results one by one
8932        for (; fileCount > 0; fileCount--) {
8933            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8934            Throwable throwable = parseResult.throwable;
8935            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8936
8937            if (throwable == null) {
8938                // Static shared libraries have synthetic package names
8939                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8940                    renameStaticSharedLibraryPackage(parseResult.pkg);
8941                }
8942                try {
8943                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8944                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8945                                currentTime, null);
8946                    }
8947                } catch (PackageManagerException e) {
8948                    errorCode = e.error;
8949                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8950                }
8951            } else if (throwable instanceof PackageParser.PackageParserException) {
8952                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8953                        throwable;
8954                errorCode = e.error;
8955                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8956            } else {
8957                throw new IllegalStateException("Unexpected exception occurred while parsing "
8958                        + parseResult.scanFile, throwable);
8959            }
8960
8961            // Delete invalid userdata apps
8962            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8963                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8964                logCriticalInfo(Log.WARN,
8965                        "Deleting invalid package at " + parseResult.scanFile);
8966                removeCodePathLI(parseResult.scanFile);
8967            }
8968        }
8969        parallelPackageParser.close();
8970    }
8971
8972    private static File getSettingsProblemFile() {
8973        File dataDir = Environment.getDataDirectory();
8974        File systemDir = new File(dataDir, "system");
8975        File fname = new File(systemDir, "uiderrors.txt");
8976        return fname;
8977    }
8978
8979    static void reportSettingsProblem(int priority, String msg) {
8980        logCriticalInfo(priority, msg);
8981    }
8982
8983    public static void logCriticalInfo(int priority, String msg) {
8984        Slog.println(priority, TAG, msg);
8985        EventLogTags.writePmCriticalInfo(msg);
8986        try {
8987            File fname = getSettingsProblemFile();
8988            FileOutputStream out = new FileOutputStream(fname, true);
8989            PrintWriter pw = new FastPrintWriter(out);
8990            SimpleDateFormat formatter = new SimpleDateFormat();
8991            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8992            pw.println(dateString + ": " + msg);
8993            pw.close();
8994            FileUtils.setPermissions(
8995                    fname.toString(),
8996                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8997                    -1, -1);
8998        } catch (java.io.IOException e) {
8999        }
9000    }
9001
9002    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9003        if (srcFile.isDirectory()) {
9004            final File baseFile = new File(pkg.baseCodePath);
9005            long maxModifiedTime = baseFile.lastModified();
9006            if (pkg.splitCodePaths != null) {
9007                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9008                    final File splitFile = new File(pkg.splitCodePaths[i]);
9009                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9010                }
9011            }
9012            return maxModifiedTime;
9013        }
9014        return srcFile.lastModified();
9015    }
9016
9017    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9018            final int policyFlags) throws PackageManagerException {
9019        // When upgrading from pre-N MR1, verify the package time stamp using the package
9020        // directory and not the APK file.
9021        final long lastModifiedTime = mIsPreNMR1Upgrade
9022                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9023        if (ps != null
9024                && ps.codePath.equals(srcFile)
9025                && ps.timeStamp == lastModifiedTime
9026                && !isCompatSignatureUpdateNeeded(pkg)
9027                && !isRecoverSignatureUpdateNeeded(pkg)) {
9028            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9029            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9030            ArraySet<PublicKey> signingKs;
9031            synchronized (mPackages) {
9032                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9033            }
9034            if (ps.signatures.mSignatures != null
9035                    && ps.signatures.mSignatures.length != 0
9036                    && signingKs != null) {
9037                // Optimization: reuse the existing cached certificates
9038                // if the package appears to be unchanged.
9039                pkg.mSignatures = ps.signatures.mSignatures;
9040                pkg.mSigningKeys = signingKs;
9041                return;
9042            }
9043
9044            Slog.w(TAG, "PackageSetting for " + ps.name
9045                    + " is missing signatures.  Collecting certs again to recover them.");
9046        } else {
9047            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9048        }
9049
9050        try {
9051            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9052            PackageParser.collectCertificates(pkg, policyFlags);
9053        } catch (PackageParserException e) {
9054            throw PackageManagerException.from(e);
9055        } finally {
9056            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9057        }
9058    }
9059
9060    /**
9061     *  Traces a package scan.
9062     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9063     */
9064    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9065            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9066        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9067        try {
9068            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9069        } finally {
9070            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9071        }
9072    }
9073
9074    /**
9075     *  Scans a package and returns the newly parsed package.
9076     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9077     */
9078    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9079            long currentTime, UserHandle user) throws PackageManagerException {
9080        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9081        PackageParser pp = new PackageParser();
9082        pp.setSeparateProcesses(mSeparateProcesses);
9083        pp.setOnlyCoreApps(mOnlyCore);
9084        pp.setDisplayMetrics(mMetrics);
9085        pp.setCallback(mPackageParserCallback);
9086
9087        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9088            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9089        }
9090
9091        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9092        final PackageParser.Package pkg;
9093        try {
9094            pkg = pp.parsePackage(scanFile, parseFlags);
9095        } catch (PackageParserException e) {
9096            throw PackageManagerException.from(e);
9097        } finally {
9098            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9099        }
9100
9101        // Static shared libraries have synthetic package names
9102        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9103            renameStaticSharedLibraryPackage(pkg);
9104        }
9105
9106        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9107    }
9108
9109    /**
9110     *  Scans a package and returns the newly parsed package.
9111     *  @throws PackageManagerException on a parse error.
9112     */
9113    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9114            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9115            throws PackageManagerException {
9116        // If the package has children and this is the first dive in the function
9117        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9118        // packages (parent and children) would be successfully scanned before the
9119        // actual scan since scanning mutates internal state and we want to atomically
9120        // install the package and its children.
9121        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9122            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9123                scanFlags |= SCAN_CHECK_ONLY;
9124            }
9125        } else {
9126            scanFlags &= ~SCAN_CHECK_ONLY;
9127        }
9128
9129        // Scan the parent
9130        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9131                scanFlags, currentTime, user);
9132
9133        // Scan the children
9134        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9135        for (int i = 0; i < childCount; i++) {
9136            PackageParser.Package childPackage = pkg.childPackages.get(i);
9137            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9138                    currentTime, user);
9139        }
9140
9141
9142        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9143            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9144        }
9145
9146        return scannedPkg;
9147    }
9148
9149    /**
9150     *  Scans a package and returns the newly parsed package.
9151     *  @throws PackageManagerException on a parse error.
9152     */
9153    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9154            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9155            throws PackageManagerException {
9156        PackageSetting ps = null;
9157        PackageSetting updatedPkg;
9158        // reader
9159        synchronized (mPackages) {
9160            // Look to see if we already know about this package.
9161            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9162            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9163                // This package has been renamed to its original name.  Let's
9164                // use that.
9165                ps = mSettings.getPackageLPr(oldName);
9166            }
9167            // If there was no original package, see one for the real package name.
9168            if (ps == null) {
9169                ps = mSettings.getPackageLPr(pkg.packageName);
9170            }
9171            // Check to see if this package could be hiding/updating a system
9172            // package.  Must look for it either under the original or real
9173            // package name depending on our state.
9174            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9175            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9176
9177            // If this is a package we don't know about on the system partition, we
9178            // may need to remove disabled child packages on the system partition
9179            // or may need to not add child packages if the parent apk is updated
9180            // on the data partition and no longer defines this child package.
9181            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9182                // If this is a parent package for an updated system app and this system
9183                // app got an OTA update which no longer defines some of the child packages
9184                // we have to prune them from the disabled system packages.
9185                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9186                if (disabledPs != null) {
9187                    final int scannedChildCount = (pkg.childPackages != null)
9188                            ? pkg.childPackages.size() : 0;
9189                    final int disabledChildCount = disabledPs.childPackageNames != null
9190                            ? disabledPs.childPackageNames.size() : 0;
9191                    for (int i = 0; i < disabledChildCount; i++) {
9192                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9193                        boolean disabledPackageAvailable = false;
9194                        for (int j = 0; j < scannedChildCount; j++) {
9195                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9196                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9197                                disabledPackageAvailable = true;
9198                                break;
9199                            }
9200                         }
9201                         if (!disabledPackageAvailable) {
9202                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9203                         }
9204                    }
9205                }
9206            }
9207        }
9208
9209        final boolean isUpdatedPkg = updatedPkg != null;
9210        final boolean isUpdatedSystemPkg = isUpdatedPkg
9211                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9212        boolean isUpdatedPkgBetter = false;
9213        // First check if this is a system package that may involve an update
9214        if (isUpdatedSystemPkg) {
9215            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9216            // it needs to drop FLAG_PRIVILEGED.
9217            if (locationIsPrivileged(scanFile)) {
9218                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9219            } else {
9220                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9221            }
9222
9223            if (ps != null && !ps.codePath.equals(scanFile)) {
9224                // The path has changed from what was last scanned...  check the
9225                // version of the new path against what we have stored to determine
9226                // what to do.
9227                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9228                if (pkg.mVersionCode <= ps.versionCode) {
9229                    // The system package has been updated and the code path does not match
9230                    // Ignore entry. Skip it.
9231                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9232                            + " ignored: updated version " + ps.versionCode
9233                            + " better than this " + pkg.mVersionCode);
9234                    if (!updatedPkg.codePath.equals(scanFile)) {
9235                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9236                                + ps.name + " changing from " + updatedPkg.codePathString
9237                                + " to " + scanFile);
9238                        updatedPkg.codePath = scanFile;
9239                        updatedPkg.codePathString = scanFile.toString();
9240                        updatedPkg.resourcePath = scanFile;
9241                        updatedPkg.resourcePathString = scanFile.toString();
9242                    }
9243                    updatedPkg.pkg = pkg;
9244                    updatedPkg.versionCode = pkg.mVersionCode;
9245
9246                    // Update the disabled system child packages to point to the package too.
9247                    final int childCount = updatedPkg.childPackageNames != null
9248                            ? updatedPkg.childPackageNames.size() : 0;
9249                    for (int i = 0; i < childCount; i++) {
9250                        String childPackageName = updatedPkg.childPackageNames.get(i);
9251                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9252                                childPackageName);
9253                        if (updatedChildPkg != null) {
9254                            updatedChildPkg.pkg = pkg;
9255                            updatedChildPkg.versionCode = pkg.mVersionCode;
9256                        }
9257                    }
9258                } else {
9259                    // The current app on the system partition is better than
9260                    // what we have updated to on the data partition; switch
9261                    // back to the system partition version.
9262                    // At this point, its safely assumed that package installation for
9263                    // apps in system partition will go through. If not there won't be a working
9264                    // version of the app
9265                    // writer
9266                    synchronized (mPackages) {
9267                        // Just remove the loaded entries from package lists.
9268                        mPackages.remove(ps.name);
9269                    }
9270
9271                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9272                            + " reverting from " + ps.codePathString
9273                            + ": new version " + pkg.mVersionCode
9274                            + " better than installed " + ps.versionCode);
9275
9276                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9277                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9278                    synchronized (mInstallLock) {
9279                        args.cleanUpResourcesLI();
9280                    }
9281                    synchronized (mPackages) {
9282                        mSettings.enableSystemPackageLPw(ps.name);
9283                    }
9284                    isUpdatedPkgBetter = true;
9285                }
9286            }
9287        }
9288
9289        String resourcePath = null;
9290        String baseResourcePath = null;
9291        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9292            if (ps != null && ps.resourcePathString != null) {
9293                resourcePath = ps.resourcePathString;
9294                baseResourcePath = ps.resourcePathString;
9295            } else {
9296                // Should not happen at all. Just log an error.
9297                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9298            }
9299        } else {
9300            resourcePath = pkg.codePath;
9301            baseResourcePath = pkg.baseCodePath;
9302        }
9303
9304        // Set application objects path explicitly.
9305        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9306        pkg.setApplicationInfoCodePath(pkg.codePath);
9307        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9308        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9309        pkg.setApplicationInfoResourcePath(resourcePath);
9310        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9311        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9312
9313        // throw an exception if we have an update to a system application, but, it's not more
9314        // recent than the package we've already scanned
9315        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9316            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9317                    + scanFile + " ignored: updated version " + ps.versionCode
9318                    + " better than this " + pkg.mVersionCode);
9319        }
9320
9321        if (isUpdatedPkg) {
9322            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9323            // initially
9324            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9325
9326            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9327            // flag set initially
9328            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9329                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9330            }
9331        }
9332
9333        // Verify certificates against what was last scanned
9334        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9335
9336        /*
9337         * A new system app appeared, but we already had a non-system one of the
9338         * same name installed earlier.
9339         */
9340        boolean shouldHideSystemApp = false;
9341        if (!isUpdatedPkg && ps != null
9342                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9343            /*
9344             * Check to make sure the signatures match first. If they don't,
9345             * wipe the installed application and its data.
9346             */
9347            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9348                    != PackageManager.SIGNATURE_MATCH) {
9349                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9350                        + " signatures don't match existing userdata copy; removing");
9351                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9352                        "scanPackageInternalLI")) {
9353                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9354                }
9355                ps = null;
9356            } else {
9357                /*
9358                 * If the newly-added system app is an older version than the
9359                 * already installed version, hide it. It will be scanned later
9360                 * and re-added like an update.
9361                 */
9362                if (pkg.mVersionCode <= ps.versionCode) {
9363                    shouldHideSystemApp = true;
9364                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9365                            + " but new version " + pkg.mVersionCode + " better than installed "
9366                            + ps.versionCode + "; hiding system");
9367                } else {
9368                    /*
9369                     * The newly found system app is a newer version that the
9370                     * one previously installed. Simply remove the
9371                     * already-installed application and replace it with our own
9372                     * while keeping the application data.
9373                     */
9374                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9375                            + " reverting from " + ps.codePathString + ": new version "
9376                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9377                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9378                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9379                    synchronized (mInstallLock) {
9380                        args.cleanUpResourcesLI();
9381                    }
9382                }
9383            }
9384        }
9385
9386        // The apk is forward locked (not public) if its code and resources
9387        // are kept in different files. (except for app in either system or
9388        // vendor path).
9389        // TODO grab this value from PackageSettings
9390        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9391            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9392                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9393            }
9394        }
9395
9396        final int userId = ((user == null) ? 0 : user.getIdentifier());
9397        if (ps != null && ps.getInstantApp(userId)) {
9398            scanFlags |= SCAN_AS_INSTANT_APP;
9399        }
9400
9401        // Note that we invoke the following method only if we are about to unpack an application
9402        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9403                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9404
9405        /*
9406         * If the system app should be overridden by a previously installed
9407         * data, hide the system app now and let the /data/app scan pick it up
9408         * again.
9409         */
9410        if (shouldHideSystemApp) {
9411            synchronized (mPackages) {
9412                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9413            }
9414        }
9415
9416        return scannedPkg;
9417    }
9418
9419    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9420        // Derive the new package synthetic package name
9421        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9422                + pkg.staticSharedLibVersion);
9423    }
9424
9425    private static String fixProcessName(String defProcessName,
9426            String processName) {
9427        if (processName == null) {
9428            return defProcessName;
9429        }
9430        return processName;
9431    }
9432
9433    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9434            throws PackageManagerException {
9435        if (pkgSetting.signatures.mSignatures != null) {
9436            // Already existing package. Make sure signatures match
9437            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9438                    == PackageManager.SIGNATURE_MATCH;
9439            if (!match) {
9440                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9441                        == PackageManager.SIGNATURE_MATCH;
9442            }
9443            if (!match) {
9444                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9445                        == PackageManager.SIGNATURE_MATCH;
9446            }
9447            if (!match) {
9448                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9449                        + pkg.packageName + " signatures do not match the "
9450                        + "previously installed version; ignoring!");
9451            }
9452        }
9453
9454        // Check for shared user signatures
9455        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9456            // Already existing package. Make sure signatures match
9457            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9458                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9459            if (!match) {
9460                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9461                        == PackageManager.SIGNATURE_MATCH;
9462            }
9463            if (!match) {
9464                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9465                        == PackageManager.SIGNATURE_MATCH;
9466            }
9467            if (!match) {
9468                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9469                        "Package " + pkg.packageName
9470                        + " has no signatures that match those in shared user "
9471                        + pkgSetting.sharedUser.name + "; ignoring!");
9472            }
9473        }
9474    }
9475
9476    /**
9477     * Enforces that only the system UID or root's UID can call a method exposed
9478     * via Binder.
9479     *
9480     * @param message used as message if SecurityException is thrown
9481     * @throws SecurityException if the caller is not system or root
9482     */
9483    private static final void enforceSystemOrRoot(String message) {
9484        final int uid = Binder.getCallingUid();
9485        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9486            throw new SecurityException(message);
9487        }
9488    }
9489
9490    @Override
9491    public void performFstrimIfNeeded() {
9492        enforceSystemOrRoot("Only the system can request fstrim");
9493
9494        // Before everything else, see whether we need to fstrim.
9495        try {
9496            IStorageManager sm = PackageHelper.getStorageManager();
9497            if (sm != null) {
9498                boolean doTrim = false;
9499                final long interval = android.provider.Settings.Global.getLong(
9500                        mContext.getContentResolver(),
9501                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9502                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9503                if (interval > 0) {
9504                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9505                    if (timeSinceLast > interval) {
9506                        doTrim = true;
9507                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9508                                + "; running immediately");
9509                    }
9510                }
9511                if (doTrim) {
9512                    final boolean dexOptDialogShown;
9513                    synchronized (mPackages) {
9514                        dexOptDialogShown = mDexOptDialogShown;
9515                    }
9516                    if (!isFirstBoot() && dexOptDialogShown) {
9517                        try {
9518                            ActivityManager.getService().showBootMessage(
9519                                    mContext.getResources().getString(
9520                                            R.string.android_upgrading_fstrim), true);
9521                        } catch (RemoteException e) {
9522                        }
9523                    }
9524                    sm.runMaintenance();
9525                }
9526            } else {
9527                Slog.e(TAG, "storageManager service unavailable!");
9528            }
9529        } catch (RemoteException e) {
9530            // Can't happen; StorageManagerService is local
9531        }
9532    }
9533
9534    @Override
9535    public void updatePackagesIfNeeded() {
9536        enforceSystemOrRoot("Only the system can request package update");
9537
9538        // We need to re-extract after an OTA.
9539        boolean causeUpgrade = isUpgrade();
9540
9541        // First boot or factory reset.
9542        // Note: we also handle devices that are upgrading to N right now as if it is their
9543        //       first boot, as they do not have profile data.
9544        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9545
9546        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9547        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9548
9549        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9550            return;
9551        }
9552
9553        List<PackageParser.Package> pkgs;
9554        synchronized (mPackages) {
9555            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9556        }
9557
9558        final long startTime = System.nanoTime();
9559        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9560                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9561                    false /* bootComplete */);
9562
9563        final int elapsedTimeSeconds =
9564                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9565
9566        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9567        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9568        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9569        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9570        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9571    }
9572
9573    /*
9574     * Return the prebuilt profile path given a package base code path.
9575     */
9576    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9577        return pkg.baseCodePath + ".prof";
9578    }
9579
9580    /**
9581     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9582     * containing statistics about the invocation. The array consists of three elements,
9583     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9584     * and {@code numberOfPackagesFailed}.
9585     */
9586    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9587            String compilerFilter, boolean bootComplete) {
9588
9589        int numberOfPackagesVisited = 0;
9590        int numberOfPackagesOptimized = 0;
9591        int numberOfPackagesSkipped = 0;
9592        int numberOfPackagesFailed = 0;
9593        final int numberOfPackagesToDexopt = pkgs.size();
9594
9595        for (PackageParser.Package pkg : pkgs) {
9596            numberOfPackagesVisited++;
9597
9598            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9599                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9600                // that are already compiled.
9601                File profileFile = new File(getPrebuildProfilePath(pkg));
9602                // Copy profile if it exists.
9603                if (profileFile.exists()) {
9604                    try {
9605                        // We could also do this lazily before calling dexopt in
9606                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9607                        // is that we don't have a good way to say "do this only once".
9608                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9609                                pkg.applicationInfo.uid, pkg.packageName)) {
9610                            Log.e(TAG, "Installer failed to copy system profile!");
9611                        }
9612                    } catch (Exception e) {
9613                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9614                                e);
9615                    }
9616                }
9617            }
9618
9619            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9620                if (DEBUG_DEXOPT) {
9621                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9622                }
9623                numberOfPackagesSkipped++;
9624                continue;
9625            }
9626
9627            if (DEBUG_DEXOPT) {
9628                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9629                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9630            }
9631
9632            if (showDialog) {
9633                try {
9634                    ActivityManager.getService().showBootMessage(
9635                            mContext.getResources().getString(R.string.android_upgrading_apk,
9636                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9637                } catch (RemoteException e) {
9638                }
9639                synchronized (mPackages) {
9640                    mDexOptDialogShown = true;
9641                }
9642            }
9643
9644            // If the OTA updates a system app which was previously preopted to a non-preopted state
9645            // the app might end up being verified at runtime. That's because by default the apps
9646            // are verify-profile but for preopted apps there's no profile.
9647            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9648            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9649            // filter (by default 'quicken').
9650            // Note that at this stage unused apps are already filtered.
9651            if (isSystemApp(pkg) &&
9652                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9653                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9654                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9655            }
9656
9657            // checkProfiles is false to avoid merging profiles during boot which
9658            // might interfere with background compilation (b/28612421).
9659            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9660            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9661            // trade-off worth doing to save boot time work.
9662            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9663            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9664                    pkg.packageName,
9665                    compilerFilter,
9666                    dexoptFlags));
9667
9668            if (pkg.isSystemApp()) {
9669                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9670                // too much boot after an OTA.
9671                int secondaryDexoptFlags = dexoptFlags |
9672                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9673                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9674                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9675                        pkg.packageName,
9676                        compilerFilter,
9677                        secondaryDexoptFlags));
9678            }
9679
9680            // TODO(shubhamajmera): Record secondary dexopt stats.
9681            switch (primaryDexOptStaus) {
9682                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9683                    numberOfPackagesOptimized++;
9684                    break;
9685                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9686                    numberOfPackagesSkipped++;
9687                    break;
9688                case PackageDexOptimizer.DEX_OPT_FAILED:
9689                    numberOfPackagesFailed++;
9690                    break;
9691                default:
9692                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9693                    break;
9694            }
9695        }
9696
9697        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9698                numberOfPackagesFailed };
9699    }
9700
9701    @Override
9702    public void notifyPackageUse(String packageName, int reason) {
9703        synchronized (mPackages) {
9704            final int callingUid = Binder.getCallingUid();
9705            final int callingUserId = UserHandle.getUserId(callingUid);
9706            if (getInstantAppPackageName(callingUid) != null) {
9707                if (!isCallerSameApp(packageName, callingUid)) {
9708                    return;
9709                }
9710            } else {
9711                if (isInstantApp(packageName, callingUserId)) {
9712                    return;
9713                }
9714            }
9715            final PackageParser.Package p = mPackages.get(packageName);
9716            if (p == null) {
9717                return;
9718            }
9719            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9720        }
9721    }
9722
9723    @Override
9724    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9725            List<String> classPaths, String loaderIsa) {
9726        int userId = UserHandle.getCallingUserId();
9727        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9728        if (ai == null) {
9729            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9730                + loadingPackageName + ", user=" + userId);
9731            return;
9732        }
9733        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9734    }
9735
9736    @Override
9737    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9738            IDexModuleRegisterCallback callback) {
9739        int userId = UserHandle.getCallingUserId();
9740        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9741        DexManager.RegisterDexModuleResult result;
9742        if (ai == null) {
9743            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9744                     " calling user. package=" + packageName + ", user=" + userId);
9745            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9746        } else {
9747            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9748        }
9749
9750        if (callback != null) {
9751            mHandler.post(() -> {
9752                try {
9753                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9754                } catch (RemoteException e) {
9755                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9756                }
9757            });
9758        }
9759    }
9760
9761    /**
9762     * Ask the package manager to perform a dex-opt with the given compiler filter.
9763     *
9764     * Note: exposed only for the shell command to allow moving packages explicitly to a
9765     *       definite state.
9766     */
9767    @Override
9768    public boolean performDexOptMode(String packageName,
9769            boolean checkProfiles, String targetCompilerFilter, boolean force,
9770            boolean bootComplete, String splitName) {
9771        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9772                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9773                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9774        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9775                splitName, flags));
9776    }
9777
9778    /**
9779     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9780     * secondary dex files belonging to the given package.
9781     *
9782     * Note: exposed only for the shell command to allow moving packages explicitly to a
9783     *       definite state.
9784     */
9785    @Override
9786    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9787            boolean force) {
9788        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9789                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9790                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9791                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9792        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9793    }
9794
9795    /*package*/ boolean performDexOpt(DexoptOptions options) {
9796        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9797            return false;
9798        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9799            return false;
9800        }
9801
9802        if (options.isDexoptOnlySecondaryDex()) {
9803            return mDexManager.dexoptSecondaryDex(options);
9804        } else {
9805            int dexoptStatus = performDexOptWithStatus(options);
9806            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9807        }
9808    }
9809
9810    /**
9811     * Perform dexopt on the given package and return one of following result:
9812     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9813     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9814     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9815     */
9816    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9817        return performDexOptTraced(options);
9818    }
9819
9820    private int performDexOptTraced(DexoptOptions options) {
9821        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9822        try {
9823            return performDexOptInternal(options);
9824        } finally {
9825            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9826        }
9827    }
9828
9829    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9830    // if the package can now be considered up to date for the given filter.
9831    private int performDexOptInternal(DexoptOptions options) {
9832        PackageParser.Package p;
9833        synchronized (mPackages) {
9834            p = mPackages.get(options.getPackageName());
9835            if (p == null) {
9836                // Package could not be found. Report failure.
9837                return PackageDexOptimizer.DEX_OPT_FAILED;
9838            }
9839            mPackageUsage.maybeWriteAsync(mPackages);
9840            mCompilerStats.maybeWriteAsync();
9841        }
9842        long callingId = Binder.clearCallingIdentity();
9843        try {
9844            synchronized (mInstallLock) {
9845                return performDexOptInternalWithDependenciesLI(p, options);
9846            }
9847        } finally {
9848            Binder.restoreCallingIdentity(callingId);
9849        }
9850    }
9851
9852    public ArraySet<String> getOptimizablePackages() {
9853        ArraySet<String> pkgs = new ArraySet<String>();
9854        synchronized (mPackages) {
9855            for (PackageParser.Package p : mPackages.values()) {
9856                if (PackageDexOptimizer.canOptimizePackage(p)) {
9857                    pkgs.add(p.packageName);
9858                }
9859            }
9860        }
9861        return pkgs;
9862    }
9863
9864    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9865            DexoptOptions options) {
9866        // Select the dex optimizer based on the force parameter.
9867        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9868        //       allocate an object here.
9869        PackageDexOptimizer pdo = options.isForce()
9870                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9871                : mPackageDexOptimizer;
9872
9873        // Dexopt all dependencies first. Note: we ignore the return value and march on
9874        // on errors.
9875        // Note that we are going to call performDexOpt on those libraries as many times as
9876        // they are referenced in packages. When we do a batch of performDexOpt (for example
9877        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9878        // and the first package that uses the library will dexopt it. The
9879        // others will see that the compiled code for the library is up to date.
9880        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9881        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9882        if (!deps.isEmpty()) {
9883            for (PackageParser.Package depPackage : deps) {
9884                // TODO: Analyze and investigate if we (should) profile libraries.
9885                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9886                        getOrCreateCompilerPackageStats(depPackage),
9887                        true /* isUsedByOtherApps */,
9888                        options);
9889            }
9890        }
9891        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9892                getOrCreateCompilerPackageStats(p),
9893                mDexManager.isUsedByOtherApps(p.packageName), options);
9894    }
9895
9896    /**
9897     * Reconcile the information we have about the secondary dex files belonging to
9898     * {@code packagName} and the actual dex files. For all dex files that were
9899     * deleted, update the internal records and delete the generated oat files.
9900     */
9901    @Override
9902    public void reconcileSecondaryDexFiles(String packageName) {
9903        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9904            return;
9905        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9906            return;
9907        }
9908        mDexManager.reconcileSecondaryDexFiles(packageName);
9909    }
9910
9911    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9912    // a reference there.
9913    /*package*/ DexManager getDexManager() {
9914        return mDexManager;
9915    }
9916
9917    /**
9918     * Execute the background dexopt job immediately.
9919     */
9920    @Override
9921    public boolean runBackgroundDexoptJob() {
9922        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9923            return false;
9924        }
9925        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9926    }
9927
9928    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9929        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9930                || p.usesStaticLibraries != null) {
9931            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9932            Set<String> collectedNames = new HashSet<>();
9933            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9934
9935            retValue.remove(p);
9936
9937            return retValue;
9938        } else {
9939            return Collections.emptyList();
9940        }
9941    }
9942
9943    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9944            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9945        if (!collectedNames.contains(p.packageName)) {
9946            collectedNames.add(p.packageName);
9947            collected.add(p);
9948
9949            if (p.usesLibraries != null) {
9950                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9951                        null, collected, collectedNames);
9952            }
9953            if (p.usesOptionalLibraries != null) {
9954                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9955                        null, collected, collectedNames);
9956            }
9957            if (p.usesStaticLibraries != null) {
9958                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9959                        p.usesStaticLibrariesVersions, collected, collectedNames);
9960            }
9961        }
9962    }
9963
9964    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9965            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9966        final int libNameCount = libs.size();
9967        for (int i = 0; i < libNameCount; i++) {
9968            String libName = libs.get(i);
9969            int version = (versions != null && versions.length == libNameCount)
9970                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9971            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9972            if (libPkg != null) {
9973                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9974            }
9975        }
9976    }
9977
9978    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9979        synchronized (mPackages) {
9980            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9981            if (libEntry != null) {
9982                return mPackages.get(libEntry.apk);
9983            }
9984            return null;
9985        }
9986    }
9987
9988    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9989        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9990        if (versionedLib == null) {
9991            return null;
9992        }
9993        return versionedLib.get(version);
9994    }
9995
9996    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9997        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9998                pkg.staticSharedLibName);
9999        if (versionedLib == null) {
10000            return null;
10001        }
10002        int previousLibVersion = -1;
10003        final int versionCount = versionedLib.size();
10004        for (int i = 0; i < versionCount; i++) {
10005            final int libVersion = versionedLib.keyAt(i);
10006            if (libVersion < pkg.staticSharedLibVersion) {
10007                previousLibVersion = Math.max(previousLibVersion, libVersion);
10008            }
10009        }
10010        if (previousLibVersion >= 0) {
10011            return versionedLib.get(previousLibVersion);
10012        }
10013        return null;
10014    }
10015
10016    public void shutdown() {
10017        mPackageUsage.writeNow(mPackages);
10018        mCompilerStats.writeNow();
10019    }
10020
10021    @Override
10022    public void dumpProfiles(String packageName) {
10023        PackageParser.Package pkg;
10024        synchronized (mPackages) {
10025            pkg = mPackages.get(packageName);
10026            if (pkg == null) {
10027                throw new IllegalArgumentException("Unknown package: " + packageName);
10028            }
10029        }
10030        /* Only the shell, root, or the app user should be able to dump profiles. */
10031        int callingUid = Binder.getCallingUid();
10032        if (callingUid != Process.SHELL_UID &&
10033            callingUid != Process.ROOT_UID &&
10034            callingUid != pkg.applicationInfo.uid) {
10035            throw new SecurityException("dumpProfiles");
10036        }
10037
10038        synchronized (mInstallLock) {
10039            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10040            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10041            try {
10042                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10043                String codePaths = TextUtils.join(";", allCodePaths);
10044                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10045            } catch (InstallerException e) {
10046                Slog.w(TAG, "Failed to dump profiles", e);
10047            }
10048            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10049        }
10050    }
10051
10052    @Override
10053    public void forceDexOpt(String packageName) {
10054        enforceSystemOrRoot("forceDexOpt");
10055
10056        PackageParser.Package pkg;
10057        synchronized (mPackages) {
10058            pkg = mPackages.get(packageName);
10059            if (pkg == null) {
10060                throw new IllegalArgumentException("Unknown package: " + packageName);
10061            }
10062        }
10063
10064        synchronized (mInstallLock) {
10065            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10066
10067            // Whoever is calling forceDexOpt wants a compiled package.
10068            // Don't use profiles since that may cause compilation to be skipped.
10069            final int res = performDexOptInternalWithDependenciesLI(
10070                    pkg,
10071                    new DexoptOptions(packageName,
10072                            getDefaultCompilerFilter(),
10073                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10074
10075            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10076            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10077                throw new IllegalStateException("Failed to dexopt: " + res);
10078            }
10079        }
10080    }
10081
10082    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10083        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10084            Slog.w(TAG, "Unable to update from " + oldPkg.name
10085                    + " to " + newPkg.packageName
10086                    + ": old package not in system partition");
10087            return false;
10088        } else if (mPackages.get(oldPkg.name) != null) {
10089            Slog.w(TAG, "Unable to update from " + oldPkg.name
10090                    + " to " + newPkg.packageName
10091                    + ": old package still exists");
10092            return false;
10093        }
10094        return true;
10095    }
10096
10097    void removeCodePathLI(File codePath) {
10098        if (codePath.isDirectory()) {
10099            try {
10100                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10101            } catch (InstallerException e) {
10102                Slog.w(TAG, "Failed to remove code path", e);
10103            }
10104        } else {
10105            codePath.delete();
10106        }
10107    }
10108
10109    private int[] resolveUserIds(int userId) {
10110        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10111    }
10112
10113    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10114        if (pkg == null) {
10115            Slog.wtf(TAG, "Package was null!", new Throwable());
10116            return;
10117        }
10118        clearAppDataLeafLIF(pkg, userId, flags);
10119        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10120        for (int i = 0; i < childCount; i++) {
10121            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10122        }
10123    }
10124
10125    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10126        final PackageSetting ps;
10127        synchronized (mPackages) {
10128            ps = mSettings.mPackages.get(pkg.packageName);
10129        }
10130        for (int realUserId : resolveUserIds(userId)) {
10131            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10132            try {
10133                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10134                        ceDataInode);
10135            } catch (InstallerException e) {
10136                Slog.w(TAG, String.valueOf(e));
10137            }
10138        }
10139    }
10140
10141    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10142        if (pkg == null) {
10143            Slog.wtf(TAG, "Package was null!", new Throwable());
10144            return;
10145        }
10146        destroyAppDataLeafLIF(pkg, userId, flags);
10147        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10148        for (int i = 0; i < childCount; i++) {
10149            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10150        }
10151    }
10152
10153    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10154        final PackageSetting ps;
10155        synchronized (mPackages) {
10156            ps = mSettings.mPackages.get(pkg.packageName);
10157        }
10158        for (int realUserId : resolveUserIds(userId)) {
10159            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10160            try {
10161                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10162                        ceDataInode);
10163            } catch (InstallerException e) {
10164                Slog.w(TAG, String.valueOf(e));
10165            }
10166            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10167        }
10168    }
10169
10170    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10171        if (pkg == null) {
10172            Slog.wtf(TAG, "Package was null!", new Throwable());
10173            return;
10174        }
10175        destroyAppProfilesLeafLIF(pkg);
10176        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10177        for (int i = 0; i < childCount; i++) {
10178            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10179        }
10180    }
10181
10182    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10183        try {
10184            mInstaller.destroyAppProfiles(pkg.packageName);
10185        } catch (InstallerException e) {
10186            Slog.w(TAG, String.valueOf(e));
10187        }
10188    }
10189
10190    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10191        if (pkg == null) {
10192            Slog.wtf(TAG, "Package was null!", new Throwable());
10193            return;
10194        }
10195        clearAppProfilesLeafLIF(pkg);
10196        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10197        for (int i = 0; i < childCount; i++) {
10198            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10199        }
10200    }
10201
10202    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10203        try {
10204            mInstaller.clearAppProfiles(pkg.packageName);
10205        } catch (InstallerException e) {
10206            Slog.w(TAG, String.valueOf(e));
10207        }
10208    }
10209
10210    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10211            long lastUpdateTime) {
10212        // Set parent install/update time
10213        PackageSetting ps = (PackageSetting) pkg.mExtras;
10214        if (ps != null) {
10215            ps.firstInstallTime = firstInstallTime;
10216            ps.lastUpdateTime = lastUpdateTime;
10217        }
10218        // Set children install/update time
10219        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10220        for (int i = 0; i < childCount; i++) {
10221            PackageParser.Package childPkg = pkg.childPackages.get(i);
10222            ps = (PackageSetting) childPkg.mExtras;
10223            if (ps != null) {
10224                ps.firstInstallTime = firstInstallTime;
10225                ps.lastUpdateTime = lastUpdateTime;
10226            }
10227        }
10228    }
10229
10230    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10231            PackageParser.Package changingLib) {
10232        if (file.path != null) {
10233            usesLibraryFiles.add(file.path);
10234            return;
10235        }
10236        PackageParser.Package p = mPackages.get(file.apk);
10237        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10238            // If we are doing this while in the middle of updating a library apk,
10239            // then we need to make sure to use that new apk for determining the
10240            // dependencies here.  (We haven't yet finished committing the new apk
10241            // to the package manager state.)
10242            if (p == null || p.packageName.equals(changingLib.packageName)) {
10243                p = changingLib;
10244            }
10245        }
10246        if (p != null) {
10247            usesLibraryFiles.addAll(p.getAllCodePaths());
10248            if (p.usesLibraryFiles != null) {
10249                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10250            }
10251        }
10252    }
10253
10254    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10255            PackageParser.Package changingLib) throws PackageManagerException {
10256        if (pkg == null) {
10257            return;
10258        }
10259        ArraySet<String> usesLibraryFiles = null;
10260        if (pkg.usesLibraries != null) {
10261            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10262                    null, null, pkg.packageName, changingLib, true, null);
10263        }
10264        if (pkg.usesStaticLibraries != null) {
10265            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10266                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10267                    pkg.packageName, changingLib, true, usesLibraryFiles);
10268        }
10269        if (pkg.usesOptionalLibraries != null) {
10270            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10271                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
10272        }
10273        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10274            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10275        } else {
10276            pkg.usesLibraryFiles = null;
10277        }
10278    }
10279
10280    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10281            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10282            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10283            boolean required, @Nullable ArraySet<String> outUsedLibraries)
10284            throws PackageManagerException {
10285        final int libCount = requestedLibraries.size();
10286        for (int i = 0; i < libCount; i++) {
10287            final String libName = requestedLibraries.get(i);
10288            final int libVersion = requiredVersions != null ? requiredVersions[i]
10289                    : SharedLibraryInfo.VERSION_UNDEFINED;
10290            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10291            if (libEntry == null) {
10292                if (required) {
10293                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10294                            "Package " + packageName + " requires unavailable shared library "
10295                                    + libName + "; failing!");
10296                } else if (DEBUG_SHARED_LIBRARIES) {
10297                    Slog.i(TAG, "Package " + packageName
10298                            + " desires unavailable shared library "
10299                            + libName + "; ignoring!");
10300                }
10301            } else {
10302                if (requiredVersions != null && requiredCertDigests != null) {
10303                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10304                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10305                            "Package " + packageName + " requires unavailable static shared"
10306                                    + " library " + libName + " version "
10307                                    + libEntry.info.getVersion() + "; failing!");
10308                    }
10309
10310                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10311                    if (libPkg == null) {
10312                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10313                                "Package " + packageName + " requires unavailable static shared"
10314                                        + " library; failing!");
10315                    }
10316
10317                    String expectedCertDigest = requiredCertDigests[i];
10318                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10319                                libPkg.mSignatures[0]);
10320                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10321                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10322                                "Package " + packageName + " requires differently signed" +
10323                                        " static shared library; failing!");
10324                    }
10325                }
10326
10327                if (outUsedLibraries == null) {
10328                    outUsedLibraries = new ArraySet<>();
10329                }
10330                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10331            }
10332        }
10333        return outUsedLibraries;
10334    }
10335
10336    private static boolean hasString(List<String> list, List<String> which) {
10337        if (list == null) {
10338            return false;
10339        }
10340        for (int i=list.size()-1; i>=0; i--) {
10341            for (int j=which.size()-1; j>=0; j--) {
10342                if (which.get(j).equals(list.get(i))) {
10343                    return true;
10344                }
10345            }
10346        }
10347        return false;
10348    }
10349
10350    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10351            PackageParser.Package changingPkg) {
10352        ArrayList<PackageParser.Package> res = null;
10353        for (PackageParser.Package pkg : mPackages.values()) {
10354            if (changingPkg != null
10355                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10356                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10357                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10358                            changingPkg.staticSharedLibName)) {
10359                return null;
10360            }
10361            if (res == null) {
10362                res = new ArrayList<>();
10363            }
10364            res.add(pkg);
10365            try {
10366                updateSharedLibrariesLPr(pkg, changingPkg);
10367            } catch (PackageManagerException e) {
10368                // If a system app update or an app and a required lib missing we
10369                // delete the package and for updated system apps keep the data as
10370                // it is better for the user to reinstall than to be in an limbo
10371                // state. Also libs disappearing under an app should never happen
10372                // - just in case.
10373                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10374                    final int flags = pkg.isUpdatedSystemApp()
10375                            ? PackageManager.DELETE_KEEP_DATA : 0;
10376                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10377                            flags , null, true, null);
10378                }
10379                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10380            }
10381        }
10382        return res;
10383    }
10384
10385    /**
10386     * Derive the value of the {@code cpuAbiOverride} based on the provided
10387     * value and an optional stored value from the package settings.
10388     */
10389    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10390        String cpuAbiOverride = null;
10391
10392        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10393            cpuAbiOverride = null;
10394        } else if (abiOverride != null) {
10395            cpuAbiOverride = abiOverride;
10396        } else if (settings != null) {
10397            cpuAbiOverride = settings.cpuAbiOverrideString;
10398        }
10399
10400        return cpuAbiOverride;
10401    }
10402
10403    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10404            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10405                    throws PackageManagerException {
10406        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10407        // If the package has children and this is the first dive in the function
10408        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10409        // whether all packages (parent and children) would be successfully scanned
10410        // before the actual scan since scanning mutates internal state and we want
10411        // to atomically install the package and its children.
10412        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10413            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10414                scanFlags |= SCAN_CHECK_ONLY;
10415            }
10416        } else {
10417            scanFlags &= ~SCAN_CHECK_ONLY;
10418        }
10419
10420        final PackageParser.Package scannedPkg;
10421        try {
10422            // Scan the parent
10423            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10424            // Scan the children
10425            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10426            for (int i = 0; i < childCount; i++) {
10427                PackageParser.Package childPkg = pkg.childPackages.get(i);
10428                scanPackageLI(childPkg, policyFlags,
10429                        scanFlags, currentTime, user);
10430            }
10431        } finally {
10432            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10433        }
10434
10435        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10436            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10437        }
10438
10439        return scannedPkg;
10440    }
10441
10442    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10443            int scanFlags, long currentTime, @Nullable UserHandle user)
10444                    throws PackageManagerException {
10445        boolean success = false;
10446        try {
10447            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10448                    currentTime, user);
10449            success = true;
10450            return res;
10451        } finally {
10452            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10453                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10454                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10455                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10456                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10457            }
10458        }
10459    }
10460
10461    /**
10462     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10463     */
10464    private static boolean apkHasCode(String fileName) {
10465        StrictJarFile jarFile = null;
10466        try {
10467            jarFile = new StrictJarFile(fileName,
10468                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10469            return jarFile.findEntry("classes.dex") != null;
10470        } catch (IOException ignore) {
10471        } finally {
10472            try {
10473                if (jarFile != null) {
10474                    jarFile.close();
10475                }
10476            } catch (IOException ignore) {}
10477        }
10478        return false;
10479    }
10480
10481    /**
10482     * Enforces code policy for the package. This ensures that if an APK has
10483     * declared hasCode="true" in its manifest that the APK actually contains
10484     * code.
10485     *
10486     * @throws PackageManagerException If bytecode could not be found when it should exist
10487     */
10488    private static void assertCodePolicy(PackageParser.Package pkg)
10489            throws PackageManagerException {
10490        final boolean shouldHaveCode =
10491                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10492        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10493            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10494                    "Package " + pkg.baseCodePath + " code is missing");
10495        }
10496
10497        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10498            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10499                final boolean splitShouldHaveCode =
10500                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10501                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10502                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10503                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10504                }
10505            }
10506        }
10507    }
10508
10509    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10510            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10511                    throws PackageManagerException {
10512        if (DEBUG_PACKAGE_SCANNING) {
10513            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10514                Log.d(TAG, "Scanning package " + pkg.packageName);
10515        }
10516
10517        applyPolicy(pkg, policyFlags);
10518
10519        assertPackageIsValid(pkg, policyFlags, scanFlags);
10520
10521        // Initialize package source and resource directories
10522        final File scanFile = new File(pkg.codePath);
10523        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10524        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10525
10526        SharedUserSetting suid = null;
10527        PackageSetting pkgSetting = null;
10528
10529        // Getting the package setting may have a side-effect, so if we
10530        // are only checking if scan would succeed, stash a copy of the
10531        // old setting to restore at the end.
10532        PackageSetting nonMutatedPs = null;
10533
10534        // We keep references to the derived CPU Abis from settings in oder to reuse
10535        // them in the case where we're not upgrading or booting for the first time.
10536        String primaryCpuAbiFromSettings = null;
10537        String secondaryCpuAbiFromSettings = null;
10538
10539        // writer
10540        synchronized (mPackages) {
10541            if (pkg.mSharedUserId != null) {
10542                // SIDE EFFECTS; may potentially allocate a new shared user
10543                suid = mSettings.getSharedUserLPw(
10544                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10545                if (DEBUG_PACKAGE_SCANNING) {
10546                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10547                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10548                                + "): packages=" + suid.packages);
10549                }
10550            }
10551
10552            // Check if we are renaming from an original package name.
10553            PackageSetting origPackage = null;
10554            String realName = null;
10555            if (pkg.mOriginalPackages != null) {
10556                // This package may need to be renamed to a previously
10557                // installed name.  Let's check on that...
10558                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10559                if (pkg.mOriginalPackages.contains(renamed)) {
10560                    // This package had originally been installed as the
10561                    // original name, and we have already taken care of
10562                    // transitioning to the new one.  Just update the new
10563                    // one to continue using the old name.
10564                    realName = pkg.mRealPackage;
10565                    if (!pkg.packageName.equals(renamed)) {
10566                        // Callers into this function may have already taken
10567                        // care of renaming the package; only do it here if
10568                        // it is not already done.
10569                        pkg.setPackageName(renamed);
10570                    }
10571                } else {
10572                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10573                        if ((origPackage = mSettings.getPackageLPr(
10574                                pkg.mOriginalPackages.get(i))) != null) {
10575                            // We do have the package already installed under its
10576                            // original name...  should we use it?
10577                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10578                                // New package is not compatible with original.
10579                                origPackage = null;
10580                                continue;
10581                            } else if (origPackage.sharedUser != null) {
10582                                // Make sure uid is compatible between packages.
10583                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10584                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10585                                            + " to " + pkg.packageName + ": old uid "
10586                                            + origPackage.sharedUser.name
10587                                            + " differs from " + pkg.mSharedUserId);
10588                                    origPackage = null;
10589                                    continue;
10590                                }
10591                                // TODO: Add case when shared user id is added [b/28144775]
10592                            } else {
10593                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10594                                        + pkg.packageName + " to old name " + origPackage.name);
10595                            }
10596                            break;
10597                        }
10598                    }
10599                }
10600            }
10601
10602            if (mTransferedPackages.contains(pkg.packageName)) {
10603                Slog.w(TAG, "Package " + pkg.packageName
10604                        + " was transferred to another, but its .apk remains");
10605            }
10606
10607            // See comments in nonMutatedPs declaration
10608            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10609                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10610                if (foundPs != null) {
10611                    nonMutatedPs = new PackageSetting(foundPs);
10612                }
10613            }
10614
10615            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10616                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10617                if (foundPs != null) {
10618                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10619                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10620                }
10621            }
10622
10623            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10624            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10625                PackageManagerService.reportSettingsProblem(Log.WARN,
10626                        "Package " + pkg.packageName + " shared user changed from "
10627                                + (pkgSetting.sharedUser != null
10628                                        ? pkgSetting.sharedUser.name : "<nothing>")
10629                                + " to "
10630                                + (suid != null ? suid.name : "<nothing>")
10631                                + "; replacing with new");
10632                pkgSetting = null;
10633            }
10634            final PackageSetting oldPkgSetting =
10635                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10636            final PackageSetting disabledPkgSetting =
10637                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10638
10639            String[] usesStaticLibraries = null;
10640            if (pkg.usesStaticLibraries != null) {
10641                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10642                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10643            }
10644
10645            if (pkgSetting == null) {
10646                final String parentPackageName = (pkg.parentPackage != null)
10647                        ? pkg.parentPackage.packageName : null;
10648                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10649                // REMOVE SharedUserSetting from method; update in a separate call
10650                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10651                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10652                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10653                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10654                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10655                        true /*allowInstall*/, instantApp, parentPackageName,
10656                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10657                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10658                // SIDE EFFECTS; updates system state; move elsewhere
10659                if (origPackage != null) {
10660                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10661                }
10662                mSettings.addUserToSettingLPw(pkgSetting);
10663            } else {
10664                // REMOVE SharedUserSetting from method; update in a separate call.
10665                //
10666                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10667                // secondaryCpuAbi are not known at this point so we always update them
10668                // to null here, only to reset them at a later point.
10669                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10670                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10671                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10672                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10673                        UserManagerService.getInstance(), usesStaticLibraries,
10674                        pkg.usesStaticLibrariesVersions);
10675            }
10676            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10677            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10678
10679            // SIDE EFFECTS; modifies system state; move elsewhere
10680            if (pkgSetting.origPackage != null) {
10681                // If we are first transitioning from an original package,
10682                // fix up the new package's name now.  We need to do this after
10683                // looking up the package under its new name, so getPackageLP
10684                // can take care of fiddling things correctly.
10685                pkg.setPackageName(origPackage.name);
10686
10687                // File a report about this.
10688                String msg = "New package " + pkgSetting.realName
10689                        + " renamed to replace old package " + pkgSetting.name;
10690                reportSettingsProblem(Log.WARN, msg);
10691
10692                // Make a note of it.
10693                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10694                    mTransferedPackages.add(origPackage.name);
10695                }
10696
10697                // No longer need to retain this.
10698                pkgSetting.origPackage = null;
10699            }
10700
10701            // SIDE EFFECTS; modifies system state; move elsewhere
10702            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10703                // Make a note of it.
10704                mTransferedPackages.add(pkg.packageName);
10705            }
10706
10707            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10708                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10709            }
10710
10711            if ((scanFlags & SCAN_BOOTING) == 0
10712                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10713                // Check all shared libraries and map to their actual file path.
10714                // We only do this here for apps not on a system dir, because those
10715                // are the only ones that can fail an install due to this.  We
10716                // will take care of the system apps by updating all of their
10717                // library paths after the scan is done. Also during the initial
10718                // scan don't update any libs as we do this wholesale after all
10719                // apps are scanned to avoid dependency based scanning.
10720                updateSharedLibrariesLPr(pkg, null);
10721            }
10722
10723            if (mFoundPolicyFile) {
10724                SELinuxMMAC.assignSeInfoValue(pkg);
10725            }
10726            pkg.applicationInfo.uid = pkgSetting.appId;
10727            pkg.mExtras = pkgSetting;
10728
10729
10730            // Static shared libs have same package with different versions where
10731            // we internally use a synthetic package name to allow multiple versions
10732            // of the same package, therefore we need to compare signatures against
10733            // the package setting for the latest library version.
10734            PackageSetting signatureCheckPs = pkgSetting;
10735            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10736                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10737                if (libraryEntry != null) {
10738                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10739                }
10740            }
10741
10742            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10743                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10744                    // We just determined the app is signed correctly, so bring
10745                    // over the latest parsed certs.
10746                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10747                } else {
10748                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10749                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10750                                "Package " + pkg.packageName + " upgrade keys do not match the "
10751                                + "previously installed version");
10752                    } else {
10753                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10754                        String msg = "System package " + pkg.packageName
10755                                + " signature changed; retaining data.";
10756                        reportSettingsProblem(Log.WARN, msg);
10757                    }
10758                }
10759            } else {
10760                try {
10761                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10762                    verifySignaturesLP(signatureCheckPs, pkg);
10763                    // We just determined the app is signed correctly, so bring
10764                    // over the latest parsed certs.
10765                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10766                } catch (PackageManagerException e) {
10767                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10768                        throw e;
10769                    }
10770                    // The signature has changed, but this package is in the system
10771                    // image...  let's recover!
10772                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10773                    // However...  if this package is part of a shared user, but it
10774                    // doesn't match the signature of the shared user, let's fail.
10775                    // What this means is that you can't change the signatures
10776                    // associated with an overall shared user, which doesn't seem all
10777                    // that unreasonable.
10778                    if (signatureCheckPs.sharedUser != null) {
10779                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10780                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10781                            throw new PackageManagerException(
10782                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10783                                    "Signature mismatch for shared user: "
10784                                            + pkgSetting.sharedUser);
10785                        }
10786                    }
10787                    // File a report about this.
10788                    String msg = "System package " + pkg.packageName
10789                            + " signature changed; retaining data.";
10790                    reportSettingsProblem(Log.WARN, msg);
10791                }
10792            }
10793
10794            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10795                // This package wants to adopt ownership of permissions from
10796                // another package.
10797                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10798                    final String origName = pkg.mAdoptPermissions.get(i);
10799                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10800                    if (orig != null) {
10801                        if (verifyPackageUpdateLPr(orig, pkg)) {
10802                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10803                                    + pkg.packageName);
10804                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10805                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10806                        }
10807                    }
10808                }
10809            }
10810        }
10811
10812        pkg.applicationInfo.processName = fixProcessName(
10813                pkg.applicationInfo.packageName,
10814                pkg.applicationInfo.processName);
10815
10816        if (pkg != mPlatformPackage) {
10817            // Get all of our default paths setup
10818            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10819        }
10820
10821        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10822
10823        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10824            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10825                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10826                final boolean extractNativeLibs = !pkg.isLibrary();
10827                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10828                        mAppLib32InstallDir);
10829                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10830
10831                // Some system apps still use directory structure for native libraries
10832                // in which case we might end up not detecting abi solely based on apk
10833                // structure. Try to detect abi based on directory structure.
10834                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10835                        pkg.applicationInfo.primaryCpuAbi == null) {
10836                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10837                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10838                }
10839            } else {
10840                // This is not a first boot or an upgrade, don't bother deriving the
10841                // ABI during the scan. Instead, trust the value that was stored in the
10842                // package setting.
10843                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10844                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10845
10846                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10847
10848                if (DEBUG_ABI_SELECTION) {
10849                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10850                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10851                        pkg.applicationInfo.secondaryCpuAbi);
10852                }
10853            }
10854        } else {
10855            if ((scanFlags & SCAN_MOVE) != 0) {
10856                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10857                // but we already have this packages package info in the PackageSetting. We just
10858                // use that and derive the native library path based on the new codepath.
10859                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10860                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10861            }
10862
10863            // Set native library paths again. For moves, the path will be updated based on the
10864            // ABIs we've determined above. For non-moves, the path will be updated based on the
10865            // ABIs we determined during compilation, but the path will depend on the final
10866            // package path (after the rename away from the stage path).
10867            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10868        }
10869
10870        // This is a special case for the "system" package, where the ABI is
10871        // dictated by the zygote configuration (and init.rc). We should keep track
10872        // of this ABI so that we can deal with "normal" applications that run under
10873        // the same UID correctly.
10874        if (mPlatformPackage == pkg) {
10875            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10876                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10877        }
10878
10879        // If there's a mismatch between the abi-override in the package setting
10880        // and the abiOverride specified for the install. Warn about this because we
10881        // would've already compiled the app without taking the package setting into
10882        // account.
10883        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10884            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10885                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10886                        " for package " + pkg.packageName);
10887            }
10888        }
10889
10890        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10891        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10892        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10893
10894        // Copy the derived override back to the parsed package, so that we can
10895        // update the package settings accordingly.
10896        pkg.cpuAbiOverride = cpuAbiOverride;
10897
10898        if (DEBUG_ABI_SELECTION) {
10899            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10900                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10901                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10902        }
10903
10904        // Push the derived path down into PackageSettings so we know what to
10905        // clean up at uninstall time.
10906        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10907
10908        if (DEBUG_ABI_SELECTION) {
10909            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10910                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10911                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10912        }
10913
10914        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10915        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10916            // We don't do this here during boot because we can do it all
10917            // at once after scanning all existing packages.
10918            //
10919            // We also do this *before* we perform dexopt on this package, so that
10920            // we can avoid redundant dexopts, and also to make sure we've got the
10921            // code and package path correct.
10922            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10923        }
10924
10925        if (mFactoryTest && pkg.requestedPermissions.contains(
10926                android.Manifest.permission.FACTORY_TEST)) {
10927            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10928        }
10929
10930        if (isSystemApp(pkg)) {
10931            pkgSetting.isOrphaned = true;
10932        }
10933
10934        // Take care of first install / last update times.
10935        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10936        if (currentTime != 0) {
10937            if (pkgSetting.firstInstallTime == 0) {
10938                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10939            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10940                pkgSetting.lastUpdateTime = currentTime;
10941            }
10942        } else if (pkgSetting.firstInstallTime == 0) {
10943            // We need *something*.  Take time time stamp of the file.
10944            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10945        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10946            if (scanFileTime != pkgSetting.timeStamp) {
10947                // A package on the system image has changed; consider this
10948                // to be an update.
10949                pkgSetting.lastUpdateTime = scanFileTime;
10950            }
10951        }
10952        pkgSetting.setTimeStamp(scanFileTime);
10953
10954        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10955            if (nonMutatedPs != null) {
10956                synchronized (mPackages) {
10957                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10958                }
10959            }
10960        } else {
10961            final int userId = user == null ? 0 : user.getIdentifier();
10962            // Modify state for the given package setting
10963            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10964                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10965            if (pkgSetting.getInstantApp(userId)) {
10966                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10967            }
10968        }
10969        return pkg;
10970    }
10971
10972    /**
10973     * Applies policy to the parsed package based upon the given policy flags.
10974     * Ensures the package is in a good state.
10975     * <p>
10976     * Implementation detail: This method must NOT have any side effect. It would
10977     * ideally be static, but, it requires locks to read system state.
10978     */
10979    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10980        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10981            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10982            if (pkg.applicationInfo.isDirectBootAware()) {
10983                // we're direct boot aware; set for all components
10984                for (PackageParser.Service s : pkg.services) {
10985                    s.info.encryptionAware = s.info.directBootAware = true;
10986                }
10987                for (PackageParser.Provider p : pkg.providers) {
10988                    p.info.encryptionAware = p.info.directBootAware = true;
10989                }
10990                for (PackageParser.Activity a : pkg.activities) {
10991                    a.info.encryptionAware = a.info.directBootAware = true;
10992                }
10993                for (PackageParser.Activity r : pkg.receivers) {
10994                    r.info.encryptionAware = r.info.directBootAware = true;
10995                }
10996            }
10997            if (compressedFileExists(pkg.baseCodePath)) {
10998                pkg.isStub = true;
10999            }
11000        } else {
11001            // Only allow system apps to be flagged as core apps.
11002            pkg.coreApp = false;
11003            // clear flags not applicable to regular apps
11004            pkg.applicationInfo.privateFlags &=
11005                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11006            pkg.applicationInfo.privateFlags &=
11007                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11008        }
11009        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11010
11011        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11012            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11013        }
11014
11015        if (!isSystemApp(pkg)) {
11016            // Only system apps can use these features.
11017            pkg.mOriginalPackages = null;
11018            pkg.mRealPackage = null;
11019            pkg.mAdoptPermissions = null;
11020        }
11021    }
11022
11023    /**
11024     * Asserts the parsed package is valid according to the given policy. If the
11025     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11026     * <p>
11027     * Implementation detail: This method must NOT have any side effects. It would
11028     * ideally be static, but, it requires locks to read system state.
11029     *
11030     * @throws PackageManagerException If the package fails any of the validation checks
11031     */
11032    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11033            throws PackageManagerException {
11034        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11035            assertCodePolicy(pkg);
11036        }
11037
11038        if (pkg.applicationInfo.getCodePath() == null ||
11039                pkg.applicationInfo.getResourcePath() == null) {
11040            // Bail out. The resource and code paths haven't been set.
11041            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11042                    "Code and resource paths haven't been set correctly");
11043        }
11044
11045        // Make sure we're not adding any bogus keyset info
11046        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11047        ksms.assertScannedPackageValid(pkg);
11048
11049        synchronized (mPackages) {
11050            // The special "android" package can only be defined once
11051            if (pkg.packageName.equals("android")) {
11052                if (mAndroidApplication != null) {
11053                    Slog.w(TAG, "*************************************************");
11054                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11055                    Slog.w(TAG, " codePath=" + pkg.codePath);
11056                    Slog.w(TAG, "*************************************************");
11057                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11058                            "Core android package being redefined.  Skipping.");
11059                }
11060            }
11061
11062            // A package name must be unique; don't allow duplicates
11063            if (mPackages.containsKey(pkg.packageName)) {
11064                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11065                        "Application package " + pkg.packageName
11066                        + " already installed.  Skipping duplicate.");
11067            }
11068
11069            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11070                // Static libs have a synthetic package name containing the version
11071                // but we still want the base name to be unique.
11072                if (mPackages.containsKey(pkg.manifestPackageName)) {
11073                    throw new PackageManagerException(
11074                            "Duplicate static shared lib provider package");
11075                }
11076
11077                // Static shared libraries should have at least O target SDK
11078                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11079                    throw new PackageManagerException(
11080                            "Packages declaring static-shared libs must target O SDK or higher");
11081                }
11082
11083                // Package declaring static a shared lib cannot be instant apps
11084                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11085                    throw new PackageManagerException(
11086                            "Packages declaring static-shared libs cannot be instant apps");
11087                }
11088
11089                // Package declaring static a shared lib cannot be renamed since the package
11090                // name is synthetic and apps can't code around package manager internals.
11091                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11092                    throw new PackageManagerException(
11093                            "Packages declaring static-shared libs cannot be renamed");
11094                }
11095
11096                // Package declaring static a shared lib cannot declare child packages
11097                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11098                    throw new PackageManagerException(
11099                            "Packages declaring static-shared libs cannot have child packages");
11100                }
11101
11102                // Package declaring static a shared lib cannot declare dynamic libs
11103                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11104                    throw new PackageManagerException(
11105                            "Packages declaring static-shared libs cannot declare dynamic libs");
11106                }
11107
11108                // Package declaring static a shared lib cannot declare shared users
11109                if (pkg.mSharedUserId != null) {
11110                    throw new PackageManagerException(
11111                            "Packages declaring static-shared libs cannot declare shared users");
11112                }
11113
11114                // Static shared libs cannot declare activities
11115                if (!pkg.activities.isEmpty()) {
11116                    throw new PackageManagerException(
11117                            "Static shared libs cannot declare activities");
11118                }
11119
11120                // Static shared libs cannot declare services
11121                if (!pkg.services.isEmpty()) {
11122                    throw new PackageManagerException(
11123                            "Static shared libs cannot declare services");
11124                }
11125
11126                // Static shared libs cannot declare providers
11127                if (!pkg.providers.isEmpty()) {
11128                    throw new PackageManagerException(
11129                            "Static shared libs cannot declare content providers");
11130                }
11131
11132                // Static shared libs cannot declare receivers
11133                if (!pkg.receivers.isEmpty()) {
11134                    throw new PackageManagerException(
11135                            "Static shared libs cannot declare broadcast receivers");
11136                }
11137
11138                // Static shared libs cannot declare permission groups
11139                if (!pkg.permissionGroups.isEmpty()) {
11140                    throw new PackageManagerException(
11141                            "Static shared libs cannot declare permission groups");
11142                }
11143
11144                // Static shared libs cannot declare permissions
11145                if (!pkg.permissions.isEmpty()) {
11146                    throw new PackageManagerException(
11147                            "Static shared libs cannot declare permissions");
11148                }
11149
11150                // Static shared libs cannot declare protected broadcasts
11151                if (pkg.protectedBroadcasts != null) {
11152                    throw new PackageManagerException(
11153                            "Static shared libs cannot declare protected broadcasts");
11154                }
11155
11156                // Static shared libs cannot be overlay targets
11157                if (pkg.mOverlayTarget != null) {
11158                    throw new PackageManagerException(
11159                            "Static shared libs cannot be overlay targets");
11160                }
11161
11162                // The version codes must be ordered as lib versions
11163                int minVersionCode = Integer.MIN_VALUE;
11164                int maxVersionCode = Integer.MAX_VALUE;
11165
11166                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11167                        pkg.staticSharedLibName);
11168                if (versionedLib != null) {
11169                    final int versionCount = versionedLib.size();
11170                    for (int i = 0; i < versionCount; i++) {
11171                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11172                        final int libVersionCode = libInfo.getDeclaringPackage()
11173                                .getVersionCode();
11174                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11175                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11176                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11177                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11178                        } else {
11179                            minVersionCode = maxVersionCode = libVersionCode;
11180                            break;
11181                        }
11182                    }
11183                }
11184                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11185                    throw new PackageManagerException("Static shared"
11186                            + " lib version codes must be ordered as lib versions");
11187                }
11188            }
11189
11190            // Only privileged apps and updated privileged apps can add child packages.
11191            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11192                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11193                    throw new PackageManagerException("Only privileged apps can add child "
11194                            + "packages. Ignoring package " + pkg.packageName);
11195                }
11196                final int childCount = pkg.childPackages.size();
11197                for (int i = 0; i < childCount; i++) {
11198                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11199                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11200                            childPkg.packageName)) {
11201                        throw new PackageManagerException("Can't override child of "
11202                                + "another disabled app. Ignoring package " + pkg.packageName);
11203                    }
11204                }
11205            }
11206
11207            // If we're only installing presumed-existing packages, require that the
11208            // scanned APK is both already known and at the path previously established
11209            // for it.  Previously unknown packages we pick up normally, but if we have an
11210            // a priori expectation about this package's install presence, enforce it.
11211            // With a singular exception for new system packages. When an OTA contains
11212            // a new system package, we allow the codepath to change from a system location
11213            // to the user-installed location. If we don't allow this change, any newer,
11214            // user-installed version of the application will be ignored.
11215            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11216                if (mExpectingBetter.containsKey(pkg.packageName)) {
11217                    logCriticalInfo(Log.WARN,
11218                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11219                } else {
11220                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11221                    if (known != null) {
11222                        if (DEBUG_PACKAGE_SCANNING) {
11223                            Log.d(TAG, "Examining " + pkg.codePath
11224                                    + " and requiring known paths " + known.codePathString
11225                                    + " & " + known.resourcePathString);
11226                        }
11227                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11228                                || !pkg.applicationInfo.getResourcePath().equals(
11229                                        known.resourcePathString)) {
11230                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11231                                    "Application package " + pkg.packageName
11232                                    + " found at " + pkg.applicationInfo.getCodePath()
11233                                    + " but expected at " + known.codePathString
11234                                    + "; ignoring.");
11235                        }
11236                    }
11237                }
11238            }
11239
11240            // Verify that this new package doesn't have any content providers
11241            // that conflict with existing packages.  Only do this if the
11242            // package isn't already installed, since we don't want to break
11243            // things that are installed.
11244            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11245                final int N = pkg.providers.size();
11246                int i;
11247                for (i=0; i<N; i++) {
11248                    PackageParser.Provider p = pkg.providers.get(i);
11249                    if (p.info.authority != null) {
11250                        String names[] = p.info.authority.split(";");
11251                        for (int j = 0; j < names.length; j++) {
11252                            if (mProvidersByAuthority.containsKey(names[j])) {
11253                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11254                                final String otherPackageName =
11255                                        ((other != null && other.getComponentName() != null) ?
11256                                                other.getComponentName().getPackageName() : "?");
11257                                throw new PackageManagerException(
11258                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11259                                        "Can't install because provider name " + names[j]
11260                                                + " (in package " + pkg.applicationInfo.packageName
11261                                                + ") is already used by " + otherPackageName);
11262                            }
11263                        }
11264                    }
11265                }
11266            }
11267        }
11268    }
11269
11270    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11271            int type, String declaringPackageName, int declaringVersionCode) {
11272        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11273        if (versionedLib == null) {
11274            versionedLib = new SparseArray<>();
11275            mSharedLibraries.put(name, versionedLib);
11276            if (type == SharedLibraryInfo.TYPE_STATIC) {
11277                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11278            }
11279        } else if (versionedLib.indexOfKey(version) >= 0) {
11280            return false;
11281        }
11282        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11283                version, type, declaringPackageName, declaringVersionCode);
11284        versionedLib.put(version, libEntry);
11285        return true;
11286    }
11287
11288    private boolean removeSharedLibraryLPw(String name, int version) {
11289        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11290        if (versionedLib == null) {
11291            return false;
11292        }
11293        final int libIdx = versionedLib.indexOfKey(version);
11294        if (libIdx < 0) {
11295            return false;
11296        }
11297        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11298        versionedLib.remove(version);
11299        if (versionedLib.size() <= 0) {
11300            mSharedLibraries.remove(name);
11301            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11302                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11303                        .getPackageName());
11304            }
11305        }
11306        return true;
11307    }
11308
11309    /**
11310     * Adds a scanned package to the system. When this method is finished, the package will
11311     * be available for query, resolution, etc...
11312     */
11313    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11314            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11315        final String pkgName = pkg.packageName;
11316        if (mCustomResolverComponentName != null &&
11317                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11318            setUpCustomResolverActivity(pkg);
11319        }
11320
11321        if (pkg.packageName.equals("android")) {
11322            synchronized (mPackages) {
11323                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11324                    // Set up information for our fall-back user intent resolution activity.
11325                    mPlatformPackage = pkg;
11326                    pkg.mVersionCode = mSdkVersion;
11327                    mAndroidApplication = pkg.applicationInfo;
11328                    if (!mResolverReplaced) {
11329                        mResolveActivity.applicationInfo = mAndroidApplication;
11330                        mResolveActivity.name = ResolverActivity.class.getName();
11331                        mResolveActivity.packageName = mAndroidApplication.packageName;
11332                        mResolveActivity.processName = "system:ui";
11333                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11334                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11335                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11336                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11337                        mResolveActivity.exported = true;
11338                        mResolveActivity.enabled = true;
11339                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11340                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11341                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11342                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11343                                | ActivityInfo.CONFIG_ORIENTATION
11344                                | ActivityInfo.CONFIG_KEYBOARD
11345                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11346                        mResolveInfo.activityInfo = mResolveActivity;
11347                        mResolveInfo.priority = 0;
11348                        mResolveInfo.preferredOrder = 0;
11349                        mResolveInfo.match = 0;
11350                        mResolveComponentName = new ComponentName(
11351                                mAndroidApplication.packageName, mResolveActivity.name);
11352                    }
11353                }
11354            }
11355        }
11356
11357        ArrayList<PackageParser.Package> clientLibPkgs = null;
11358        // writer
11359        synchronized (mPackages) {
11360            boolean hasStaticSharedLibs = false;
11361
11362            // Any app can add new static shared libraries
11363            if (pkg.staticSharedLibName != null) {
11364                // Static shared libs don't allow renaming as they have synthetic package
11365                // names to allow install of multiple versions, so use name from manifest.
11366                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11367                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11368                        pkg.manifestPackageName, pkg.mVersionCode)) {
11369                    hasStaticSharedLibs = true;
11370                } else {
11371                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11372                                + pkg.staticSharedLibName + " already exists; skipping");
11373                }
11374                // Static shared libs cannot be updated once installed since they
11375                // use synthetic package name which includes the version code, so
11376                // not need to update other packages's shared lib dependencies.
11377            }
11378
11379            if (!hasStaticSharedLibs
11380                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11381                // Only system apps can add new dynamic shared libraries.
11382                if (pkg.libraryNames != null) {
11383                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11384                        String name = pkg.libraryNames.get(i);
11385                        boolean allowed = false;
11386                        if (pkg.isUpdatedSystemApp()) {
11387                            // New library entries can only be added through the
11388                            // system image.  This is important to get rid of a lot
11389                            // of nasty edge cases: for example if we allowed a non-
11390                            // system update of the app to add a library, then uninstalling
11391                            // the update would make the library go away, and assumptions
11392                            // we made such as through app install filtering would now
11393                            // have allowed apps on the device which aren't compatible
11394                            // with it.  Better to just have the restriction here, be
11395                            // conservative, and create many fewer cases that can negatively
11396                            // impact the user experience.
11397                            final PackageSetting sysPs = mSettings
11398                                    .getDisabledSystemPkgLPr(pkg.packageName);
11399                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11400                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11401                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11402                                        allowed = true;
11403                                        break;
11404                                    }
11405                                }
11406                            }
11407                        } else {
11408                            allowed = true;
11409                        }
11410                        if (allowed) {
11411                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11412                                    SharedLibraryInfo.VERSION_UNDEFINED,
11413                                    SharedLibraryInfo.TYPE_DYNAMIC,
11414                                    pkg.packageName, pkg.mVersionCode)) {
11415                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11416                                        + name + " already exists; skipping");
11417                            }
11418                        } else {
11419                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11420                                    + name + " that is not declared on system image; skipping");
11421                        }
11422                    }
11423
11424                    if ((scanFlags & SCAN_BOOTING) == 0) {
11425                        // If we are not booting, we need to update any applications
11426                        // that are clients of our shared library.  If we are booting,
11427                        // this will all be done once the scan is complete.
11428                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11429                    }
11430                }
11431            }
11432        }
11433
11434        if ((scanFlags & SCAN_BOOTING) != 0) {
11435            // No apps can run during boot scan, so they don't need to be frozen
11436        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11437            // Caller asked to not kill app, so it's probably not frozen
11438        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11439            // Caller asked us to ignore frozen check for some reason; they
11440            // probably didn't know the package name
11441        } else {
11442            // We're doing major surgery on this package, so it better be frozen
11443            // right now to keep it from launching
11444            checkPackageFrozen(pkgName);
11445        }
11446
11447        // Also need to kill any apps that are dependent on the library.
11448        if (clientLibPkgs != null) {
11449            for (int i=0; i<clientLibPkgs.size(); i++) {
11450                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11451                killApplication(clientPkg.applicationInfo.packageName,
11452                        clientPkg.applicationInfo.uid, "update lib");
11453            }
11454        }
11455
11456        // writer
11457        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11458
11459        synchronized (mPackages) {
11460            // We don't expect installation to fail beyond this point
11461
11462            // Add the new setting to mSettings
11463            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11464            // Add the new setting to mPackages
11465            mPackages.put(pkg.applicationInfo.packageName, pkg);
11466            // Make sure we don't accidentally delete its data.
11467            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11468            while (iter.hasNext()) {
11469                PackageCleanItem item = iter.next();
11470                if (pkgName.equals(item.packageName)) {
11471                    iter.remove();
11472                }
11473            }
11474
11475            // Add the package's KeySets to the global KeySetManagerService
11476            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11477            ksms.addScannedPackageLPw(pkg);
11478
11479            int N = pkg.providers.size();
11480            StringBuilder r = null;
11481            int i;
11482            for (i=0; i<N; i++) {
11483                PackageParser.Provider p = pkg.providers.get(i);
11484                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11485                        p.info.processName);
11486                mProviders.addProvider(p);
11487                p.syncable = p.info.isSyncable;
11488                if (p.info.authority != null) {
11489                    String names[] = p.info.authority.split(";");
11490                    p.info.authority = null;
11491                    for (int j = 0; j < names.length; j++) {
11492                        if (j == 1 && p.syncable) {
11493                            // We only want the first authority for a provider to possibly be
11494                            // syncable, so if we already added this provider using a different
11495                            // authority clear the syncable flag. We copy the provider before
11496                            // changing it because the mProviders object contains a reference
11497                            // to a provider that we don't want to change.
11498                            // Only do this for the second authority since the resulting provider
11499                            // object can be the same for all future authorities for this provider.
11500                            p = new PackageParser.Provider(p);
11501                            p.syncable = false;
11502                        }
11503                        if (!mProvidersByAuthority.containsKey(names[j])) {
11504                            mProvidersByAuthority.put(names[j], p);
11505                            if (p.info.authority == null) {
11506                                p.info.authority = names[j];
11507                            } else {
11508                                p.info.authority = p.info.authority + ";" + names[j];
11509                            }
11510                            if (DEBUG_PACKAGE_SCANNING) {
11511                                if (chatty)
11512                                    Log.d(TAG, "Registered content provider: " + names[j]
11513                                            + ", className = " + p.info.name + ", isSyncable = "
11514                                            + p.info.isSyncable);
11515                            }
11516                        } else {
11517                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11518                            Slog.w(TAG, "Skipping provider name " + names[j] +
11519                                    " (in package " + pkg.applicationInfo.packageName +
11520                                    "): name already used by "
11521                                    + ((other != null && other.getComponentName() != null)
11522                                            ? other.getComponentName().getPackageName() : "?"));
11523                        }
11524                    }
11525                }
11526                if (chatty) {
11527                    if (r == null) {
11528                        r = new StringBuilder(256);
11529                    } else {
11530                        r.append(' ');
11531                    }
11532                    r.append(p.info.name);
11533                }
11534            }
11535            if (r != null) {
11536                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11537            }
11538
11539            N = pkg.services.size();
11540            r = null;
11541            for (i=0; i<N; i++) {
11542                PackageParser.Service s = pkg.services.get(i);
11543                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11544                        s.info.processName);
11545                mServices.addService(s);
11546                if (chatty) {
11547                    if (r == null) {
11548                        r = new StringBuilder(256);
11549                    } else {
11550                        r.append(' ');
11551                    }
11552                    r.append(s.info.name);
11553                }
11554            }
11555            if (r != null) {
11556                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11557            }
11558
11559            N = pkg.receivers.size();
11560            r = null;
11561            for (i=0; i<N; i++) {
11562                PackageParser.Activity a = pkg.receivers.get(i);
11563                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11564                        a.info.processName);
11565                mReceivers.addActivity(a, "receiver");
11566                if (chatty) {
11567                    if (r == null) {
11568                        r = new StringBuilder(256);
11569                    } else {
11570                        r.append(' ');
11571                    }
11572                    r.append(a.info.name);
11573                }
11574            }
11575            if (r != null) {
11576                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11577            }
11578
11579            N = pkg.activities.size();
11580            r = null;
11581            for (i=0; i<N; i++) {
11582                PackageParser.Activity a = pkg.activities.get(i);
11583                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11584                        a.info.processName);
11585                mActivities.addActivity(a, "activity");
11586                if (chatty) {
11587                    if (r == null) {
11588                        r = new StringBuilder(256);
11589                    } else {
11590                        r.append(' ');
11591                    }
11592                    r.append(a.info.name);
11593                }
11594            }
11595            if (r != null) {
11596                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11597            }
11598
11599            N = pkg.permissionGroups.size();
11600            r = null;
11601            for (i=0; i<N; i++) {
11602                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11603                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11604                final String curPackageName = cur == null ? null : cur.info.packageName;
11605                // Dont allow ephemeral apps to define new permission groups.
11606                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11607                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11608                            + pg.info.packageName
11609                            + " ignored: instant apps cannot define new permission groups.");
11610                    continue;
11611                }
11612                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11613                if (cur == null || isPackageUpdate) {
11614                    mPermissionGroups.put(pg.info.name, pg);
11615                    if (chatty) {
11616                        if (r == null) {
11617                            r = new StringBuilder(256);
11618                        } else {
11619                            r.append(' ');
11620                        }
11621                        if (isPackageUpdate) {
11622                            r.append("UPD:");
11623                        }
11624                        r.append(pg.info.name);
11625                    }
11626                } else {
11627                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11628                            + pg.info.packageName + " ignored: original from "
11629                            + cur.info.packageName);
11630                    if (chatty) {
11631                        if (r == null) {
11632                            r = new StringBuilder(256);
11633                        } else {
11634                            r.append(' ');
11635                        }
11636                        r.append("DUP:");
11637                        r.append(pg.info.name);
11638                    }
11639                }
11640            }
11641            if (r != null) {
11642                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11643            }
11644
11645            N = pkg.permissions.size();
11646            r = null;
11647            for (i=0; i<N; i++) {
11648                PackageParser.Permission p = pkg.permissions.get(i);
11649
11650                // Dont allow ephemeral apps to define new permissions.
11651                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11652                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11653                            + p.info.packageName
11654                            + " ignored: instant apps cannot define new permissions.");
11655                    continue;
11656                }
11657
11658                // Assume by default that we did not install this permission into the system.
11659                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11660
11661                // Now that permission groups have a special meaning, we ignore permission
11662                // groups for legacy apps to prevent unexpected behavior. In particular,
11663                // permissions for one app being granted to someone just because they happen
11664                // to be in a group defined by another app (before this had no implications).
11665                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11666                    p.group = mPermissionGroups.get(p.info.group);
11667                    // Warn for a permission in an unknown group.
11668                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11669                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11670                                + p.info.packageName + " in an unknown group " + p.info.group);
11671                    }
11672                }
11673
11674                ArrayMap<String, BasePermission> permissionMap =
11675                        p.tree ? mSettings.mPermissionTrees
11676                                : mSettings.mPermissions;
11677                BasePermission bp = permissionMap.get(p.info.name);
11678
11679                // Allow system apps to redefine non-system permissions
11680                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11681                    final boolean currentOwnerIsSystem = (bp.perm != null
11682                            && isSystemApp(bp.perm.owner));
11683                    if (isSystemApp(p.owner)) {
11684                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11685                            // It's a built-in permission and no owner, take ownership now
11686                            bp.packageSetting = pkgSetting;
11687                            bp.perm = p;
11688                            bp.uid = pkg.applicationInfo.uid;
11689                            bp.sourcePackage = p.info.packageName;
11690                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11691                        } else if (!currentOwnerIsSystem) {
11692                            String msg = "New decl " + p.owner + " of permission  "
11693                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11694                            reportSettingsProblem(Log.WARN, msg);
11695                            bp = null;
11696                        }
11697                    }
11698                }
11699
11700                if (bp == null) {
11701                    bp = new BasePermission(p.info.name, p.info.packageName,
11702                            BasePermission.TYPE_NORMAL);
11703                    permissionMap.put(p.info.name, bp);
11704                }
11705
11706                if (bp.perm == null) {
11707                    if (bp.sourcePackage == null
11708                            || bp.sourcePackage.equals(p.info.packageName)) {
11709                        BasePermission tree = findPermissionTreeLP(p.info.name);
11710                        if (tree == null
11711                                || tree.sourcePackage.equals(p.info.packageName)) {
11712                            bp.packageSetting = pkgSetting;
11713                            bp.perm = p;
11714                            bp.uid = pkg.applicationInfo.uid;
11715                            bp.sourcePackage = p.info.packageName;
11716                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11717                            if (chatty) {
11718                                if (r == null) {
11719                                    r = new StringBuilder(256);
11720                                } else {
11721                                    r.append(' ');
11722                                }
11723                                r.append(p.info.name);
11724                            }
11725                        } else {
11726                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11727                                    + p.info.packageName + " ignored: base tree "
11728                                    + tree.name + " is from package "
11729                                    + tree.sourcePackage);
11730                        }
11731                    } else {
11732                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11733                                + p.info.packageName + " ignored: original from "
11734                                + bp.sourcePackage);
11735                    }
11736                } else if (chatty) {
11737                    if (r == null) {
11738                        r = new StringBuilder(256);
11739                    } else {
11740                        r.append(' ');
11741                    }
11742                    r.append("DUP:");
11743                    r.append(p.info.name);
11744                }
11745                if (bp.perm == p) {
11746                    bp.protectionLevel = p.info.protectionLevel;
11747                }
11748            }
11749
11750            if (r != null) {
11751                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11752            }
11753
11754            N = pkg.instrumentation.size();
11755            r = null;
11756            for (i=0; i<N; i++) {
11757                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11758                a.info.packageName = pkg.applicationInfo.packageName;
11759                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11760                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11761                a.info.splitNames = pkg.splitNames;
11762                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11763                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11764                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11765                a.info.dataDir = pkg.applicationInfo.dataDir;
11766                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11767                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11768                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11769                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11770                mInstrumentation.put(a.getComponentName(), a);
11771                if (chatty) {
11772                    if (r == null) {
11773                        r = new StringBuilder(256);
11774                    } else {
11775                        r.append(' ');
11776                    }
11777                    r.append(a.info.name);
11778                }
11779            }
11780            if (r != null) {
11781                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11782            }
11783
11784            if (pkg.protectedBroadcasts != null) {
11785                N = pkg.protectedBroadcasts.size();
11786                synchronized (mProtectedBroadcasts) {
11787                    for (i = 0; i < N; i++) {
11788                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11789                    }
11790                }
11791            }
11792        }
11793
11794        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11795    }
11796
11797    /**
11798     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11799     * is derived purely on the basis of the contents of {@code scanFile} and
11800     * {@code cpuAbiOverride}.
11801     *
11802     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11803     */
11804    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11805                                 String cpuAbiOverride, boolean extractLibs,
11806                                 File appLib32InstallDir)
11807            throws PackageManagerException {
11808        // Give ourselves some initial paths; we'll come back for another
11809        // pass once we've determined ABI below.
11810        setNativeLibraryPaths(pkg, appLib32InstallDir);
11811
11812        // We would never need to extract libs for forward-locked and external packages,
11813        // since the container service will do it for us. We shouldn't attempt to
11814        // extract libs from system app when it was not updated.
11815        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11816                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11817            extractLibs = false;
11818        }
11819
11820        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11821        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11822
11823        NativeLibraryHelper.Handle handle = null;
11824        try {
11825            handle = NativeLibraryHelper.Handle.create(pkg);
11826            // TODO(multiArch): This can be null for apps that didn't go through the
11827            // usual installation process. We can calculate it again, like we
11828            // do during install time.
11829            //
11830            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11831            // unnecessary.
11832            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11833
11834            // Null out the abis so that they can be recalculated.
11835            pkg.applicationInfo.primaryCpuAbi = null;
11836            pkg.applicationInfo.secondaryCpuAbi = null;
11837            if (isMultiArch(pkg.applicationInfo)) {
11838                // Warn if we've set an abiOverride for multi-lib packages..
11839                // By definition, we need to copy both 32 and 64 bit libraries for
11840                // such packages.
11841                if (pkg.cpuAbiOverride != null
11842                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11843                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11844                }
11845
11846                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11847                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11848                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11849                    if (extractLibs) {
11850                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11851                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11852                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11853                                useIsaSpecificSubdirs);
11854                    } else {
11855                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11856                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11857                    }
11858                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11859                }
11860
11861                // Shared library native code should be in the APK zip aligned
11862                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11863                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11864                            "Shared library native lib extraction not supported");
11865                }
11866
11867                maybeThrowExceptionForMultiArchCopy(
11868                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11869
11870                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11871                    if (extractLibs) {
11872                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11873                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11874                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11875                                useIsaSpecificSubdirs);
11876                    } else {
11877                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11878                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11879                    }
11880                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11881                }
11882
11883                maybeThrowExceptionForMultiArchCopy(
11884                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11885
11886                if (abi64 >= 0) {
11887                    // Shared library native libs should be in the APK zip aligned
11888                    if (extractLibs && pkg.isLibrary()) {
11889                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11890                                "Shared library native lib extraction not supported");
11891                    }
11892                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11893                }
11894
11895                if (abi32 >= 0) {
11896                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11897                    if (abi64 >= 0) {
11898                        if (pkg.use32bitAbi) {
11899                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11900                            pkg.applicationInfo.primaryCpuAbi = abi;
11901                        } else {
11902                            pkg.applicationInfo.secondaryCpuAbi = abi;
11903                        }
11904                    } else {
11905                        pkg.applicationInfo.primaryCpuAbi = abi;
11906                    }
11907                }
11908            } else {
11909                String[] abiList = (cpuAbiOverride != null) ?
11910                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11911
11912                // Enable gross and lame hacks for apps that are built with old
11913                // SDK tools. We must scan their APKs for renderscript bitcode and
11914                // not launch them if it's present. Don't bother checking on devices
11915                // that don't have 64 bit support.
11916                boolean needsRenderScriptOverride = false;
11917                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11918                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11919                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11920                    needsRenderScriptOverride = true;
11921                }
11922
11923                final int copyRet;
11924                if (extractLibs) {
11925                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11926                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11927                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11928                } else {
11929                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11930                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11931                }
11932                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11933
11934                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11935                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11936                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11937                }
11938
11939                if (copyRet >= 0) {
11940                    // Shared libraries that have native libs must be multi-architecture
11941                    if (pkg.isLibrary()) {
11942                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11943                                "Shared library with native libs must be multiarch");
11944                    }
11945                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11946                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11947                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11948                } else if (needsRenderScriptOverride) {
11949                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11950                }
11951            }
11952        } catch (IOException ioe) {
11953            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11954        } finally {
11955            IoUtils.closeQuietly(handle);
11956        }
11957
11958        // Now that we've calculated the ABIs and determined if it's an internal app,
11959        // we will go ahead and populate the nativeLibraryPath.
11960        setNativeLibraryPaths(pkg, appLib32InstallDir);
11961    }
11962
11963    /**
11964     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11965     * i.e, so that all packages can be run inside a single process if required.
11966     *
11967     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11968     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11969     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11970     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11971     * updating a package that belongs to a shared user.
11972     *
11973     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11974     * adds unnecessary complexity.
11975     */
11976    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11977            PackageParser.Package scannedPackage) {
11978        String requiredInstructionSet = null;
11979        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11980            requiredInstructionSet = VMRuntime.getInstructionSet(
11981                     scannedPackage.applicationInfo.primaryCpuAbi);
11982        }
11983
11984        PackageSetting requirer = null;
11985        for (PackageSetting ps : packagesForUser) {
11986            // If packagesForUser contains scannedPackage, we skip it. This will happen
11987            // when scannedPackage is an update of an existing package. Without this check,
11988            // we will never be able to change the ABI of any package belonging to a shared
11989            // user, even if it's compatible with other packages.
11990            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11991                if (ps.primaryCpuAbiString == null) {
11992                    continue;
11993                }
11994
11995                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11996                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11997                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11998                    // this but there's not much we can do.
11999                    String errorMessage = "Instruction set mismatch, "
12000                            + ((requirer == null) ? "[caller]" : requirer)
12001                            + " requires " + requiredInstructionSet + " whereas " + ps
12002                            + " requires " + instructionSet;
12003                    Slog.w(TAG, errorMessage);
12004                }
12005
12006                if (requiredInstructionSet == null) {
12007                    requiredInstructionSet = instructionSet;
12008                    requirer = ps;
12009                }
12010            }
12011        }
12012
12013        if (requiredInstructionSet != null) {
12014            String adjustedAbi;
12015            if (requirer != null) {
12016                // requirer != null implies that either scannedPackage was null or that scannedPackage
12017                // did not require an ABI, in which case we have to adjust scannedPackage to match
12018                // the ABI of the set (which is the same as requirer's ABI)
12019                adjustedAbi = requirer.primaryCpuAbiString;
12020                if (scannedPackage != null) {
12021                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12022                }
12023            } else {
12024                // requirer == null implies that we're updating all ABIs in the set to
12025                // match scannedPackage.
12026                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12027            }
12028
12029            for (PackageSetting ps : packagesForUser) {
12030                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12031                    if (ps.primaryCpuAbiString != null) {
12032                        continue;
12033                    }
12034
12035                    ps.primaryCpuAbiString = adjustedAbi;
12036                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12037                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12038                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12039                        if (DEBUG_ABI_SELECTION) {
12040                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12041                                    + " (requirer="
12042                                    + (requirer != null ? requirer.pkg : "null")
12043                                    + ", scannedPackage="
12044                                    + (scannedPackage != null ? scannedPackage : "null")
12045                                    + ")");
12046                        }
12047                        try {
12048                            mInstaller.rmdex(ps.codePathString,
12049                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12050                        } catch (InstallerException ignored) {
12051                        }
12052                    }
12053                }
12054            }
12055        }
12056    }
12057
12058    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12059        synchronized (mPackages) {
12060            mResolverReplaced = true;
12061            // Set up information for custom user intent resolution activity.
12062            mResolveActivity.applicationInfo = pkg.applicationInfo;
12063            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12064            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12065            mResolveActivity.processName = pkg.applicationInfo.packageName;
12066            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12067            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12068                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12069            mResolveActivity.theme = 0;
12070            mResolveActivity.exported = true;
12071            mResolveActivity.enabled = true;
12072            mResolveInfo.activityInfo = mResolveActivity;
12073            mResolveInfo.priority = 0;
12074            mResolveInfo.preferredOrder = 0;
12075            mResolveInfo.match = 0;
12076            mResolveComponentName = mCustomResolverComponentName;
12077            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12078                    mResolveComponentName);
12079        }
12080    }
12081
12082    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12083        if (installerActivity == null) {
12084            if (DEBUG_EPHEMERAL) {
12085                Slog.d(TAG, "Clear ephemeral installer activity");
12086            }
12087            mInstantAppInstallerActivity = null;
12088            return;
12089        }
12090
12091        if (DEBUG_EPHEMERAL) {
12092            Slog.d(TAG, "Set ephemeral installer activity: "
12093                    + installerActivity.getComponentName());
12094        }
12095        // Set up information for ephemeral installer activity
12096        mInstantAppInstallerActivity = installerActivity;
12097        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12098                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12099        mInstantAppInstallerActivity.exported = true;
12100        mInstantAppInstallerActivity.enabled = true;
12101        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12102        mInstantAppInstallerInfo.priority = 0;
12103        mInstantAppInstallerInfo.preferredOrder = 1;
12104        mInstantAppInstallerInfo.isDefault = true;
12105        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12106                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12107    }
12108
12109    private static String calculateBundledApkRoot(final String codePathString) {
12110        final File codePath = new File(codePathString);
12111        final File codeRoot;
12112        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12113            codeRoot = Environment.getRootDirectory();
12114        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12115            codeRoot = Environment.getOemDirectory();
12116        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12117            codeRoot = Environment.getVendorDirectory();
12118        } else {
12119            // Unrecognized code path; take its top real segment as the apk root:
12120            // e.g. /something/app/blah.apk => /something
12121            try {
12122                File f = codePath.getCanonicalFile();
12123                File parent = f.getParentFile();    // non-null because codePath is a file
12124                File tmp;
12125                while ((tmp = parent.getParentFile()) != null) {
12126                    f = parent;
12127                    parent = tmp;
12128                }
12129                codeRoot = f;
12130                Slog.w(TAG, "Unrecognized code path "
12131                        + codePath + " - using " + codeRoot);
12132            } catch (IOException e) {
12133                // Can't canonicalize the code path -- shenanigans?
12134                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12135                return Environment.getRootDirectory().getPath();
12136            }
12137        }
12138        return codeRoot.getPath();
12139    }
12140
12141    /**
12142     * Derive and set the location of native libraries for the given package,
12143     * which varies depending on where and how the package was installed.
12144     */
12145    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12146        final ApplicationInfo info = pkg.applicationInfo;
12147        final String codePath = pkg.codePath;
12148        final File codeFile = new File(codePath);
12149        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12150        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12151
12152        info.nativeLibraryRootDir = null;
12153        info.nativeLibraryRootRequiresIsa = false;
12154        info.nativeLibraryDir = null;
12155        info.secondaryNativeLibraryDir = null;
12156
12157        if (isApkFile(codeFile)) {
12158            // Monolithic install
12159            if (bundledApp) {
12160                // If "/system/lib64/apkname" exists, assume that is the per-package
12161                // native library directory to use; otherwise use "/system/lib/apkname".
12162                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12163                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12164                        getPrimaryInstructionSet(info));
12165
12166                // This is a bundled system app so choose the path based on the ABI.
12167                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12168                // is just the default path.
12169                final String apkName = deriveCodePathName(codePath);
12170                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12171                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12172                        apkName).getAbsolutePath();
12173
12174                if (info.secondaryCpuAbi != null) {
12175                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12176                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12177                            secondaryLibDir, apkName).getAbsolutePath();
12178                }
12179            } else if (asecApp) {
12180                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12181                        .getAbsolutePath();
12182            } else {
12183                final String apkName = deriveCodePathName(codePath);
12184                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12185                        .getAbsolutePath();
12186            }
12187
12188            info.nativeLibraryRootRequiresIsa = false;
12189            info.nativeLibraryDir = info.nativeLibraryRootDir;
12190        } else {
12191            // Cluster install
12192            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12193            info.nativeLibraryRootRequiresIsa = true;
12194
12195            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12196                    getPrimaryInstructionSet(info)).getAbsolutePath();
12197
12198            if (info.secondaryCpuAbi != null) {
12199                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12200                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12201            }
12202        }
12203    }
12204
12205    /**
12206     * Calculate the abis and roots for a bundled app. These can uniquely
12207     * be determined from the contents of the system partition, i.e whether
12208     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12209     * of this information, and instead assume that the system was built
12210     * sensibly.
12211     */
12212    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12213                                           PackageSetting pkgSetting) {
12214        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12215
12216        // If "/system/lib64/apkname" exists, assume that is the per-package
12217        // native library directory to use; otherwise use "/system/lib/apkname".
12218        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12219        setBundledAppAbi(pkg, apkRoot, apkName);
12220        // pkgSetting might be null during rescan following uninstall of updates
12221        // to a bundled app, so accommodate that possibility.  The settings in
12222        // that case will be established later from the parsed package.
12223        //
12224        // If the settings aren't null, sync them up with what we've just derived.
12225        // note that apkRoot isn't stored in the package settings.
12226        if (pkgSetting != null) {
12227            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12228            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12229        }
12230    }
12231
12232    /**
12233     * Deduces the ABI of a bundled app and sets the relevant fields on the
12234     * parsed pkg object.
12235     *
12236     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12237     *        under which system libraries are installed.
12238     * @param apkName the name of the installed package.
12239     */
12240    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12241        final File codeFile = new File(pkg.codePath);
12242
12243        final boolean has64BitLibs;
12244        final boolean has32BitLibs;
12245        if (isApkFile(codeFile)) {
12246            // Monolithic install
12247            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12248            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12249        } else {
12250            // Cluster install
12251            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12252            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12253                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12254                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12255                has64BitLibs = (new File(rootDir, isa)).exists();
12256            } else {
12257                has64BitLibs = false;
12258            }
12259            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12260                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12261                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12262                has32BitLibs = (new File(rootDir, isa)).exists();
12263            } else {
12264                has32BitLibs = false;
12265            }
12266        }
12267
12268        if (has64BitLibs && !has32BitLibs) {
12269            // The package has 64 bit libs, but not 32 bit libs. Its primary
12270            // ABI should be 64 bit. We can safely assume here that the bundled
12271            // native libraries correspond to the most preferred ABI in the list.
12272
12273            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12274            pkg.applicationInfo.secondaryCpuAbi = null;
12275        } else if (has32BitLibs && !has64BitLibs) {
12276            // The package has 32 bit libs but not 64 bit libs. Its primary
12277            // ABI should be 32 bit.
12278
12279            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12280            pkg.applicationInfo.secondaryCpuAbi = null;
12281        } else if (has32BitLibs && has64BitLibs) {
12282            // The application has both 64 and 32 bit bundled libraries. We check
12283            // here that the app declares multiArch support, and warn if it doesn't.
12284            //
12285            // We will be lenient here and record both ABIs. The primary will be the
12286            // ABI that's higher on the list, i.e, a device that's configured to prefer
12287            // 64 bit apps will see a 64 bit primary ABI,
12288
12289            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12290                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12291            }
12292
12293            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12294                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12295                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12296            } else {
12297                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12298                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12299            }
12300        } else {
12301            pkg.applicationInfo.primaryCpuAbi = null;
12302            pkg.applicationInfo.secondaryCpuAbi = null;
12303        }
12304    }
12305
12306    private void killApplication(String pkgName, int appId, String reason) {
12307        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12308    }
12309
12310    private void killApplication(String pkgName, int appId, int userId, String reason) {
12311        // Request the ActivityManager to kill the process(only for existing packages)
12312        // so that we do not end up in a confused state while the user is still using the older
12313        // version of the application while the new one gets installed.
12314        final long token = Binder.clearCallingIdentity();
12315        try {
12316            IActivityManager am = ActivityManager.getService();
12317            if (am != null) {
12318                try {
12319                    am.killApplication(pkgName, appId, userId, reason);
12320                } catch (RemoteException e) {
12321                }
12322            }
12323        } finally {
12324            Binder.restoreCallingIdentity(token);
12325        }
12326    }
12327
12328    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12329        // Remove the parent package setting
12330        PackageSetting ps = (PackageSetting) pkg.mExtras;
12331        if (ps != null) {
12332            removePackageLI(ps, chatty);
12333        }
12334        // Remove the child package setting
12335        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12336        for (int i = 0; i < childCount; i++) {
12337            PackageParser.Package childPkg = pkg.childPackages.get(i);
12338            ps = (PackageSetting) childPkg.mExtras;
12339            if (ps != null) {
12340                removePackageLI(ps, chatty);
12341            }
12342        }
12343    }
12344
12345    void removePackageLI(PackageSetting ps, boolean chatty) {
12346        if (DEBUG_INSTALL) {
12347            if (chatty)
12348                Log.d(TAG, "Removing package " + ps.name);
12349        }
12350
12351        // writer
12352        synchronized (mPackages) {
12353            mPackages.remove(ps.name);
12354            final PackageParser.Package pkg = ps.pkg;
12355            if (pkg != null) {
12356                cleanPackageDataStructuresLILPw(pkg, chatty);
12357            }
12358        }
12359    }
12360
12361    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12362        if (DEBUG_INSTALL) {
12363            if (chatty)
12364                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12365        }
12366
12367        // writer
12368        synchronized (mPackages) {
12369            // Remove the parent package
12370            mPackages.remove(pkg.applicationInfo.packageName);
12371            cleanPackageDataStructuresLILPw(pkg, chatty);
12372
12373            // Remove the child packages
12374            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12375            for (int i = 0; i < childCount; i++) {
12376                PackageParser.Package childPkg = pkg.childPackages.get(i);
12377                mPackages.remove(childPkg.applicationInfo.packageName);
12378                cleanPackageDataStructuresLILPw(childPkg, chatty);
12379            }
12380        }
12381    }
12382
12383    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12384        int N = pkg.providers.size();
12385        StringBuilder r = null;
12386        int i;
12387        for (i=0; i<N; i++) {
12388            PackageParser.Provider p = pkg.providers.get(i);
12389            mProviders.removeProvider(p);
12390            if (p.info.authority == null) {
12391
12392                /* There was another ContentProvider with this authority when
12393                 * this app was installed so this authority is null,
12394                 * Ignore it as we don't have to unregister the provider.
12395                 */
12396                continue;
12397            }
12398            String names[] = p.info.authority.split(";");
12399            for (int j = 0; j < names.length; j++) {
12400                if (mProvidersByAuthority.get(names[j]) == p) {
12401                    mProvidersByAuthority.remove(names[j]);
12402                    if (DEBUG_REMOVE) {
12403                        if (chatty)
12404                            Log.d(TAG, "Unregistered content provider: " + names[j]
12405                                    + ", className = " + p.info.name + ", isSyncable = "
12406                                    + p.info.isSyncable);
12407                    }
12408                }
12409            }
12410            if (DEBUG_REMOVE && chatty) {
12411                if (r == null) {
12412                    r = new StringBuilder(256);
12413                } else {
12414                    r.append(' ');
12415                }
12416                r.append(p.info.name);
12417            }
12418        }
12419        if (r != null) {
12420            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12421        }
12422
12423        N = pkg.services.size();
12424        r = null;
12425        for (i=0; i<N; i++) {
12426            PackageParser.Service s = pkg.services.get(i);
12427            mServices.removeService(s);
12428            if (chatty) {
12429                if (r == null) {
12430                    r = new StringBuilder(256);
12431                } else {
12432                    r.append(' ');
12433                }
12434                r.append(s.info.name);
12435            }
12436        }
12437        if (r != null) {
12438            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12439        }
12440
12441        N = pkg.receivers.size();
12442        r = null;
12443        for (i=0; i<N; i++) {
12444            PackageParser.Activity a = pkg.receivers.get(i);
12445            mReceivers.removeActivity(a, "receiver");
12446            if (DEBUG_REMOVE && chatty) {
12447                if (r == null) {
12448                    r = new StringBuilder(256);
12449                } else {
12450                    r.append(' ');
12451                }
12452                r.append(a.info.name);
12453            }
12454        }
12455        if (r != null) {
12456            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12457        }
12458
12459        N = pkg.activities.size();
12460        r = null;
12461        for (i=0; i<N; i++) {
12462            PackageParser.Activity a = pkg.activities.get(i);
12463            mActivities.removeActivity(a, "activity");
12464            if (DEBUG_REMOVE && chatty) {
12465                if (r == null) {
12466                    r = new StringBuilder(256);
12467                } else {
12468                    r.append(' ');
12469                }
12470                r.append(a.info.name);
12471            }
12472        }
12473        if (r != null) {
12474            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12475        }
12476
12477        N = pkg.permissions.size();
12478        r = null;
12479        for (i=0; i<N; i++) {
12480            PackageParser.Permission p = pkg.permissions.get(i);
12481            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12482            if (bp == null) {
12483                bp = mSettings.mPermissionTrees.get(p.info.name);
12484            }
12485            if (bp != null && bp.perm == p) {
12486                bp.perm = null;
12487                if (DEBUG_REMOVE && chatty) {
12488                    if (r == null) {
12489                        r = new StringBuilder(256);
12490                    } else {
12491                        r.append(' ');
12492                    }
12493                    r.append(p.info.name);
12494                }
12495            }
12496            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12497                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12498                if (appOpPkgs != null) {
12499                    appOpPkgs.remove(pkg.packageName);
12500                }
12501            }
12502        }
12503        if (r != null) {
12504            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12505        }
12506
12507        N = pkg.requestedPermissions.size();
12508        r = null;
12509        for (i=0; i<N; i++) {
12510            String perm = pkg.requestedPermissions.get(i);
12511            BasePermission bp = mSettings.mPermissions.get(perm);
12512            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12513                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12514                if (appOpPkgs != null) {
12515                    appOpPkgs.remove(pkg.packageName);
12516                    if (appOpPkgs.isEmpty()) {
12517                        mAppOpPermissionPackages.remove(perm);
12518                    }
12519                }
12520            }
12521        }
12522        if (r != null) {
12523            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12524        }
12525
12526        N = pkg.instrumentation.size();
12527        r = null;
12528        for (i=0; i<N; i++) {
12529            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12530            mInstrumentation.remove(a.getComponentName());
12531            if (DEBUG_REMOVE && chatty) {
12532                if (r == null) {
12533                    r = new StringBuilder(256);
12534                } else {
12535                    r.append(' ');
12536                }
12537                r.append(a.info.name);
12538            }
12539        }
12540        if (r != null) {
12541            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12542        }
12543
12544        r = null;
12545        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12546            // Only system apps can hold shared libraries.
12547            if (pkg.libraryNames != null) {
12548                for (i = 0; i < pkg.libraryNames.size(); i++) {
12549                    String name = pkg.libraryNames.get(i);
12550                    if (removeSharedLibraryLPw(name, 0)) {
12551                        if (DEBUG_REMOVE && chatty) {
12552                            if (r == null) {
12553                                r = new StringBuilder(256);
12554                            } else {
12555                                r.append(' ');
12556                            }
12557                            r.append(name);
12558                        }
12559                    }
12560                }
12561            }
12562        }
12563
12564        r = null;
12565
12566        // Any package can hold static shared libraries.
12567        if (pkg.staticSharedLibName != null) {
12568            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12569                if (DEBUG_REMOVE && chatty) {
12570                    if (r == null) {
12571                        r = new StringBuilder(256);
12572                    } else {
12573                        r.append(' ');
12574                    }
12575                    r.append(pkg.staticSharedLibName);
12576                }
12577            }
12578        }
12579
12580        if (r != null) {
12581            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12582        }
12583    }
12584
12585    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12586        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12587            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12588                return true;
12589            }
12590        }
12591        return false;
12592    }
12593
12594    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12595    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12596    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12597
12598    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12599        // Update the parent permissions
12600        updatePermissionsLPw(pkg.packageName, pkg, flags);
12601        // Update the child permissions
12602        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12603        for (int i = 0; i < childCount; i++) {
12604            PackageParser.Package childPkg = pkg.childPackages.get(i);
12605            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12606        }
12607    }
12608
12609    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12610            int flags) {
12611        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12612        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12613    }
12614
12615    private void updatePermissionsLPw(String changingPkg,
12616            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12617        // Make sure there are no dangling permission trees.
12618        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12619        while (it.hasNext()) {
12620            final BasePermission bp = it.next();
12621            if (bp.packageSetting == null) {
12622                // We may not yet have parsed the package, so just see if
12623                // we still know about its settings.
12624                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12625            }
12626            if (bp.packageSetting == null) {
12627                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12628                        + " from package " + bp.sourcePackage);
12629                it.remove();
12630            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12631                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12632                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12633                            + " from package " + bp.sourcePackage);
12634                    flags |= UPDATE_PERMISSIONS_ALL;
12635                    it.remove();
12636                }
12637            }
12638        }
12639
12640        // Make sure all dynamic permissions have been assigned to a package,
12641        // and make sure there are no dangling permissions.
12642        it = mSettings.mPermissions.values().iterator();
12643        while (it.hasNext()) {
12644            final BasePermission bp = it.next();
12645            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12646                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12647                        + bp.name + " pkg=" + bp.sourcePackage
12648                        + " info=" + bp.pendingInfo);
12649                if (bp.packageSetting == null && bp.pendingInfo != null) {
12650                    final BasePermission tree = findPermissionTreeLP(bp.name);
12651                    if (tree != null && tree.perm != null) {
12652                        bp.packageSetting = tree.packageSetting;
12653                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12654                                new PermissionInfo(bp.pendingInfo));
12655                        bp.perm.info.packageName = tree.perm.info.packageName;
12656                        bp.perm.info.name = bp.name;
12657                        bp.uid = tree.uid;
12658                    }
12659                }
12660            }
12661            if (bp.packageSetting == null) {
12662                // We may not yet have parsed the package, so just see if
12663                // we still know about its settings.
12664                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12665            }
12666            if (bp.packageSetting == null) {
12667                Slog.w(TAG, "Removing dangling permission: " + bp.name
12668                        + " from package " + bp.sourcePackage);
12669                it.remove();
12670            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12671                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12672                    Slog.i(TAG, "Removing old permission: " + bp.name
12673                            + " from package " + bp.sourcePackage);
12674                    flags |= UPDATE_PERMISSIONS_ALL;
12675                    it.remove();
12676                }
12677            }
12678        }
12679
12680        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12681        // Now update the permissions for all packages, in particular
12682        // replace the granted permissions of the system packages.
12683        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12684            for (PackageParser.Package pkg : mPackages.values()) {
12685                if (pkg != pkgInfo) {
12686                    // Only replace for packages on requested volume
12687                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12688                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12689                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12690                    grantPermissionsLPw(pkg, replace, changingPkg);
12691                }
12692            }
12693        }
12694
12695        if (pkgInfo != null) {
12696            // Only replace for packages on requested volume
12697            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12698            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12699                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12700            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12701        }
12702        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12703    }
12704
12705    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12706            String packageOfInterest) {
12707        // IMPORTANT: There are two types of permissions: install and runtime.
12708        // Install time permissions are granted when the app is installed to
12709        // all device users and users added in the future. Runtime permissions
12710        // are granted at runtime explicitly to specific users. Normal and signature
12711        // protected permissions are install time permissions. Dangerous permissions
12712        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12713        // otherwise they are runtime permissions. This function does not manage
12714        // runtime permissions except for the case an app targeting Lollipop MR1
12715        // being upgraded to target a newer SDK, in which case dangerous permissions
12716        // are transformed from install time to runtime ones.
12717
12718        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12719        if (ps == null) {
12720            return;
12721        }
12722
12723        PermissionsState permissionsState = ps.getPermissionsState();
12724        PermissionsState origPermissions = permissionsState;
12725
12726        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12727
12728        boolean runtimePermissionsRevoked = false;
12729        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12730
12731        boolean changedInstallPermission = false;
12732
12733        if (replace) {
12734            ps.installPermissionsFixed = false;
12735            if (!ps.isSharedUser()) {
12736                origPermissions = new PermissionsState(permissionsState);
12737                permissionsState.reset();
12738            } else {
12739                // We need to know only about runtime permission changes since the
12740                // calling code always writes the install permissions state but
12741                // the runtime ones are written only if changed. The only cases of
12742                // changed runtime permissions here are promotion of an install to
12743                // runtime and revocation of a runtime from a shared user.
12744                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12745                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12746                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12747                    runtimePermissionsRevoked = true;
12748                }
12749            }
12750        }
12751
12752        permissionsState.setGlobalGids(mGlobalGids);
12753
12754        final int N = pkg.requestedPermissions.size();
12755        for (int i=0; i<N; i++) {
12756            final String name = pkg.requestedPermissions.get(i);
12757            final BasePermission bp = mSettings.mPermissions.get(name);
12758            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12759                    >= Build.VERSION_CODES.M;
12760
12761            if (DEBUG_INSTALL) {
12762                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12763            }
12764
12765            if (bp == null || bp.packageSetting == null) {
12766                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12767                    if (DEBUG_PERMISSIONS) {
12768                        Slog.i(TAG, "Unknown permission " + name
12769                                + " in package " + pkg.packageName);
12770                    }
12771                }
12772                continue;
12773            }
12774
12775
12776            // Limit ephemeral apps to ephemeral allowed permissions.
12777            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12778                if (DEBUG_PERMISSIONS) {
12779                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12780                            + pkg.packageName);
12781                }
12782                continue;
12783            }
12784
12785            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12786                if (DEBUG_PERMISSIONS) {
12787                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12788                            + pkg.packageName);
12789                }
12790                continue;
12791            }
12792
12793            final String perm = bp.name;
12794            boolean allowedSig = false;
12795            int grant = GRANT_DENIED;
12796
12797            // Keep track of app op permissions.
12798            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12799                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12800                if (pkgs == null) {
12801                    pkgs = new ArraySet<>();
12802                    mAppOpPermissionPackages.put(bp.name, pkgs);
12803                }
12804                pkgs.add(pkg.packageName);
12805            }
12806
12807            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12808            switch (level) {
12809                case PermissionInfo.PROTECTION_NORMAL: {
12810                    // For all apps normal permissions are install time ones.
12811                    grant = GRANT_INSTALL;
12812                } break;
12813
12814                case PermissionInfo.PROTECTION_DANGEROUS: {
12815                    // If a permission review is required for legacy apps we represent
12816                    // their permissions as always granted runtime ones since we need
12817                    // to keep the review required permission flag per user while an
12818                    // install permission's state is shared across all users.
12819                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12820                        // For legacy apps dangerous permissions are install time ones.
12821                        grant = GRANT_INSTALL;
12822                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12823                        // For legacy apps that became modern, install becomes runtime.
12824                        grant = GRANT_UPGRADE;
12825                    } else if (mPromoteSystemApps
12826                            && isSystemApp(ps)
12827                            && mExistingSystemPackages.contains(ps.name)) {
12828                        // For legacy system apps, install becomes runtime.
12829                        // We cannot check hasInstallPermission() for system apps since those
12830                        // permissions were granted implicitly and not persisted pre-M.
12831                        grant = GRANT_UPGRADE;
12832                    } else {
12833                        // For modern apps keep runtime permissions unchanged.
12834                        grant = GRANT_RUNTIME;
12835                    }
12836                } break;
12837
12838                case PermissionInfo.PROTECTION_SIGNATURE: {
12839                    // For all apps signature permissions are install time ones.
12840                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12841                    if (allowedSig) {
12842                        grant = GRANT_INSTALL;
12843                    }
12844                } break;
12845            }
12846
12847            if (DEBUG_PERMISSIONS) {
12848                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12849            }
12850
12851            if (grant != GRANT_DENIED) {
12852                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12853                    // If this is an existing, non-system package, then
12854                    // we can't add any new permissions to it.
12855                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12856                        // Except...  if this is a permission that was added
12857                        // to the platform (note: need to only do this when
12858                        // updating the platform).
12859                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12860                            grant = GRANT_DENIED;
12861                        }
12862                    }
12863                }
12864
12865                switch (grant) {
12866                    case GRANT_INSTALL: {
12867                        // Revoke this as runtime permission to handle the case of
12868                        // a runtime permission being downgraded to an install one.
12869                        // Also in permission review mode we keep dangerous permissions
12870                        // for legacy apps
12871                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12872                            if (origPermissions.getRuntimePermissionState(
12873                                    bp.name, userId) != null) {
12874                                // Revoke the runtime permission and clear the flags.
12875                                origPermissions.revokeRuntimePermission(bp, userId);
12876                                origPermissions.updatePermissionFlags(bp, userId,
12877                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12878                                // If we revoked a permission permission, we have to write.
12879                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12880                                        changedRuntimePermissionUserIds, userId);
12881                            }
12882                        }
12883                        // Grant an install permission.
12884                        if (permissionsState.grantInstallPermission(bp) !=
12885                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12886                            changedInstallPermission = true;
12887                        }
12888                    } break;
12889
12890                    case GRANT_RUNTIME: {
12891                        // Grant previously granted runtime permissions.
12892                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12893                            PermissionState permissionState = origPermissions
12894                                    .getRuntimePermissionState(bp.name, userId);
12895                            int flags = permissionState != null
12896                                    ? permissionState.getFlags() : 0;
12897                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12898                                // Don't propagate the permission in a permission review mode if
12899                                // the former was revoked, i.e. marked to not propagate on upgrade.
12900                                // Note that in a permission review mode install permissions are
12901                                // represented as constantly granted runtime ones since we need to
12902                                // keep a per user state associated with the permission. Also the
12903                                // revoke on upgrade flag is no longer applicable and is reset.
12904                                final boolean revokeOnUpgrade = (flags & PackageManager
12905                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12906                                if (revokeOnUpgrade) {
12907                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12908                                    // Since we changed the flags, we have to write.
12909                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12910                                            changedRuntimePermissionUserIds, userId);
12911                                }
12912                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12913                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12914                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12915                                        // If we cannot put the permission as it was,
12916                                        // we have to write.
12917                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12918                                                changedRuntimePermissionUserIds, userId);
12919                                    }
12920                                }
12921
12922                                // If the app supports runtime permissions no need for a review.
12923                                if (mPermissionReviewRequired
12924                                        && appSupportsRuntimePermissions
12925                                        && (flags & PackageManager
12926                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12927                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12928                                    // Since we changed the flags, we have to write.
12929                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12930                                            changedRuntimePermissionUserIds, userId);
12931                                }
12932                            } else if (mPermissionReviewRequired
12933                                    && !appSupportsRuntimePermissions) {
12934                                // For legacy apps that need a permission review, every new
12935                                // runtime permission is granted but it is pending a review.
12936                                // We also need to review only platform defined runtime
12937                                // permissions as these are the only ones the platform knows
12938                                // how to disable the API to simulate revocation as legacy
12939                                // apps don't expect to run with revoked permissions.
12940                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12941                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12942                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12943                                        // We changed the flags, hence have to write.
12944                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12945                                                changedRuntimePermissionUserIds, userId);
12946                                    }
12947                                }
12948                                if (permissionsState.grantRuntimePermission(bp, userId)
12949                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12950                                    // We changed the permission, hence have to write.
12951                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12952                                            changedRuntimePermissionUserIds, userId);
12953                                }
12954                            }
12955                            // Propagate the permission flags.
12956                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12957                        }
12958                    } break;
12959
12960                    case GRANT_UPGRADE: {
12961                        // Grant runtime permissions for a previously held install permission.
12962                        PermissionState permissionState = origPermissions
12963                                .getInstallPermissionState(bp.name);
12964                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12965
12966                        if (origPermissions.revokeInstallPermission(bp)
12967                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12968                            // We will be transferring the permission flags, so clear them.
12969                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12970                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12971                            changedInstallPermission = true;
12972                        }
12973
12974                        // If the permission is not to be promoted to runtime we ignore it and
12975                        // also its other flags as they are not applicable to install permissions.
12976                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12977                            for (int userId : currentUserIds) {
12978                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12979                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12980                                    // Transfer the permission flags.
12981                                    permissionsState.updatePermissionFlags(bp, userId,
12982                                            flags, flags);
12983                                    // If we granted the permission, we have to write.
12984                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12985                                            changedRuntimePermissionUserIds, userId);
12986                                }
12987                            }
12988                        }
12989                    } break;
12990
12991                    default: {
12992                        if (packageOfInterest == null
12993                                || packageOfInterest.equals(pkg.packageName)) {
12994                            if (DEBUG_PERMISSIONS) {
12995                                Slog.i(TAG, "Not granting permission " + perm
12996                                        + " to package " + pkg.packageName
12997                                        + " because it was previously installed without");
12998                            }
12999                        }
13000                    } break;
13001                }
13002            } else {
13003                if (permissionsState.revokeInstallPermission(bp) !=
13004                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13005                    // Also drop the permission flags.
13006                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13007                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13008                    changedInstallPermission = true;
13009                    Slog.i(TAG, "Un-granting permission " + perm
13010                            + " from package " + pkg.packageName
13011                            + " (protectionLevel=" + bp.protectionLevel
13012                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13013                            + ")");
13014                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13015                    // Don't print warning for app op permissions, since it is fine for them
13016                    // not to be granted, there is a UI for the user to decide.
13017                    if (DEBUG_PERMISSIONS
13018                            && (packageOfInterest == null
13019                                    || packageOfInterest.equals(pkg.packageName))) {
13020                        Slog.i(TAG, "Not granting permission " + perm
13021                                + " to package " + pkg.packageName
13022                                + " (protectionLevel=" + bp.protectionLevel
13023                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13024                                + ")");
13025                    }
13026                }
13027            }
13028        }
13029
13030        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13031                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13032            // This is the first that we have heard about this package, so the
13033            // permissions we have now selected are fixed until explicitly
13034            // changed.
13035            ps.installPermissionsFixed = true;
13036        }
13037
13038        // Persist the runtime permissions state for users with changes. If permissions
13039        // were revoked because no app in the shared user declares them we have to
13040        // write synchronously to avoid losing runtime permissions state.
13041        for (int userId : changedRuntimePermissionUserIds) {
13042            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13043        }
13044    }
13045
13046    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13047        boolean allowed = false;
13048        final int NP = PackageParser.NEW_PERMISSIONS.length;
13049        for (int ip=0; ip<NP; ip++) {
13050            final PackageParser.NewPermissionInfo npi
13051                    = PackageParser.NEW_PERMISSIONS[ip];
13052            if (npi.name.equals(perm)
13053                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13054                allowed = true;
13055                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13056                        + pkg.packageName);
13057                break;
13058            }
13059        }
13060        return allowed;
13061    }
13062
13063    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13064            BasePermission bp, PermissionsState origPermissions) {
13065        boolean privilegedPermission = (bp.protectionLevel
13066                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13067        boolean privappPermissionsDisable =
13068                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13069        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13070        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13071        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13072                && !platformPackage && platformPermission) {
13073            ArraySet<String> wlPermissions = SystemConfig.getInstance()
13074                    .getPrivAppPermissions(pkg.packageName);
13075            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
13076            if (!whitelisted) {
13077                Slog.w(TAG, "Privileged permission " + perm + " for package "
13078                        + pkg.packageName + " - not in privapp-permissions whitelist");
13079                // Only report violations for apps on system image
13080                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13081                    if (mPrivappPermissionsViolations == null) {
13082                        mPrivappPermissionsViolations = new ArraySet<>();
13083                    }
13084                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13085                }
13086                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13087                    return false;
13088                }
13089            }
13090        }
13091        boolean allowed = (compareSignatures(
13092                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13093                        == PackageManager.SIGNATURE_MATCH)
13094                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13095                        == PackageManager.SIGNATURE_MATCH);
13096        if (!allowed && privilegedPermission) {
13097            if (isSystemApp(pkg)) {
13098                // For updated system applications, a system permission
13099                // is granted only if it had been defined by the original application.
13100                if (pkg.isUpdatedSystemApp()) {
13101                    final PackageSetting sysPs = mSettings
13102                            .getDisabledSystemPkgLPr(pkg.packageName);
13103                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13104                        // If the original was granted this permission, we take
13105                        // that grant decision as read and propagate it to the
13106                        // update.
13107                        if (sysPs.isPrivileged()) {
13108                            allowed = true;
13109                        }
13110                    } else {
13111                        // The system apk may have been updated with an older
13112                        // version of the one on the data partition, but which
13113                        // granted a new system permission that it didn't have
13114                        // before.  In this case we do want to allow the app to
13115                        // now get the new permission if the ancestral apk is
13116                        // privileged to get it.
13117                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13118                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13119                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13120                                    allowed = true;
13121                                    break;
13122                                }
13123                            }
13124                        }
13125                        // Also if a privileged parent package on the system image or any of
13126                        // its children requested a privileged permission, the updated child
13127                        // packages can also get the permission.
13128                        if (pkg.parentPackage != null) {
13129                            final PackageSetting disabledSysParentPs = mSettings
13130                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13131                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13132                                    && disabledSysParentPs.isPrivileged()) {
13133                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13134                                    allowed = true;
13135                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13136                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13137                                    for (int i = 0; i < count; i++) {
13138                                        PackageParser.Package disabledSysChildPkg =
13139                                                disabledSysParentPs.pkg.childPackages.get(i);
13140                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13141                                                perm)) {
13142                                            allowed = true;
13143                                            break;
13144                                        }
13145                                    }
13146                                }
13147                            }
13148                        }
13149                    }
13150                } else {
13151                    allowed = isPrivilegedApp(pkg);
13152                }
13153            }
13154        }
13155        if (!allowed) {
13156            if (!allowed && (bp.protectionLevel
13157                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13158                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13159                // If this was a previously normal/dangerous permission that got moved
13160                // to a system permission as part of the runtime permission redesign, then
13161                // we still want to blindly grant it to old apps.
13162                allowed = true;
13163            }
13164            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13165                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13166                // If this permission is to be granted to the system installer and
13167                // this app is an installer, then it gets the permission.
13168                allowed = true;
13169            }
13170            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13171                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13172                // If this permission is to be granted to the system verifier and
13173                // this app is a verifier, then it gets the permission.
13174                allowed = true;
13175            }
13176            if (!allowed && (bp.protectionLevel
13177                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13178                    && isSystemApp(pkg)) {
13179                // Any pre-installed system app is allowed to get this permission.
13180                allowed = true;
13181            }
13182            if (!allowed && (bp.protectionLevel
13183                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13184                // For development permissions, a development permission
13185                // is granted only if it was already granted.
13186                allowed = origPermissions.hasInstallPermission(perm);
13187            }
13188            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13189                    && pkg.packageName.equals(mSetupWizardPackage)) {
13190                // If this permission is to be granted to the system setup wizard and
13191                // this app is a setup wizard, then it gets the permission.
13192                allowed = true;
13193            }
13194        }
13195        return allowed;
13196    }
13197
13198    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13199        final int permCount = pkg.requestedPermissions.size();
13200        for (int j = 0; j < permCount; j++) {
13201            String requestedPermission = pkg.requestedPermissions.get(j);
13202            if (permission.equals(requestedPermission)) {
13203                return true;
13204            }
13205        }
13206        return false;
13207    }
13208
13209    final class ActivityIntentResolver
13210            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13211        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13212                boolean defaultOnly, int userId) {
13213            if (!sUserManager.exists(userId)) return null;
13214            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13215            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13216        }
13217
13218        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13219                int userId) {
13220            if (!sUserManager.exists(userId)) return null;
13221            mFlags = flags;
13222            return super.queryIntent(intent, resolvedType,
13223                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13224                    userId);
13225        }
13226
13227        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13228                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13229            if (!sUserManager.exists(userId)) return null;
13230            if (packageActivities == null) {
13231                return null;
13232            }
13233            mFlags = flags;
13234            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13235            final int N = packageActivities.size();
13236            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13237                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13238
13239            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13240            for (int i = 0; i < N; ++i) {
13241                intentFilters = packageActivities.get(i).intents;
13242                if (intentFilters != null && intentFilters.size() > 0) {
13243                    PackageParser.ActivityIntentInfo[] array =
13244                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13245                    intentFilters.toArray(array);
13246                    listCut.add(array);
13247                }
13248            }
13249            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13250        }
13251
13252        /**
13253         * Finds a privileged activity that matches the specified activity names.
13254         */
13255        private PackageParser.Activity findMatchingActivity(
13256                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13257            for (PackageParser.Activity sysActivity : activityList) {
13258                if (sysActivity.info.name.equals(activityInfo.name)) {
13259                    return sysActivity;
13260                }
13261                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13262                    return sysActivity;
13263                }
13264                if (sysActivity.info.targetActivity != null) {
13265                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13266                        return sysActivity;
13267                    }
13268                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13269                        return sysActivity;
13270                    }
13271                }
13272            }
13273            return null;
13274        }
13275
13276        public class IterGenerator<E> {
13277            public Iterator<E> generate(ActivityIntentInfo info) {
13278                return null;
13279            }
13280        }
13281
13282        public class ActionIterGenerator extends IterGenerator<String> {
13283            @Override
13284            public Iterator<String> generate(ActivityIntentInfo info) {
13285                return info.actionsIterator();
13286            }
13287        }
13288
13289        public class CategoriesIterGenerator extends IterGenerator<String> {
13290            @Override
13291            public Iterator<String> generate(ActivityIntentInfo info) {
13292                return info.categoriesIterator();
13293            }
13294        }
13295
13296        public class SchemesIterGenerator extends IterGenerator<String> {
13297            @Override
13298            public Iterator<String> generate(ActivityIntentInfo info) {
13299                return info.schemesIterator();
13300            }
13301        }
13302
13303        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13304            @Override
13305            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13306                return info.authoritiesIterator();
13307            }
13308        }
13309
13310        /**
13311         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13312         * MODIFIED. Do not pass in a list that should not be changed.
13313         */
13314        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13315                IterGenerator<T> generator, Iterator<T> searchIterator) {
13316            // loop through the set of actions; every one must be found in the intent filter
13317            while (searchIterator.hasNext()) {
13318                // we must have at least one filter in the list to consider a match
13319                if (intentList.size() == 0) {
13320                    break;
13321                }
13322
13323                final T searchAction = searchIterator.next();
13324
13325                // loop through the set of intent filters
13326                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13327                while (intentIter.hasNext()) {
13328                    final ActivityIntentInfo intentInfo = intentIter.next();
13329                    boolean selectionFound = false;
13330
13331                    // loop through the intent filter's selection criteria; at least one
13332                    // of them must match the searched criteria
13333                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13334                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13335                        final T intentSelection = intentSelectionIter.next();
13336                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13337                            selectionFound = true;
13338                            break;
13339                        }
13340                    }
13341
13342                    // the selection criteria wasn't found in this filter's set; this filter
13343                    // is not a potential match
13344                    if (!selectionFound) {
13345                        intentIter.remove();
13346                    }
13347                }
13348            }
13349        }
13350
13351        private boolean isProtectedAction(ActivityIntentInfo filter) {
13352            final Iterator<String> actionsIter = filter.actionsIterator();
13353            while (actionsIter != null && actionsIter.hasNext()) {
13354                final String filterAction = actionsIter.next();
13355                if (PROTECTED_ACTIONS.contains(filterAction)) {
13356                    return true;
13357                }
13358            }
13359            return false;
13360        }
13361
13362        /**
13363         * Adjusts the priority of the given intent filter according to policy.
13364         * <p>
13365         * <ul>
13366         * <li>The priority for non privileged applications is capped to '0'</li>
13367         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13368         * <li>The priority for unbundled updates to privileged applications is capped to the
13369         *      priority defined on the system partition</li>
13370         * </ul>
13371         * <p>
13372         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13373         * allowed to obtain any priority on any action.
13374         */
13375        private void adjustPriority(
13376                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13377            // nothing to do; priority is fine as-is
13378            if (intent.getPriority() <= 0) {
13379                return;
13380            }
13381
13382            final ActivityInfo activityInfo = intent.activity.info;
13383            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13384
13385            final boolean privilegedApp =
13386                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13387            if (!privilegedApp) {
13388                // non-privileged applications can never define a priority >0
13389                if (DEBUG_FILTERS) {
13390                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13391                            + " package: " + applicationInfo.packageName
13392                            + " activity: " + intent.activity.className
13393                            + " origPrio: " + intent.getPriority());
13394                }
13395                intent.setPriority(0);
13396                return;
13397            }
13398
13399            if (systemActivities == null) {
13400                // the system package is not disabled; we're parsing the system partition
13401                if (isProtectedAction(intent)) {
13402                    if (mDeferProtectedFilters) {
13403                        // We can't deal with these just yet. No component should ever obtain a
13404                        // >0 priority for a protected actions, with ONE exception -- the setup
13405                        // wizard. The setup wizard, however, cannot be known until we're able to
13406                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13407                        // until all intent filters have been processed. Chicken, meet egg.
13408                        // Let the filter temporarily have a high priority and rectify the
13409                        // priorities after all system packages have been scanned.
13410                        mProtectedFilters.add(intent);
13411                        if (DEBUG_FILTERS) {
13412                            Slog.i(TAG, "Protected action; save for later;"
13413                                    + " package: " + applicationInfo.packageName
13414                                    + " activity: " + intent.activity.className
13415                                    + " origPrio: " + intent.getPriority());
13416                        }
13417                        return;
13418                    } else {
13419                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13420                            Slog.i(TAG, "No setup wizard;"
13421                                + " All protected intents capped to priority 0");
13422                        }
13423                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13424                            if (DEBUG_FILTERS) {
13425                                Slog.i(TAG, "Found setup wizard;"
13426                                    + " allow priority " + intent.getPriority() + ";"
13427                                    + " package: " + intent.activity.info.packageName
13428                                    + " activity: " + intent.activity.className
13429                                    + " priority: " + intent.getPriority());
13430                            }
13431                            // setup wizard gets whatever it wants
13432                            return;
13433                        }
13434                        if (DEBUG_FILTERS) {
13435                            Slog.i(TAG, "Protected action; cap priority to 0;"
13436                                    + " package: " + intent.activity.info.packageName
13437                                    + " activity: " + intent.activity.className
13438                                    + " origPrio: " + intent.getPriority());
13439                        }
13440                        intent.setPriority(0);
13441                        return;
13442                    }
13443                }
13444                // privileged apps on the system image get whatever priority they request
13445                return;
13446            }
13447
13448            // privileged app unbundled update ... try to find the same activity
13449            final PackageParser.Activity foundActivity =
13450                    findMatchingActivity(systemActivities, activityInfo);
13451            if (foundActivity == null) {
13452                // this is a new activity; it cannot obtain >0 priority
13453                if (DEBUG_FILTERS) {
13454                    Slog.i(TAG, "New activity; cap priority to 0;"
13455                            + " package: " + applicationInfo.packageName
13456                            + " activity: " + intent.activity.className
13457                            + " origPrio: " + intent.getPriority());
13458                }
13459                intent.setPriority(0);
13460                return;
13461            }
13462
13463            // found activity, now check for filter equivalence
13464
13465            // a shallow copy is enough; we modify the list, not its contents
13466            final List<ActivityIntentInfo> intentListCopy =
13467                    new ArrayList<>(foundActivity.intents);
13468            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13469
13470            // find matching action subsets
13471            final Iterator<String> actionsIterator = intent.actionsIterator();
13472            if (actionsIterator != null) {
13473                getIntentListSubset(
13474                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13475                if (intentListCopy.size() == 0) {
13476                    // no more intents to match; we're not equivalent
13477                    if (DEBUG_FILTERS) {
13478                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13479                                + " package: " + applicationInfo.packageName
13480                                + " activity: " + intent.activity.className
13481                                + " origPrio: " + intent.getPriority());
13482                    }
13483                    intent.setPriority(0);
13484                    return;
13485                }
13486            }
13487
13488            // find matching category subsets
13489            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13490            if (categoriesIterator != null) {
13491                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13492                        categoriesIterator);
13493                if (intentListCopy.size() == 0) {
13494                    // no more intents to match; we're not equivalent
13495                    if (DEBUG_FILTERS) {
13496                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13497                                + " package: " + applicationInfo.packageName
13498                                + " activity: " + intent.activity.className
13499                                + " origPrio: " + intent.getPriority());
13500                    }
13501                    intent.setPriority(0);
13502                    return;
13503                }
13504            }
13505
13506            // find matching schemes subsets
13507            final Iterator<String> schemesIterator = intent.schemesIterator();
13508            if (schemesIterator != null) {
13509                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13510                        schemesIterator);
13511                if (intentListCopy.size() == 0) {
13512                    // no more intents to match; we're not equivalent
13513                    if (DEBUG_FILTERS) {
13514                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13515                                + " package: " + applicationInfo.packageName
13516                                + " activity: " + intent.activity.className
13517                                + " origPrio: " + intent.getPriority());
13518                    }
13519                    intent.setPriority(0);
13520                    return;
13521                }
13522            }
13523
13524            // find matching authorities subsets
13525            final Iterator<IntentFilter.AuthorityEntry>
13526                    authoritiesIterator = intent.authoritiesIterator();
13527            if (authoritiesIterator != null) {
13528                getIntentListSubset(intentListCopy,
13529                        new AuthoritiesIterGenerator(),
13530                        authoritiesIterator);
13531                if (intentListCopy.size() == 0) {
13532                    // no more intents to match; we're not equivalent
13533                    if (DEBUG_FILTERS) {
13534                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13535                                + " package: " + applicationInfo.packageName
13536                                + " activity: " + intent.activity.className
13537                                + " origPrio: " + intent.getPriority());
13538                    }
13539                    intent.setPriority(0);
13540                    return;
13541                }
13542            }
13543
13544            // we found matching filter(s); app gets the max priority of all intents
13545            int cappedPriority = 0;
13546            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13547                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13548            }
13549            if (intent.getPriority() > cappedPriority) {
13550                if (DEBUG_FILTERS) {
13551                    Slog.i(TAG, "Found matching filter(s);"
13552                            + " cap priority to " + cappedPriority + ";"
13553                            + " package: " + applicationInfo.packageName
13554                            + " activity: " + intent.activity.className
13555                            + " origPrio: " + intent.getPriority());
13556                }
13557                intent.setPriority(cappedPriority);
13558                return;
13559            }
13560            // all this for nothing; the requested priority was <= what was on the system
13561        }
13562
13563        public final void addActivity(PackageParser.Activity a, String type) {
13564            mActivities.put(a.getComponentName(), a);
13565            if (DEBUG_SHOW_INFO)
13566                Log.v(
13567                TAG, "  " + type + " " +
13568                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13569            if (DEBUG_SHOW_INFO)
13570                Log.v(TAG, "    Class=" + a.info.name);
13571            final int NI = a.intents.size();
13572            for (int j=0; j<NI; j++) {
13573                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13574                if ("activity".equals(type)) {
13575                    final PackageSetting ps =
13576                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13577                    final List<PackageParser.Activity> systemActivities =
13578                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13579                    adjustPriority(systemActivities, intent);
13580                }
13581                if (DEBUG_SHOW_INFO) {
13582                    Log.v(TAG, "    IntentFilter:");
13583                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13584                }
13585                if (!intent.debugCheck()) {
13586                    Log.w(TAG, "==> For Activity " + a.info.name);
13587                }
13588                addFilter(intent);
13589            }
13590        }
13591
13592        public final void removeActivity(PackageParser.Activity a, String type) {
13593            mActivities.remove(a.getComponentName());
13594            if (DEBUG_SHOW_INFO) {
13595                Log.v(TAG, "  " + type + " "
13596                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13597                                : a.info.name) + ":");
13598                Log.v(TAG, "    Class=" + a.info.name);
13599            }
13600            final int NI = a.intents.size();
13601            for (int j=0; j<NI; j++) {
13602                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13603                if (DEBUG_SHOW_INFO) {
13604                    Log.v(TAG, "    IntentFilter:");
13605                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13606                }
13607                removeFilter(intent);
13608            }
13609        }
13610
13611        @Override
13612        protected boolean allowFilterResult(
13613                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13614            ActivityInfo filterAi = filter.activity.info;
13615            for (int i=dest.size()-1; i>=0; i--) {
13616                ActivityInfo destAi = dest.get(i).activityInfo;
13617                if (destAi.name == filterAi.name
13618                        && destAi.packageName == filterAi.packageName) {
13619                    return false;
13620                }
13621            }
13622            return true;
13623        }
13624
13625        @Override
13626        protected ActivityIntentInfo[] newArray(int size) {
13627            return new ActivityIntentInfo[size];
13628        }
13629
13630        @Override
13631        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13632            if (!sUserManager.exists(userId)) return true;
13633            PackageParser.Package p = filter.activity.owner;
13634            if (p != null) {
13635                PackageSetting ps = (PackageSetting)p.mExtras;
13636                if (ps != null) {
13637                    // System apps are never considered stopped for purposes of
13638                    // filtering, because there may be no way for the user to
13639                    // actually re-launch them.
13640                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13641                            && ps.getStopped(userId);
13642                }
13643            }
13644            return false;
13645        }
13646
13647        @Override
13648        protected boolean isPackageForFilter(String packageName,
13649                PackageParser.ActivityIntentInfo info) {
13650            return packageName.equals(info.activity.owner.packageName);
13651        }
13652
13653        @Override
13654        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13655                int match, int userId) {
13656            if (!sUserManager.exists(userId)) return null;
13657            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13658                return null;
13659            }
13660            final PackageParser.Activity activity = info.activity;
13661            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13662            if (ps == null) {
13663                return null;
13664            }
13665            final PackageUserState userState = ps.readUserState(userId);
13666            ActivityInfo ai =
13667                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13668            if (ai == null) {
13669                return null;
13670            }
13671            final boolean matchExplicitlyVisibleOnly =
13672                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13673            final boolean matchVisibleToInstantApp =
13674                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13675            final boolean componentVisible =
13676                    matchVisibleToInstantApp
13677                    && info.isVisibleToInstantApp()
13678                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13679            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13680            // throw out filters that aren't visible to ephemeral apps
13681            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13682                return null;
13683            }
13684            // throw out instant app filters if we're not explicitly requesting them
13685            if (!matchInstantApp && userState.instantApp) {
13686                return null;
13687            }
13688            // throw out instant app filters if updates are available; will trigger
13689            // instant app resolution
13690            if (userState.instantApp && ps.isUpdateAvailable()) {
13691                return null;
13692            }
13693            final ResolveInfo res = new ResolveInfo();
13694            res.activityInfo = ai;
13695            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13696                res.filter = info;
13697            }
13698            if (info != null) {
13699                res.handleAllWebDataURI = info.handleAllWebDataURI();
13700            }
13701            res.priority = info.getPriority();
13702            res.preferredOrder = activity.owner.mPreferredOrder;
13703            //System.out.println("Result: " + res.activityInfo.className +
13704            //                   " = " + res.priority);
13705            res.match = match;
13706            res.isDefault = info.hasDefault;
13707            res.labelRes = info.labelRes;
13708            res.nonLocalizedLabel = info.nonLocalizedLabel;
13709            if (userNeedsBadging(userId)) {
13710                res.noResourceId = true;
13711            } else {
13712                res.icon = info.icon;
13713            }
13714            res.iconResourceId = info.icon;
13715            res.system = res.activityInfo.applicationInfo.isSystemApp();
13716            res.isInstantAppAvailable = userState.instantApp;
13717            return res;
13718        }
13719
13720        @Override
13721        protected void sortResults(List<ResolveInfo> results) {
13722            Collections.sort(results, mResolvePrioritySorter);
13723        }
13724
13725        @Override
13726        protected void dumpFilter(PrintWriter out, String prefix,
13727                PackageParser.ActivityIntentInfo filter) {
13728            out.print(prefix); out.print(
13729                    Integer.toHexString(System.identityHashCode(filter.activity)));
13730                    out.print(' ');
13731                    filter.activity.printComponentShortName(out);
13732                    out.print(" filter ");
13733                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13734        }
13735
13736        @Override
13737        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13738            return filter.activity;
13739        }
13740
13741        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13742            PackageParser.Activity activity = (PackageParser.Activity)label;
13743            out.print(prefix); out.print(
13744                    Integer.toHexString(System.identityHashCode(activity)));
13745                    out.print(' ');
13746                    activity.printComponentShortName(out);
13747            if (count > 1) {
13748                out.print(" ("); out.print(count); out.print(" filters)");
13749            }
13750            out.println();
13751        }
13752
13753        // Keys are String (activity class name), values are Activity.
13754        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13755                = new ArrayMap<ComponentName, PackageParser.Activity>();
13756        private int mFlags;
13757    }
13758
13759    private final class ServiceIntentResolver
13760            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13761        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13762                boolean defaultOnly, int userId) {
13763            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13764            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13765        }
13766
13767        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13768                int userId) {
13769            if (!sUserManager.exists(userId)) return null;
13770            mFlags = flags;
13771            return super.queryIntent(intent, resolvedType,
13772                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13773                    userId);
13774        }
13775
13776        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13777                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13778            if (!sUserManager.exists(userId)) return null;
13779            if (packageServices == null) {
13780                return null;
13781            }
13782            mFlags = flags;
13783            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13784            final int N = packageServices.size();
13785            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13786                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13787
13788            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13789            for (int i = 0; i < N; ++i) {
13790                intentFilters = packageServices.get(i).intents;
13791                if (intentFilters != null && intentFilters.size() > 0) {
13792                    PackageParser.ServiceIntentInfo[] array =
13793                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13794                    intentFilters.toArray(array);
13795                    listCut.add(array);
13796                }
13797            }
13798            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13799        }
13800
13801        public final void addService(PackageParser.Service s) {
13802            mServices.put(s.getComponentName(), s);
13803            if (DEBUG_SHOW_INFO) {
13804                Log.v(TAG, "  "
13805                        + (s.info.nonLocalizedLabel != null
13806                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13807                Log.v(TAG, "    Class=" + s.info.name);
13808            }
13809            final int NI = s.intents.size();
13810            int j;
13811            for (j=0; j<NI; j++) {
13812                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13813                if (DEBUG_SHOW_INFO) {
13814                    Log.v(TAG, "    IntentFilter:");
13815                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13816                }
13817                if (!intent.debugCheck()) {
13818                    Log.w(TAG, "==> For Service " + s.info.name);
13819                }
13820                addFilter(intent);
13821            }
13822        }
13823
13824        public final void removeService(PackageParser.Service s) {
13825            mServices.remove(s.getComponentName());
13826            if (DEBUG_SHOW_INFO) {
13827                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13828                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13829                Log.v(TAG, "    Class=" + s.info.name);
13830            }
13831            final int NI = s.intents.size();
13832            int j;
13833            for (j=0; j<NI; j++) {
13834                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13835                if (DEBUG_SHOW_INFO) {
13836                    Log.v(TAG, "    IntentFilter:");
13837                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13838                }
13839                removeFilter(intent);
13840            }
13841        }
13842
13843        @Override
13844        protected boolean allowFilterResult(
13845                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13846            ServiceInfo filterSi = filter.service.info;
13847            for (int i=dest.size()-1; i>=0; i--) {
13848                ServiceInfo destAi = dest.get(i).serviceInfo;
13849                if (destAi.name == filterSi.name
13850                        && destAi.packageName == filterSi.packageName) {
13851                    return false;
13852                }
13853            }
13854            return true;
13855        }
13856
13857        @Override
13858        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13859            return new PackageParser.ServiceIntentInfo[size];
13860        }
13861
13862        @Override
13863        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13864            if (!sUserManager.exists(userId)) return true;
13865            PackageParser.Package p = filter.service.owner;
13866            if (p != null) {
13867                PackageSetting ps = (PackageSetting)p.mExtras;
13868                if (ps != null) {
13869                    // System apps are never considered stopped for purposes of
13870                    // filtering, because there may be no way for the user to
13871                    // actually re-launch them.
13872                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13873                            && ps.getStopped(userId);
13874                }
13875            }
13876            return false;
13877        }
13878
13879        @Override
13880        protected boolean isPackageForFilter(String packageName,
13881                PackageParser.ServiceIntentInfo info) {
13882            return packageName.equals(info.service.owner.packageName);
13883        }
13884
13885        @Override
13886        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13887                int match, int userId) {
13888            if (!sUserManager.exists(userId)) return null;
13889            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13890            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13891                return null;
13892            }
13893            final PackageParser.Service service = info.service;
13894            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13895            if (ps == null) {
13896                return null;
13897            }
13898            final PackageUserState userState = ps.readUserState(userId);
13899            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13900                    userState, userId);
13901            if (si == null) {
13902                return null;
13903            }
13904            final boolean matchVisibleToInstantApp =
13905                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13906            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13907            // throw out filters that aren't visible to ephemeral apps
13908            if (matchVisibleToInstantApp
13909                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13910                return null;
13911            }
13912            // throw out ephemeral filters if we're not explicitly requesting them
13913            if (!isInstantApp && userState.instantApp) {
13914                return null;
13915            }
13916            // throw out instant app filters if updates are available; will trigger
13917            // instant app resolution
13918            if (userState.instantApp && ps.isUpdateAvailable()) {
13919                return null;
13920            }
13921            final ResolveInfo res = new ResolveInfo();
13922            res.serviceInfo = si;
13923            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13924                res.filter = filter;
13925            }
13926            res.priority = info.getPriority();
13927            res.preferredOrder = service.owner.mPreferredOrder;
13928            res.match = match;
13929            res.isDefault = info.hasDefault;
13930            res.labelRes = info.labelRes;
13931            res.nonLocalizedLabel = info.nonLocalizedLabel;
13932            res.icon = info.icon;
13933            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13934            return res;
13935        }
13936
13937        @Override
13938        protected void sortResults(List<ResolveInfo> results) {
13939            Collections.sort(results, mResolvePrioritySorter);
13940        }
13941
13942        @Override
13943        protected void dumpFilter(PrintWriter out, String prefix,
13944                PackageParser.ServiceIntentInfo filter) {
13945            out.print(prefix); out.print(
13946                    Integer.toHexString(System.identityHashCode(filter.service)));
13947                    out.print(' ');
13948                    filter.service.printComponentShortName(out);
13949                    out.print(" filter ");
13950                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13951        }
13952
13953        @Override
13954        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13955            return filter.service;
13956        }
13957
13958        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13959            PackageParser.Service service = (PackageParser.Service)label;
13960            out.print(prefix); out.print(
13961                    Integer.toHexString(System.identityHashCode(service)));
13962                    out.print(' ');
13963                    service.printComponentShortName(out);
13964            if (count > 1) {
13965                out.print(" ("); out.print(count); out.print(" filters)");
13966            }
13967            out.println();
13968        }
13969
13970//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13971//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13972//            final List<ResolveInfo> retList = Lists.newArrayList();
13973//            while (i.hasNext()) {
13974//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13975//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13976//                    retList.add(resolveInfo);
13977//                }
13978//            }
13979//            return retList;
13980//        }
13981
13982        // Keys are String (activity class name), values are Activity.
13983        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13984                = new ArrayMap<ComponentName, PackageParser.Service>();
13985        private int mFlags;
13986    }
13987
13988    private final class ProviderIntentResolver
13989            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13990        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13991                boolean defaultOnly, int userId) {
13992            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13993            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13994        }
13995
13996        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13997                int userId) {
13998            if (!sUserManager.exists(userId))
13999                return null;
14000            mFlags = flags;
14001            return super.queryIntent(intent, resolvedType,
14002                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14003                    userId);
14004        }
14005
14006        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14007                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14008            if (!sUserManager.exists(userId))
14009                return null;
14010            if (packageProviders == null) {
14011                return null;
14012            }
14013            mFlags = flags;
14014            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14015            final int N = packageProviders.size();
14016            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14017                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14018
14019            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14020            for (int i = 0; i < N; ++i) {
14021                intentFilters = packageProviders.get(i).intents;
14022                if (intentFilters != null && intentFilters.size() > 0) {
14023                    PackageParser.ProviderIntentInfo[] array =
14024                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14025                    intentFilters.toArray(array);
14026                    listCut.add(array);
14027                }
14028            }
14029            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14030        }
14031
14032        public final void addProvider(PackageParser.Provider p) {
14033            if (mProviders.containsKey(p.getComponentName())) {
14034                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14035                return;
14036            }
14037
14038            mProviders.put(p.getComponentName(), p);
14039            if (DEBUG_SHOW_INFO) {
14040                Log.v(TAG, "  "
14041                        + (p.info.nonLocalizedLabel != null
14042                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14043                Log.v(TAG, "    Class=" + p.info.name);
14044            }
14045            final int NI = p.intents.size();
14046            int j;
14047            for (j = 0; j < NI; j++) {
14048                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14049                if (DEBUG_SHOW_INFO) {
14050                    Log.v(TAG, "    IntentFilter:");
14051                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14052                }
14053                if (!intent.debugCheck()) {
14054                    Log.w(TAG, "==> For Provider " + p.info.name);
14055                }
14056                addFilter(intent);
14057            }
14058        }
14059
14060        public final void removeProvider(PackageParser.Provider p) {
14061            mProviders.remove(p.getComponentName());
14062            if (DEBUG_SHOW_INFO) {
14063                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14064                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14065                Log.v(TAG, "    Class=" + p.info.name);
14066            }
14067            final int NI = p.intents.size();
14068            int j;
14069            for (j = 0; j < NI; j++) {
14070                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14071                if (DEBUG_SHOW_INFO) {
14072                    Log.v(TAG, "    IntentFilter:");
14073                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14074                }
14075                removeFilter(intent);
14076            }
14077        }
14078
14079        @Override
14080        protected boolean allowFilterResult(
14081                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14082            ProviderInfo filterPi = filter.provider.info;
14083            for (int i = dest.size() - 1; i >= 0; i--) {
14084                ProviderInfo destPi = dest.get(i).providerInfo;
14085                if (destPi.name == filterPi.name
14086                        && destPi.packageName == filterPi.packageName) {
14087                    return false;
14088                }
14089            }
14090            return true;
14091        }
14092
14093        @Override
14094        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14095            return new PackageParser.ProviderIntentInfo[size];
14096        }
14097
14098        @Override
14099        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14100            if (!sUserManager.exists(userId))
14101                return true;
14102            PackageParser.Package p = filter.provider.owner;
14103            if (p != null) {
14104                PackageSetting ps = (PackageSetting) p.mExtras;
14105                if (ps != null) {
14106                    // System apps are never considered stopped for purposes of
14107                    // filtering, because there may be no way for the user to
14108                    // actually re-launch them.
14109                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14110                            && ps.getStopped(userId);
14111                }
14112            }
14113            return false;
14114        }
14115
14116        @Override
14117        protected boolean isPackageForFilter(String packageName,
14118                PackageParser.ProviderIntentInfo info) {
14119            return packageName.equals(info.provider.owner.packageName);
14120        }
14121
14122        @Override
14123        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14124                int match, int userId) {
14125            if (!sUserManager.exists(userId))
14126                return null;
14127            final PackageParser.ProviderIntentInfo info = filter;
14128            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14129                return null;
14130            }
14131            final PackageParser.Provider provider = info.provider;
14132            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14133            if (ps == null) {
14134                return null;
14135            }
14136            final PackageUserState userState = ps.readUserState(userId);
14137            final boolean matchVisibleToInstantApp =
14138                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14139            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14140            // throw out filters that aren't visible to instant applications
14141            if (matchVisibleToInstantApp
14142                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14143                return null;
14144            }
14145            // throw out instant application filters if we're not explicitly requesting them
14146            if (!isInstantApp && userState.instantApp) {
14147                return null;
14148            }
14149            // throw out instant application filters if updates are available; will trigger
14150            // instant application resolution
14151            if (userState.instantApp && ps.isUpdateAvailable()) {
14152                return null;
14153            }
14154            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14155                    userState, userId);
14156            if (pi == null) {
14157                return null;
14158            }
14159            final ResolveInfo res = new ResolveInfo();
14160            res.providerInfo = pi;
14161            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14162                res.filter = filter;
14163            }
14164            res.priority = info.getPriority();
14165            res.preferredOrder = provider.owner.mPreferredOrder;
14166            res.match = match;
14167            res.isDefault = info.hasDefault;
14168            res.labelRes = info.labelRes;
14169            res.nonLocalizedLabel = info.nonLocalizedLabel;
14170            res.icon = info.icon;
14171            res.system = res.providerInfo.applicationInfo.isSystemApp();
14172            return res;
14173        }
14174
14175        @Override
14176        protected void sortResults(List<ResolveInfo> results) {
14177            Collections.sort(results, mResolvePrioritySorter);
14178        }
14179
14180        @Override
14181        protected void dumpFilter(PrintWriter out, String prefix,
14182                PackageParser.ProviderIntentInfo filter) {
14183            out.print(prefix);
14184            out.print(
14185                    Integer.toHexString(System.identityHashCode(filter.provider)));
14186            out.print(' ');
14187            filter.provider.printComponentShortName(out);
14188            out.print(" filter ");
14189            out.println(Integer.toHexString(System.identityHashCode(filter)));
14190        }
14191
14192        @Override
14193        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14194            return filter.provider;
14195        }
14196
14197        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14198            PackageParser.Provider provider = (PackageParser.Provider)label;
14199            out.print(prefix); out.print(
14200                    Integer.toHexString(System.identityHashCode(provider)));
14201                    out.print(' ');
14202                    provider.printComponentShortName(out);
14203            if (count > 1) {
14204                out.print(" ("); out.print(count); out.print(" filters)");
14205            }
14206            out.println();
14207        }
14208
14209        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14210                = new ArrayMap<ComponentName, PackageParser.Provider>();
14211        private int mFlags;
14212    }
14213
14214    static final class EphemeralIntentResolver
14215            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14216        /**
14217         * The result that has the highest defined order. Ordering applies on a
14218         * per-package basis. Mapping is from package name to Pair of order and
14219         * EphemeralResolveInfo.
14220         * <p>
14221         * NOTE: This is implemented as a field variable for convenience and efficiency.
14222         * By having a field variable, we're able to track filter ordering as soon as
14223         * a non-zero order is defined. Otherwise, multiple loops across the result set
14224         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14225         * this needs to be contained entirely within {@link #filterResults}.
14226         */
14227        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14228
14229        @Override
14230        protected AuxiliaryResolveInfo[] newArray(int size) {
14231            return new AuxiliaryResolveInfo[size];
14232        }
14233
14234        @Override
14235        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14236            return true;
14237        }
14238
14239        @Override
14240        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14241                int userId) {
14242            if (!sUserManager.exists(userId)) {
14243                return null;
14244            }
14245            final String packageName = responseObj.resolveInfo.getPackageName();
14246            final Integer order = responseObj.getOrder();
14247            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14248                    mOrderResult.get(packageName);
14249            // ordering is enabled and this item's order isn't high enough
14250            if (lastOrderResult != null && lastOrderResult.first >= order) {
14251                return null;
14252            }
14253            final InstantAppResolveInfo res = responseObj.resolveInfo;
14254            if (order > 0) {
14255                // non-zero order, enable ordering
14256                mOrderResult.put(packageName, new Pair<>(order, res));
14257            }
14258            return responseObj;
14259        }
14260
14261        @Override
14262        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14263            // only do work if ordering is enabled [most of the time it won't be]
14264            if (mOrderResult.size() == 0) {
14265                return;
14266            }
14267            int resultSize = results.size();
14268            for (int i = 0; i < resultSize; i++) {
14269                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14270                final String packageName = info.getPackageName();
14271                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14272                if (savedInfo == null) {
14273                    // package doesn't having ordering
14274                    continue;
14275                }
14276                if (savedInfo.second == info) {
14277                    // circled back to the highest ordered item; remove from order list
14278                    mOrderResult.remove(savedInfo);
14279                    if (mOrderResult.size() == 0) {
14280                        // no more ordered items
14281                        break;
14282                    }
14283                    continue;
14284                }
14285                // item has a worse order, remove it from the result list
14286                results.remove(i);
14287                resultSize--;
14288                i--;
14289            }
14290        }
14291    }
14292
14293    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14294            new Comparator<ResolveInfo>() {
14295        public int compare(ResolveInfo r1, ResolveInfo r2) {
14296            int v1 = r1.priority;
14297            int v2 = r2.priority;
14298            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14299            if (v1 != v2) {
14300                return (v1 > v2) ? -1 : 1;
14301            }
14302            v1 = r1.preferredOrder;
14303            v2 = r2.preferredOrder;
14304            if (v1 != v2) {
14305                return (v1 > v2) ? -1 : 1;
14306            }
14307            if (r1.isDefault != r2.isDefault) {
14308                return r1.isDefault ? -1 : 1;
14309            }
14310            v1 = r1.match;
14311            v2 = r2.match;
14312            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14313            if (v1 != v2) {
14314                return (v1 > v2) ? -1 : 1;
14315            }
14316            if (r1.system != r2.system) {
14317                return r1.system ? -1 : 1;
14318            }
14319            if (r1.activityInfo != null) {
14320                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14321            }
14322            if (r1.serviceInfo != null) {
14323                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14324            }
14325            if (r1.providerInfo != null) {
14326                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14327            }
14328            return 0;
14329        }
14330    };
14331
14332    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14333            new Comparator<ProviderInfo>() {
14334        public int compare(ProviderInfo p1, ProviderInfo p2) {
14335            final int v1 = p1.initOrder;
14336            final int v2 = p2.initOrder;
14337            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14338        }
14339    };
14340
14341    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14342            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14343            final int[] userIds) {
14344        mHandler.post(new Runnable() {
14345            @Override
14346            public void run() {
14347                try {
14348                    final IActivityManager am = ActivityManager.getService();
14349                    if (am == null) return;
14350                    final int[] resolvedUserIds;
14351                    if (userIds == null) {
14352                        resolvedUserIds = am.getRunningUserIds();
14353                    } else {
14354                        resolvedUserIds = userIds;
14355                    }
14356                    for (int id : resolvedUserIds) {
14357                        final Intent intent = new Intent(action,
14358                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14359                        if (extras != null) {
14360                            intent.putExtras(extras);
14361                        }
14362                        if (targetPkg != null) {
14363                            intent.setPackage(targetPkg);
14364                        }
14365                        // Modify the UID when posting to other users
14366                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14367                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14368                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14369                            intent.putExtra(Intent.EXTRA_UID, uid);
14370                        }
14371                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14372                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14373                        if (DEBUG_BROADCASTS) {
14374                            RuntimeException here = new RuntimeException("here");
14375                            here.fillInStackTrace();
14376                            Slog.d(TAG, "Sending to user " + id + ": "
14377                                    + intent.toShortString(false, true, false, false)
14378                                    + " " + intent.getExtras(), here);
14379                        }
14380                        am.broadcastIntent(null, intent, null, finishedReceiver,
14381                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14382                                null, finishedReceiver != null, false, id);
14383                    }
14384                } catch (RemoteException ex) {
14385                }
14386            }
14387        });
14388    }
14389
14390    /**
14391     * Check if the external storage media is available. This is true if there
14392     * is a mounted external storage medium or if the external storage is
14393     * emulated.
14394     */
14395    private boolean isExternalMediaAvailable() {
14396        return mMediaMounted || Environment.isExternalStorageEmulated();
14397    }
14398
14399    @Override
14400    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14401        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14402            return null;
14403        }
14404        // writer
14405        synchronized (mPackages) {
14406            if (!isExternalMediaAvailable()) {
14407                // If the external storage is no longer mounted at this point,
14408                // the caller may not have been able to delete all of this
14409                // packages files and can not delete any more.  Bail.
14410                return null;
14411            }
14412            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14413            if (lastPackage != null) {
14414                pkgs.remove(lastPackage);
14415            }
14416            if (pkgs.size() > 0) {
14417                return pkgs.get(0);
14418            }
14419        }
14420        return null;
14421    }
14422
14423    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14424        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14425                userId, andCode ? 1 : 0, packageName);
14426        if (mSystemReady) {
14427            msg.sendToTarget();
14428        } else {
14429            if (mPostSystemReadyMessages == null) {
14430                mPostSystemReadyMessages = new ArrayList<>();
14431            }
14432            mPostSystemReadyMessages.add(msg);
14433        }
14434    }
14435
14436    void startCleaningPackages() {
14437        // reader
14438        if (!isExternalMediaAvailable()) {
14439            return;
14440        }
14441        synchronized (mPackages) {
14442            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14443                return;
14444            }
14445        }
14446        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14447        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14448        IActivityManager am = ActivityManager.getService();
14449        if (am != null) {
14450            int dcsUid = -1;
14451            synchronized (mPackages) {
14452                if (!mDefaultContainerWhitelisted) {
14453                    mDefaultContainerWhitelisted = true;
14454                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14455                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14456                }
14457            }
14458            try {
14459                if (dcsUid > 0) {
14460                    am.backgroundWhitelistUid(dcsUid);
14461                }
14462                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14463                        UserHandle.USER_SYSTEM);
14464            } catch (RemoteException e) {
14465            }
14466        }
14467    }
14468
14469    @Override
14470    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14471            int installFlags, String installerPackageName, int userId) {
14472        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14473
14474        final int callingUid = Binder.getCallingUid();
14475        enforceCrossUserPermission(callingUid, userId,
14476                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14477
14478        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14479            try {
14480                if (observer != null) {
14481                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14482                }
14483            } catch (RemoteException re) {
14484            }
14485            return;
14486        }
14487
14488        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14489            installFlags |= PackageManager.INSTALL_FROM_ADB;
14490
14491        } else {
14492            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14493            // about installerPackageName.
14494
14495            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14496            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14497        }
14498
14499        UserHandle user;
14500        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14501            user = UserHandle.ALL;
14502        } else {
14503            user = new UserHandle(userId);
14504        }
14505
14506        // Only system components can circumvent runtime permissions when installing.
14507        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14508                && mContext.checkCallingOrSelfPermission(Manifest.permission
14509                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14510            throw new SecurityException("You need the "
14511                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14512                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14513        }
14514
14515        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14516                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14517            throw new IllegalArgumentException(
14518                    "New installs into ASEC containers no longer supported");
14519        }
14520
14521        final File originFile = new File(originPath);
14522        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14523
14524        final Message msg = mHandler.obtainMessage(INIT_COPY);
14525        final VerificationInfo verificationInfo = new VerificationInfo(
14526                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14527        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14528                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14529                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14530                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14531        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14532        msg.obj = params;
14533
14534        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14535                System.identityHashCode(msg.obj));
14536        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14537                System.identityHashCode(msg.obj));
14538
14539        mHandler.sendMessage(msg);
14540    }
14541
14542
14543    /**
14544     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14545     * it is acting on behalf on an enterprise or the user).
14546     *
14547     * Note that the ordering of the conditionals in this method is important. The checks we perform
14548     * are as follows, in this order:
14549     *
14550     * 1) If the install is being performed by a system app, we can trust the app to have set the
14551     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14552     *    what it is.
14553     * 2) If the install is being performed by a device or profile owner app, the install reason
14554     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14555     *    set the install reason correctly. If the app targets an older SDK version where install
14556     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14557     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14558     * 3) In all other cases, the install is being performed by a regular app that is neither part
14559     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14560     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14561     *    set to enterprise policy and if so, change it to unknown instead.
14562     */
14563    private int fixUpInstallReason(String installerPackageName, int installerUid,
14564            int installReason) {
14565        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14566                == PERMISSION_GRANTED) {
14567            // If the install is being performed by a system app, we trust that app to have set the
14568            // install reason correctly.
14569            return installReason;
14570        }
14571
14572        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14573            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14574        if (dpm != null) {
14575            ComponentName owner = null;
14576            try {
14577                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14578                if (owner == null) {
14579                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14580                }
14581            } catch (RemoteException e) {
14582            }
14583            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14584                // If the install is being performed by a device or profile owner, the install
14585                // reason should be enterprise policy.
14586                return PackageManager.INSTALL_REASON_POLICY;
14587            }
14588        }
14589
14590        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14591            // If the install is being performed by a regular app (i.e. neither system app nor
14592            // device or profile owner), we have no reason to believe that the app is acting on
14593            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14594            // change it to unknown instead.
14595            return PackageManager.INSTALL_REASON_UNKNOWN;
14596        }
14597
14598        // If the install is being performed by a regular app and the install reason was set to any
14599        // value but enterprise policy, leave the install reason unchanged.
14600        return installReason;
14601    }
14602
14603    void installStage(String packageName, File stagedDir, String stagedCid,
14604            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14605            String installerPackageName, int installerUid, UserHandle user,
14606            Certificate[][] certificates) {
14607        if (DEBUG_EPHEMERAL) {
14608            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14609                Slog.d(TAG, "Ephemeral install of " + packageName);
14610            }
14611        }
14612        final VerificationInfo verificationInfo = new VerificationInfo(
14613                sessionParams.originatingUri, sessionParams.referrerUri,
14614                sessionParams.originatingUid, installerUid);
14615
14616        final OriginInfo origin;
14617        if (stagedDir != null) {
14618            origin = OriginInfo.fromStagedFile(stagedDir);
14619        } else {
14620            origin = OriginInfo.fromStagedContainer(stagedCid);
14621        }
14622
14623        final Message msg = mHandler.obtainMessage(INIT_COPY);
14624        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14625                sessionParams.installReason);
14626        final InstallParams params = new InstallParams(origin, null, observer,
14627                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14628                verificationInfo, user, sessionParams.abiOverride,
14629                sessionParams.grantedRuntimePermissions, certificates, installReason);
14630        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14631        msg.obj = params;
14632
14633        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14634                System.identityHashCode(msg.obj));
14635        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14636                System.identityHashCode(msg.obj));
14637
14638        mHandler.sendMessage(msg);
14639    }
14640
14641    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14642            int userId) {
14643        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14644        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14645                false /*startReceiver*/, pkgSetting.appId, userId);
14646
14647        // Send a session commit broadcast
14648        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14649        info.installReason = pkgSetting.getInstallReason(userId);
14650        info.appPackageName = packageName;
14651        sendSessionCommitBroadcast(info, userId);
14652    }
14653
14654    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14655            boolean includeStopped, int appId, int... userIds) {
14656        if (ArrayUtils.isEmpty(userIds)) {
14657            return;
14658        }
14659        Bundle extras = new Bundle(1);
14660        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14661        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14662
14663        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14664                packageName, extras, 0, null, null, userIds);
14665        if (sendBootCompleted) {
14666            mHandler.post(() -> {
14667                        for (int userId : userIds) {
14668                            sendBootCompletedBroadcastToSystemApp(
14669                                    packageName, includeStopped, userId);
14670                        }
14671                    }
14672            );
14673        }
14674    }
14675
14676    /**
14677     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14678     * automatically without needing an explicit launch.
14679     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14680     */
14681    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14682            int userId) {
14683        // If user is not running, the app didn't miss any broadcast
14684        if (!mUserManagerInternal.isUserRunning(userId)) {
14685            return;
14686        }
14687        final IActivityManager am = ActivityManager.getService();
14688        try {
14689            // Deliver LOCKED_BOOT_COMPLETED first
14690            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14691                    .setPackage(packageName);
14692            if (includeStopped) {
14693                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14694            }
14695            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14696            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14697                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14698
14699            // Deliver BOOT_COMPLETED only if user is unlocked
14700            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14701                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14702                if (includeStopped) {
14703                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14704                }
14705                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14706                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14707            }
14708        } catch (RemoteException e) {
14709            throw e.rethrowFromSystemServer();
14710        }
14711    }
14712
14713    @Override
14714    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14715            int userId) {
14716        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14717        PackageSetting pkgSetting;
14718        final int callingUid = Binder.getCallingUid();
14719        enforceCrossUserPermission(callingUid, userId,
14720                true /* requireFullPermission */, true /* checkShell */,
14721                "setApplicationHiddenSetting for user " + userId);
14722
14723        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14724            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14725            return false;
14726        }
14727
14728        long callingId = Binder.clearCallingIdentity();
14729        try {
14730            boolean sendAdded = false;
14731            boolean sendRemoved = false;
14732            // writer
14733            synchronized (mPackages) {
14734                pkgSetting = mSettings.mPackages.get(packageName);
14735                if (pkgSetting == null) {
14736                    return false;
14737                }
14738                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14739                    return false;
14740                }
14741                // Do not allow "android" is being disabled
14742                if ("android".equals(packageName)) {
14743                    Slog.w(TAG, "Cannot hide package: android");
14744                    return false;
14745                }
14746                // Cannot hide static shared libs as they are considered
14747                // a part of the using app (emulating static linking). Also
14748                // static libs are installed always on internal storage.
14749                PackageParser.Package pkg = mPackages.get(packageName);
14750                if (pkg != null && pkg.staticSharedLibName != null) {
14751                    Slog.w(TAG, "Cannot hide package: " + packageName
14752                            + " providing static shared library: "
14753                            + pkg.staticSharedLibName);
14754                    return false;
14755                }
14756                // Only allow protected packages to hide themselves.
14757                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14758                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14759                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14760                    return false;
14761                }
14762
14763                if (pkgSetting.getHidden(userId) != hidden) {
14764                    pkgSetting.setHidden(hidden, userId);
14765                    mSettings.writePackageRestrictionsLPr(userId);
14766                    if (hidden) {
14767                        sendRemoved = true;
14768                    } else {
14769                        sendAdded = true;
14770                    }
14771                }
14772            }
14773            if (sendAdded) {
14774                sendPackageAddedForUser(packageName, pkgSetting, userId);
14775                return true;
14776            }
14777            if (sendRemoved) {
14778                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14779                        "hiding pkg");
14780                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14781                return true;
14782            }
14783        } finally {
14784            Binder.restoreCallingIdentity(callingId);
14785        }
14786        return false;
14787    }
14788
14789    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14790            int userId) {
14791        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14792        info.removedPackage = packageName;
14793        info.installerPackageName = pkgSetting.installerPackageName;
14794        info.removedUsers = new int[] {userId};
14795        info.broadcastUsers = new int[] {userId};
14796        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14797        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14798    }
14799
14800    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14801        if (pkgList.length > 0) {
14802            Bundle extras = new Bundle(1);
14803            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14804
14805            sendPackageBroadcast(
14806                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14807                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14808                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14809                    new int[] {userId});
14810        }
14811    }
14812
14813    /**
14814     * Returns true if application is not found or there was an error. Otherwise it returns
14815     * the hidden state of the package for the given user.
14816     */
14817    @Override
14818    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14819        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14820        final int callingUid = Binder.getCallingUid();
14821        enforceCrossUserPermission(callingUid, userId,
14822                true /* requireFullPermission */, false /* checkShell */,
14823                "getApplicationHidden for user " + userId);
14824        PackageSetting ps;
14825        long callingId = Binder.clearCallingIdentity();
14826        try {
14827            // writer
14828            synchronized (mPackages) {
14829                ps = mSettings.mPackages.get(packageName);
14830                if (ps == null) {
14831                    return true;
14832                }
14833                if (filterAppAccessLPr(ps, callingUid, userId)) {
14834                    return true;
14835                }
14836                return ps.getHidden(userId);
14837            }
14838        } finally {
14839            Binder.restoreCallingIdentity(callingId);
14840        }
14841    }
14842
14843    /**
14844     * @hide
14845     */
14846    @Override
14847    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14848            int installReason) {
14849        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14850                null);
14851        PackageSetting pkgSetting;
14852        final int callingUid = Binder.getCallingUid();
14853        enforceCrossUserPermission(callingUid, userId,
14854                true /* requireFullPermission */, true /* checkShell */,
14855                "installExistingPackage for user " + userId);
14856        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14857            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14858        }
14859
14860        long callingId = Binder.clearCallingIdentity();
14861        try {
14862            boolean installed = false;
14863            final boolean instantApp =
14864                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14865            final boolean fullApp =
14866                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14867
14868            // writer
14869            synchronized (mPackages) {
14870                pkgSetting = mSettings.mPackages.get(packageName);
14871                if (pkgSetting == null) {
14872                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14873                }
14874                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14875                    // only allow the existing package to be used if it's installed as a full
14876                    // application for at least one user
14877                    boolean installAllowed = false;
14878                    for (int checkUserId : sUserManager.getUserIds()) {
14879                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14880                        if (installAllowed) {
14881                            break;
14882                        }
14883                    }
14884                    if (!installAllowed) {
14885                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14886                    }
14887                }
14888                if (!pkgSetting.getInstalled(userId)) {
14889                    pkgSetting.setInstalled(true, userId);
14890                    pkgSetting.setHidden(false, userId);
14891                    pkgSetting.setInstallReason(installReason, userId);
14892                    mSettings.writePackageRestrictionsLPr(userId);
14893                    mSettings.writeKernelMappingLPr(pkgSetting);
14894                    installed = true;
14895                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14896                    // upgrade app from instant to full; we don't allow app downgrade
14897                    installed = true;
14898                }
14899                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14900            }
14901
14902            if (installed) {
14903                if (pkgSetting.pkg != null) {
14904                    synchronized (mInstallLock) {
14905                        // We don't need to freeze for a brand new install
14906                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14907                    }
14908                }
14909                sendPackageAddedForUser(packageName, pkgSetting, userId);
14910                synchronized (mPackages) {
14911                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14912                }
14913            }
14914        } finally {
14915            Binder.restoreCallingIdentity(callingId);
14916        }
14917
14918        return PackageManager.INSTALL_SUCCEEDED;
14919    }
14920
14921    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14922            boolean instantApp, boolean fullApp) {
14923        // no state specified; do nothing
14924        if (!instantApp && !fullApp) {
14925            return;
14926        }
14927        if (userId != UserHandle.USER_ALL) {
14928            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14929                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14930            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14931                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14932            }
14933        } else {
14934            for (int currentUserId : sUserManager.getUserIds()) {
14935                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14936                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14937                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14938                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14939                }
14940            }
14941        }
14942    }
14943
14944    boolean isUserRestricted(int userId, String restrictionKey) {
14945        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14946        if (restrictions.getBoolean(restrictionKey, false)) {
14947            Log.w(TAG, "User is restricted: " + restrictionKey);
14948            return true;
14949        }
14950        return false;
14951    }
14952
14953    @Override
14954    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14955            int userId) {
14956        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14957        final int callingUid = Binder.getCallingUid();
14958        enforceCrossUserPermission(callingUid, userId,
14959                true /* requireFullPermission */, true /* checkShell */,
14960                "setPackagesSuspended for user " + userId);
14961
14962        if (ArrayUtils.isEmpty(packageNames)) {
14963            return packageNames;
14964        }
14965
14966        // List of package names for whom the suspended state has changed.
14967        List<String> changedPackages = new ArrayList<>(packageNames.length);
14968        // List of package names for whom the suspended state is not set as requested in this
14969        // method.
14970        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14971        long callingId = Binder.clearCallingIdentity();
14972        try {
14973            for (int i = 0; i < packageNames.length; i++) {
14974                String packageName = packageNames[i];
14975                boolean changed = false;
14976                final int appId;
14977                synchronized (mPackages) {
14978                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14979                    if (pkgSetting == null
14980                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14981                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14982                                + "\". Skipping suspending/un-suspending.");
14983                        unactionedPackages.add(packageName);
14984                        continue;
14985                    }
14986                    appId = pkgSetting.appId;
14987                    if (pkgSetting.getSuspended(userId) != suspended) {
14988                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14989                            unactionedPackages.add(packageName);
14990                            continue;
14991                        }
14992                        pkgSetting.setSuspended(suspended, userId);
14993                        mSettings.writePackageRestrictionsLPr(userId);
14994                        changed = true;
14995                        changedPackages.add(packageName);
14996                    }
14997                }
14998
14999                if (changed && suspended) {
15000                    killApplication(packageName, UserHandle.getUid(userId, appId),
15001                            "suspending package");
15002                }
15003            }
15004        } finally {
15005            Binder.restoreCallingIdentity(callingId);
15006        }
15007
15008        if (!changedPackages.isEmpty()) {
15009            sendPackagesSuspendedForUser(changedPackages.toArray(
15010                    new String[changedPackages.size()]), userId, suspended);
15011        }
15012
15013        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15014    }
15015
15016    @Override
15017    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15018        final int callingUid = Binder.getCallingUid();
15019        enforceCrossUserPermission(callingUid, userId,
15020                true /* requireFullPermission */, false /* checkShell */,
15021                "isPackageSuspendedForUser for user " + userId);
15022        synchronized (mPackages) {
15023            final PackageSetting ps = mSettings.mPackages.get(packageName);
15024            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15025                throw new IllegalArgumentException("Unknown target package: " + packageName);
15026            }
15027            return ps.getSuspended(userId);
15028        }
15029    }
15030
15031    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15032        if (isPackageDeviceAdmin(packageName, userId)) {
15033            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15034                    + "\": has an active device admin");
15035            return false;
15036        }
15037
15038        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15039        if (packageName.equals(activeLauncherPackageName)) {
15040            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15041                    + "\": contains the active launcher");
15042            return false;
15043        }
15044
15045        if (packageName.equals(mRequiredInstallerPackage)) {
15046            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15047                    + "\": required for package installation");
15048            return false;
15049        }
15050
15051        if (packageName.equals(mRequiredUninstallerPackage)) {
15052            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15053                    + "\": required for package uninstallation");
15054            return false;
15055        }
15056
15057        if (packageName.equals(mRequiredVerifierPackage)) {
15058            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15059                    + "\": required for package verification");
15060            return false;
15061        }
15062
15063        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15064            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15065                    + "\": is the default dialer");
15066            return false;
15067        }
15068
15069        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15070            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15071                    + "\": protected package");
15072            return false;
15073        }
15074
15075        // Cannot suspend static shared libs as they are considered
15076        // a part of the using app (emulating static linking). Also
15077        // static libs are installed always on internal storage.
15078        PackageParser.Package pkg = mPackages.get(packageName);
15079        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15080            Slog.w(TAG, "Cannot suspend package: " + packageName
15081                    + " providing static shared library: "
15082                    + pkg.staticSharedLibName);
15083            return false;
15084        }
15085
15086        return true;
15087    }
15088
15089    private String getActiveLauncherPackageName(int userId) {
15090        Intent intent = new Intent(Intent.ACTION_MAIN);
15091        intent.addCategory(Intent.CATEGORY_HOME);
15092        ResolveInfo resolveInfo = resolveIntent(
15093                intent,
15094                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15095                PackageManager.MATCH_DEFAULT_ONLY,
15096                userId);
15097
15098        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15099    }
15100
15101    private String getDefaultDialerPackageName(int userId) {
15102        synchronized (mPackages) {
15103            return mSettings.getDefaultDialerPackageNameLPw(userId);
15104        }
15105    }
15106
15107    @Override
15108    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15109        mContext.enforceCallingOrSelfPermission(
15110                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15111                "Only package verification agents can verify applications");
15112
15113        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15114        final PackageVerificationResponse response = new PackageVerificationResponse(
15115                verificationCode, Binder.getCallingUid());
15116        msg.arg1 = id;
15117        msg.obj = response;
15118        mHandler.sendMessage(msg);
15119    }
15120
15121    @Override
15122    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15123            long millisecondsToDelay) {
15124        mContext.enforceCallingOrSelfPermission(
15125                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15126                "Only package verification agents can extend verification timeouts");
15127
15128        final PackageVerificationState state = mPendingVerification.get(id);
15129        final PackageVerificationResponse response = new PackageVerificationResponse(
15130                verificationCodeAtTimeout, Binder.getCallingUid());
15131
15132        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15133            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15134        }
15135        if (millisecondsToDelay < 0) {
15136            millisecondsToDelay = 0;
15137        }
15138        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15139                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15140            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15141        }
15142
15143        if ((state != null) && !state.timeoutExtended()) {
15144            state.extendTimeout();
15145
15146            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15147            msg.arg1 = id;
15148            msg.obj = response;
15149            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15150        }
15151    }
15152
15153    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15154            int verificationCode, UserHandle user) {
15155        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15156        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15157        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15158        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15159        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15160
15161        mContext.sendBroadcastAsUser(intent, user,
15162                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15163    }
15164
15165    private ComponentName matchComponentForVerifier(String packageName,
15166            List<ResolveInfo> receivers) {
15167        ActivityInfo targetReceiver = null;
15168
15169        final int NR = receivers.size();
15170        for (int i = 0; i < NR; i++) {
15171            final ResolveInfo info = receivers.get(i);
15172            if (info.activityInfo == null) {
15173                continue;
15174            }
15175
15176            if (packageName.equals(info.activityInfo.packageName)) {
15177                targetReceiver = info.activityInfo;
15178                break;
15179            }
15180        }
15181
15182        if (targetReceiver == null) {
15183            return null;
15184        }
15185
15186        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15187    }
15188
15189    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15190            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15191        if (pkgInfo.verifiers.length == 0) {
15192            return null;
15193        }
15194
15195        final int N = pkgInfo.verifiers.length;
15196        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15197        for (int i = 0; i < N; i++) {
15198            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15199
15200            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15201                    receivers);
15202            if (comp == null) {
15203                continue;
15204            }
15205
15206            final int verifierUid = getUidForVerifier(verifierInfo);
15207            if (verifierUid == -1) {
15208                continue;
15209            }
15210
15211            if (DEBUG_VERIFY) {
15212                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15213                        + " with the correct signature");
15214            }
15215            sufficientVerifiers.add(comp);
15216            verificationState.addSufficientVerifier(verifierUid);
15217        }
15218
15219        return sufficientVerifiers;
15220    }
15221
15222    private int getUidForVerifier(VerifierInfo verifierInfo) {
15223        synchronized (mPackages) {
15224            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15225            if (pkg == null) {
15226                return -1;
15227            } else if (pkg.mSignatures.length != 1) {
15228                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15229                        + " has more than one signature; ignoring");
15230                return -1;
15231            }
15232
15233            /*
15234             * If the public key of the package's signature does not match
15235             * our expected public key, then this is a different package and
15236             * we should skip.
15237             */
15238
15239            final byte[] expectedPublicKey;
15240            try {
15241                final Signature verifierSig = pkg.mSignatures[0];
15242                final PublicKey publicKey = verifierSig.getPublicKey();
15243                expectedPublicKey = publicKey.getEncoded();
15244            } catch (CertificateException e) {
15245                return -1;
15246            }
15247
15248            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15249
15250            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15251                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15252                        + " does not have the expected public key; ignoring");
15253                return -1;
15254            }
15255
15256            return pkg.applicationInfo.uid;
15257        }
15258    }
15259
15260    @Override
15261    public void finishPackageInstall(int token, boolean didLaunch) {
15262        enforceSystemOrRoot("Only the system is allowed to finish installs");
15263
15264        if (DEBUG_INSTALL) {
15265            Slog.v(TAG, "BM finishing package install for " + token);
15266        }
15267        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15268
15269        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15270        mHandler.sendMessage(msg);
15271    }
15272
15273    /**
15274     * Get the verification agent timeout.  Used for both the APK verifier and the
15275     * intent filter verifier.
15276     *
15277     * @return verification timeout in milliseconds
15278     */
15279    private long getVerificationTimeout() {
15280        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15281                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15282                DEFAULT_VERIFICATION_TIMEOUT);
15283    }
15284
15285    /**
15286     * Get the default verification agent response code.
15287     *
15288     * @return default verification response code
15289     */
15290    private int getDefaultVerificationResponse(UserHandle user) {
15291        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15292            return PackageManager.VERIFICATION_REJECT;
15293        }
15294        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15295                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15296                DEFAULT_VERIFICATION_RESPONSE);
15297    }
15298
15299    /**
15300     * Check whether or not package verification has been enabled.
15301     *
15302     * @return true if verification should be performed
15303     */
15304    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15305        if (!DEFAULT_VERIFY_ENABLE) {
15306            return false;
15307        }
15308
15309        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15310
15311        // Check if installing from ADB
15312        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15313            // Do not run verification in a test harness environment
15314            if (ActivityManager.isRunningInTestHarness()) {
15315                return false;
15316            }
15317            if (ensureVerifyAppsEnabled) {
15318                return true;
15319            }
15320            // Check if the developer does not want package verification for ADB installs
15321            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15322                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15323                return false;
15324            }
15325        } else {
15326            // only when not installed from ADB, skip verification for instant apps when
15327            // the installer and verifier are the same.
15328            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15329                if (mInstantAppInstallerActivity != null
15330                        && mInstantAppInstallerActivity.packageName.equals(
15331                                mRequiredVerifierPackage)) {
15332                    try {
15333                        mContext.getSystemService(AppOpsManager.class)
15334                                .checkPackage(installerUid, mRequiredVerifierPackage);
15335                        if (DEBUG_VERIFY) {
15336                            Slog.i(TAG, "disable verification for instant app");
15337                        }
15338                        return false;
15339                    } catch (SecurityException ignore) { }
15340                }
15341            }
15342        }
15343
15344        if (ensureVerifyAppsEnabled) {
15345            return true;
15346        }
15347
15348        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15349                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15350    }
15351
15352    @Override
15353    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15354            throws RemoteException {
15355        mContext.enforceCallingOrSelfPermission(
15356                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15357                "Only intentfilter verification agents can verify applications");
15358
15359        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15360        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15361                Binder.getCallingUid(), verificationCode, failedDomains);
15362        msg.arg1 = id;
15363        msg.obj = response;
15364        mHandler.sendMessage(msg);
15365    }
15366
15367    @Override
15368    public int getIntentVerificationStatus(String packageName, int userId) {
15369        final int callingUid = Binder.getCallingUid();
15370        if (UserHandle.getUserId(callingUid) != userId) {
15371            mContext.enforceCallingOrSelfPermission(
15372                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15373                    "getIntentVerificationStatus" + userId);
15374        }
15375        if (getInstantAppPackageName(callingUid) != null) {
15376            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15377        }
15378        synchronized (mPackages) {
15379            final PackageSetting ps = mSettings.mPackages.get(packageName);
15380            if (ps == null
15381                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15382                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15383            }
15384            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15385        }
15386    }
15387
15388    @Override
15389    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15390        mContext.enforceCallingOrSelfPermission(
15391                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15392
15393        boolean result = false;
15394        synchronized (mPackages) {
15395            final PackageSetting ps = mSettings.mPackages.get(packageName);
15396            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15397                return false;
15398            }
15399            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15400        }
15401        if (result) {
15402            scheduleWritePackageRestrictionsLocked(userId);
15403        }
15404        return result;
15405    }
15406
15407    @Override
15408    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15409            String packageName) {
15410        final int callingUid = Binder.getCallingUid();
15411        if (getInstantAppPackageName(callingUid) != null) {
15412            return ParceledListSlice.emptyList();
15413        }
15414        synchronized (mPackages) {
15415            final PackageSetting ps = mSettings.mPackages.get(packageName);
15416            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15417                return ParceledListSlice.emptyList();
15418            }
15419            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15420        }
15421    }
15422
15423    @Override
15424    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15425        if (TextUtils.isEmpty(packageName)) {
15426            return ParceledListSlice.emptyList();
15427        }
15428        final int callingUid = Binder.getCallingUid();
15429        final int callingUserId = UserHandle.getUserId(callingUid);
15430        synchronized (mPackages) {
15431            PackageParser.Package pkg = mPackages.get(packageName);
15432            if (pkg == null || pkg.activities == null) {
15433                return ParceledListSlice.emptyList();
15434            }
15435            if (pkg.mExtras == null) {
15436                return ParceledListSlice.emptyList();
15437            }
15438            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15439            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15440                return ParceledListSlice.emptyList();
15441            }
15442            final int count = pkg.activities.size();
15443            ArrayList<IntentFilter> result = new ArrayList<>();
15444            for (int n=0; n<count; n++) {
15445                PackageParser.Activity activity = pkg.activities.get(n);
15446                if (activity.intents != null && activity.intents.size() > 0) {
15447                    result.addAll(activity.intents);
15448                }
15449            }
15450            return new ParceledListSlice<>(result);
15451        }
15452    }
15453
15454    @Override
15455    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15456        mContext.enforceCallingOrSelfPermission(
15457                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15458        if (UserHandle.getCallingUserId() != userId) {
15459            mContext.enforceCallingOrSelfPermission(
15460                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15461        }
15462
15463        synchronized (mPackages) {
15464            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15465            if (packageName != null) {
15466                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15467                        packageName, userId);
15468            }
15469            return result;
15470        }
15471    }
15472
15473    @Override
15474    public String getDefaultBrowserPackageName(int userId) {
15475        if (UserHandle.getCallingUserId() != userId) {
15476            mContext.enforceCallingOrSelfPermission(
15477                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15478        }
15479        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15480            return null;
15481        }
15482        synchronized (mPackages) {
15483            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15484        }
15485    }
15486
15487    /**
15488     * Get the "allow unknown sources" setting.
15489     *
15490     * @return the current "allow unknown sources" setting
15491     */
15492    private int getUnknownSourcesSettings() {
15493        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15494                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15495                -1);
15496    }
15497
15498    @Override
15499    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15500        final int callingUid = Binder.getCallingUid();
15501        if (getInstantAppPackageName(callingUid) != null) {
15502            return;
15503        }
15504        // writer
15505        synchronized (mPackages) {
15506            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15507            if (targetPackageSetting == null
15508                    || filterAppAccessLPr(
15509                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15510                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15511            }
15512
15513            PackageSetting installerPackageSetting;
15514            if (installerPackageName != null) {
15515                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15516                if (installerPackageSetting == null) {
15517                    throw new IllegalArgumentException("Unknown installer package: "
15518                            + installerPackageName);
15519                }
15520            } else {
15521                installerPackageSetting = null;
15522            }
15523
15524            Signature[] callerSignature;
15525            Object obj = mSettings.getUserIdLPr(callingUid);
15526            if (obj != null) {
15527                if (obj instanceof SharedUserSetting) {
15528                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15529                } else if (obj instanceof PackageSetting) {
15530                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15531                } else {
15532                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15533                }
15534            } else {
15535                throw new SecurityException("Unknown calling UID: " + callingUid);
15536            }
15537
15538            // Verify: can't set installerPackageName to a package that is
15539            // not signed with the same cert as the caller.
15540            if (installerPackageSetting != null) {
15541                if (compareSignatures(callerSignature,
15542                        installerPackageSetting.signatures.mSignatures)
15543                        != PackageManager.SIGNATURE_MATCH) {
15544                    throw new SecurityException(
15545                            "Caller does not have same cert as new installer package "
15546                            + installerPackageName);
15547                }
15548            }
15549
15550            // Verify: if target already has an installer package, it must
15551            // be signed with the same cert as the caller.
15552            if (targetPackageSetting.installerPackageName != null) {
15553                PackageSetting setting = mSettings.mPackages.get(
15554                        targetPackageSetting.installerPackageName);
15555                // If the currently set package isn't valid, then it's always
15556                // okay to change it.
15557                if (setting != null) {
15558                    if (compareSignatures(callerSignature,
15559                            setting.signatures.mSignatures)
15560                            != PackageManager.SIGNATURE_MATCH) {
15561                        throw new SecurityException(
15562                                "Caller does not have same cert as old installer package "
15563                                + targetPackageSetting.installerPackageName);
15564                    }
15565                }
15566            }
15567
15568            // Okay!
15569            targetPackageSetting.installerPackageName = installerPackageName;
15570            if (installerPackageName != null) {
15571                mSettings.mInstallerPackages.add(installerPackageName);
15572            }
15573            scheduleWriteSettingsLocked();
15574        }
15575    }
15576
15577    @Override
15578    public void setApplicationCategoryHint(String packageName, int categoryHint,
15579            String callerPackageName) {
15580        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15581            throw new SecurityException("Instant applications don't have access to this method");
15582        }
15583        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15584                callerPackageName);
15585        synchronized (mPackages) {
15586            PackageSetting ps = mSettings.mPackages.get(packageName);
15587            if (ps == null) {
15588                throw new IllegalArgumentException("Unknown target package " + packageName);
15589            }
15590            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15591                throw new IllegalArgumentException("Unknown target package " + packageName);
15592            }
15593            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15594                throw new IllegalArgumentException("Calling package " + callerPackageName
15595                        + " is not installer for " + packageName);
15596            }
15597
15598            if (ps.categoryHint != categoryHint) {
15599                ps.categoryHint = categoryHint;
15600                scheduleWriteSettingsLocked();
15601            }
15602        }
15603    }
15604
15605    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15606        // Queue up an async operation since the package installation may take a little while.
15607        mHandler.post(new Runnable() {
15608            public void run() {
15609                mHandler.removeCallbacks(this);
15610                 // Result object to be returned
15611                PackageInstalledInfo res = new PackageInstalledInfo();
15612                res.setReturnCode(currentStatus);
15613                res.uid = -1;
15614                res.pkg = null;
15615                res.removedInfo = null;
15616                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15617                    args.doPreInstall(res.returnCode);
15618                    synchronized (mInstallLock) {
15619                        installPackageTracedLI(args, res);
15620                    }
15621                    args.doPostInstall(res.returnCode, res.uid);
15622                }
15623
15624                // A restore should be performed at this point if (a) the install
15625                // succeeded, (b) the operation is not an update, and (c) the new
15626                // package has not opted out of backup participation.
15627                final boolean update = res.removedInfo != null
15628                        && res.removedInfo.removedPackage != null;
15629                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15630                boolean doRestore = !update
15631                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15632
15633                // Set up the post-install work request bookkeeping.  This will be used
15634                // and cleaned up by the post-install event handling regardless of whether
15635                // there's a restore pass performed.  Token values are >= 1.
15636                int token;
15637                if (mNextInstallToken < 0) mNextInstallToken = 1;
15638                token = mNextInstallToken++;
15639
15640                PostInstallData data = new PostInstallData(args, res);
15641                mRunningInstalls.put(token, data);
15642                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15643
15644                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15645                    // Pass responsibility to the Backup Manager.  It will perform a
15646                    // restore if appropriate, then pass responsibility back to the
15647                    // Package Manager to run the post-install observer callbacks
15648                    // and broadcasts.
15649                    IBackupManager bm = IBackupManager.Stub.asInterface(
15650                            ServiceManager.getService(Context.BACKUP_SERVICE));
15651                    if (bm != null) {
15652                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15653                                + " to BM for possible restore");
15654                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15655                        try {
15656                            // TODO: http://b/22388012
15657                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15658                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15659                            } else {
15660                                doRestore = false;
15661                            }
15662                        } catch (RemoteException e) {
15663                            // can't happen; the backup manager is local
15664                        } catch (Exception e) {
15665                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15666                            doRestore = false;
15667                        }
15668                    } else {
15669                        Slog.e(TAG, "Backup Manager not found!");
15670                        doRestore = false;
15671                    }
15672                }
15673
15674                if (!doRestore) {
15675                    // No restore possible, or the Backup Manager was mysteriously not
15676                    // available -- just fire the post-install work request directly.
15677                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15678
15679                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15680
15681                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15682                    mHandler.sendMessage(msg);
15683                }
15684            }
15685        });
15686    }
15687
15688    /**
15689     * Callback from PackageSettings whenever an app is first transitioned out of the
15690     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15691     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15692     * here whether the app is the target of an ongoing install, and only send the
15693     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15694     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15695     * handling.
15696     */
15697    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15698        // Serialize this with the rest of the install-process message chain.  In the
15699        // restore-at-install case, this Runnable will necessarily run before the
15700        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15701        // are coherent.  In the non-restore case, the app has already completed install
15702        // and been launched through some other means, so it is not in a problematic
15703        // state for observers to see the FIRST_LAUNCH signal.
15704        mHandler.post(new Runnable() {
15705            @Override
15706            public void run() {
15707                for (int i = 0; i < mRunningInstalls.size(); i++) {
15708                    final PostInstallData data = mRunningInstalls.valueAt(i);
15709                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15710                        continue;
15711                    }
15712                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15713                        // right package; but is it for the right user?
15714                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15715                            if (userId == data.res.newUsers[uIndex]) {
15716                                if (DEBUG_BACKUP) {
15717                                    Slog.i(TAG, "Package " + pkgName
15718                                            + " being restored so deferring FIRST_LAUNCH");
15719                                }
15720                                return;
15721                            }
15722                        }
15723                    }
15724                }
15725                // didn't find it, so not being restored
15726                if (DEBUG_BACKUP) {
15727                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15728                }
15729                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15730            }
15731        });
15732    }
15733
15734    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15735        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15736                installerPkg, null, userIds);
15737    }
15738
15739    private abstract class HandlerParams {
15740        private static final int MAX_RETRIES = 4;
15741
15742        /**
15743         * Number of times startCopy() has been attempted and had a non-fatal
15744         * error.
15745         */
15746        private int mRetries = 0;
15747
15748        /** User handle for the user requesting the information or installation. */
15749        private final UserHandle mUser;
15750        String traceMethod;
15751        int traceCookie;
15752
15753        HandlerParams(UserHandle user) {
15754            mUser = user;
15755        }
15756
15757        UserHandle getUser() {
15758            return mUser;
15759        }
15760
15761        HandlerParams setTraceMethod(String traceMethod) {
15762            this.traceMethod = traceMethod;
15763            return this;
15764        }
15765
15766        HandlerParams setTraceCookie(int traceCookie) {
15767            this.traceCookie = traceCookie;
15768            return this;
15769        }
15770
15771        final boolean startCopy() {
15772            boolean res;
15773            try {
15774                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15775
15776                if (++mRetries > MAX_RETRIES) {
15777                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15778                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15779                    handleServiceError();
15780                    return false;
15781                } else {
15782                    handleStartCopy();
15783                    res = true;
15784                }
15785            } catch (RemoteException e) {
15786                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15787                mHandler.sendEmptyMessage(MCS_RECONNECT);
15788                res = false;
15789            }
15790            handleReturnCode();
15791            return res;
15792        }
15793
15794        final void serviceError() {
15795            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15796            handleServiceError();
15797            handleReturnCode();
15798        }
15799
15800        abstract void handleStartCopy() throws RemoteException;
15801        abstract void handleServiceError();
15802        abstract void handleReturnCode();
15803    }
15804
15805    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15806        for (File path : paths) {
15807            try {
15808                mcs.clearDirectory(path.getAbsolutePath());
15809            } catch (RemoteException e) {
15810            }
15811        }
15812    }
15813
15814    static class OriginInfo {
15815        /**
15816         * Location where install is coming from, before it has been
15817         * copied/renamed into place. This could be a single monolithic APK
15818         * file, or a cluster directory. This location may be untrusted.
15819         */
15820        final File file;
15821        final String cid;
15822
15823        /**
15824         * Flag indicating that {@link #file} or {@link #cid} has already been
15825         * staged, meaning downstream users don't need to defensively copy the
15826         * contents.
15827         */
15828        final boolean staged;
15829
15830        /**
15831         * Flag indicating that {@link #file} or {@link #cid} is an already
15832         * installed app that is being moved.
15833         */
15834        final boolean existing;
15835
15836        final String resolvedPath;
15837        final File resolvedFile;
15838
15839        static OriginInfo fromNothing() {
15840            return new OriginInfo(null, null, false, false);
15841        }
15842
15843        static OriginInfo fromUntrustedFile(File file) {
15844            return new OriginInfo(file, null, false, false);
15845        }
15846
15847        static OriginInfo fromExistingFile(File file) {
15848            return new OriginInfo(file, null, false, true);
15849        }
15850
15851        static OriginInfo fromStagedFile(File file) {
15852            return new OriginInfo(file, null, true, false);
15853        }
15854
15855        static OriginInfo fromStagedContainer(String cid) {
15856            return new OriginInfo(null, cid, true, false);
15857        }
15858
15859        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15860            this.file = file;
15861            this.cid = cid;
15862            this.staged = staged;
15863            this.existing = existing;
15864
15865            if (cid != null) {
15866                resolvedPath = PackageHelper.getSdDir(cid);
15867                resolvedFile = new File(resolvedPath);
15868            } else if (file != null) {
15869                resolvedPath = file.getAbsolutePath();
15870                resolvedFile = file;
15871            } else {
15872                resolvedPath = null;
15873                resolvedFile = null;
15874            }
15875        }
15876    }
15877
15878    static class MoveInfo {
15879        final int moveId;
15880        final String fromUuid;
15881        final String toUuid;
15882        final String packageName;
15883        final String dataAppName;
15884        final int appId;
15885        final String seinfo;
15886        final int targetSdkVersion;
15887
15888        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15889                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15890            this.moveId = moveId;
15891            this.fromUuid = fromUuid;
15892            this.toUuid = toUuid;
15893            this.packageName = packageName;
15894            this.dataAppName = dataAppName;
15895            this.appId = appId;
15896            this.seinfo = seinfo;
15897            this.targetSdkVersion = targetSdkVersion;
15898        }
15899    }
15900
15901    static class VerificationInfo {
15902        /** A constant used to indicate that a uid value is not present. */
15903        public static final int NO_UID = -1;
15904
15905        /** URI referencing where the package was downloaded from. */
15906        final Uri originatingUri;
15907
15908        /** HTTP referrer URI associated with the originatingURI. */
15909        final Uri referrer;
15910
15911        /** UID of the application that the install request originated from. */
15912        final int originatingUid;
15913
15914        /** UID of application requesting the install */
15915        final int installerUid;
15916
15917        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15918            this.originatingUri = originatingUri;
15919            this.referrer = referrer;
15920            this.originatingUid = originatingUid;
15921            this.installerUid = installerUid;
15922        }
15923    }
15924
15925    class InstallParams extends HandlerParams {
15926        final OriginInfo origin;
15927        final MoveInfo move;
15928        final IPackageInstallObserver2 observer;
15929        int installFlags;
15930        final String installerPackageName;
15931        final String volumeUuid;
15932        private InstallArgs mArgs;
15933        private int mRet;
15934        final String packageAbiOverride;
15935        final String[] grantedRuntimePermissions;
15936        final VerificationInfo verificationInfo;
15937        final Certificate[][] certificates;
15938        final int installReason;
15939
15940        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15941                int installFlags, String installerPackageName, String volumeUuid,
15942                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15943                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15944            super(user);
15945            this.origin = origin;
15946            this.move = move;
15947            this.observer = observer;
15948            this.installFlags = installFlags;
15949            this.installerPackageName = installerPackageName;
15950            this.volumeUuid = volumeUuid;
15951            this.verificationInfo = verificationInfo;
15952            this.packageAbiOverride = packageAbiOverride;
15953            this.grantedRuntimePermissions = grantedPermissions;
15954            this.certificates = certificates;
15955            this.installReason = installReason;
15956        }
15957
15958        @Override
15959        public String toString() {
15960            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15961                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15962        }
15963
15964        private int installLocationPolicy(PackageInfoLite pkgLite) {
15965            String packageName = pkgLite.packageName;
15966            int installLocation = pkgLite.installLocation;
15967            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15968            // reader
15969            synchronized (mPackages) {
15970                // Currently installed package which the new package is attempting to replace or
15971                // null if no such package is installed.
15972                PackageParser.Package installedPkg = mPackages.get(packageName);
15973                // Package which currently owns the data which the new package will own if installed.
15974                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15975                // will be null whereas dataOwnerPkg will contain information about the package
15976                // which was uninstalled while keeping its data.
15977                PackageParser.Package dataOwnerPkg = installedPkg;
15978                if (dataOwnerPkg  == null) {
15979                    PackageSetting ps = mSettings.mPackages.get(packageName);
15980                    if (ps != null) {
15981                        dataOwnerPkg = ps.pkg;
15982                    }
15983                }
15984
15985                if (dataOwnerPkg != null) {
15986                    // If installed, the package will get access to data left on the device by its
15987                    // predecessor. As a security measure, this is permited only if this is not a
15988                    // version downgrade or if the predecessor package is marked as debuggable and
15989                    // a downgrade is explicitly requested.
15990                    //
15991                    // On debuggable platform builds, downgrades are permitted even for
15992                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15993                    // not offer security guarantees and thus it's OK to disable some security
15994                    // mechanisms to make debugging/testing easier on those builds. However, even on
15995                    // debuggable builds downgrades of packages are permitted only if requested via
15996                    // installFlags. This is because we aim to keep the behavior of debuggable
15997                    // platform builds as close as possible to the behavior of non-debuggable
15998                    // platform builds.
15999                    final boolean downgradeRequested =
16000                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16001                    final boolean packageDebuggable =
16002                                (dataOwnerPkg.applicationInfo.flags
16003                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16004                    final boolean downgradePermitted =
16005                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16006                    if (!downgradePermitted) {
16007                        try {
16008                            checkDowngrade(dataOwnerPkg, pkgLite);
16009                        } catch (PackageManagerException e) {
16010                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16011                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16012                        }
16013                    }
16014                }
16015
16016                if (installedPkg != null) {
16017                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16018                        // Check for updated system application.
16019                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16020                            if (onSd) {
16021                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16022                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16023                            }
16024                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16025                        } else {
16026                            if (onSd) {
16027                                // Install flag overrides everything.
16028                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16029                            }
16030                            // If current upgrade specifies particular preference
16031                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16032                                // Application explicitly specified internal.
16033                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16034                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16035                                // App explictly prefers external. Let policy decide
16036                            } else {
16037                                // Prefer previous location
16038                                if (isExternal(installedPkg)) {
16039                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16040                                }
16041                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16042                            }
16043                        }
16044                    } else {
16045                        // Invalid install. Return error code
16046                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16047                    }
16048                }
16049            }
16050            // All the special cases have been taken care of.
16051            // Return result based on recommended install location.
16052            if (onSd) {
16053                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16054            }
16055            return pkgLite.recommendedInstallLocation;
16056        }
16057
16058        /*
16059         * Invoke remote method to get package information and install
16060         * location values. Override install location based on default
16061         * policy if needed and then create install arguments based
16062         * on the install location.
16063         */
16064        public void handleStartCopy() throws RemoteException {
16065            int ret = PackageManager.INSTALL_SUCCEEDED;
16066
16067            // If we're already staged, we've firmly committed to an install location
16068            if (origin.staged) {
16069                if (origin.file != null) {
16070                    installFlags |= PackageManager.INSTALL_INTERNAL;
16071                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16072                } else if (origin.cid != null) {
16073                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16074                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16075                } else {
16076                    throw new IllegalStateException("Invalid stage location");
16077                }
16078            }
16079
16080            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16081            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16082            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16083            PackageInfoLite pkgLite = null;
16084
16085            if (onInt && onSd) {
16086                // Check if both bits are set.
16087                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16088                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16089            } else if (onSd && ephemeral) {
16090                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16091                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16092            } else {
16093                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16094                        packageAbiOverride);
16095
16096                if (DEBUG_EPHEMERAL && ephemeral) {
16097                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16098                }
16099
16100                /*
16101                 * If we have too little free space, try to free cache
16102                 * before giving up.
16103                 */
16104                if (!origin.staged && pkgLite.recommendedInstallLocation
16105                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16106                    // TODO: focus freeing disk space on the target device
16107                    final StorageManager storage = StorageManager.from(mContext);
16108                    final long lowThreshold = storage.getStorageLowBytes(
16109                            Environment.getDataDirectory());
16110
16111                    final long sizeBytes = mContainerService.calculateInstalledSize(
16112                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16113
16114                    try {
16115                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16116                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16117                                installFlags, packageAbiOverride);
16118                    } catch (InstallerException e) {
16119                        Slog.w(TAG, "Failed to free cache", e);
16120                    }
16121
16122                    /*
16123                     * The cache free must have deleted the file we
16124                     * downloaded to install.
16125                     *
16126                     * TODO: fix the "freeCache" call to not delete
16127                     *       the file we care about.
16128                     */
16129                    if (pkgLite.recommendedInstallLocation
16130                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16131                        pkgLite.recommendedInstallLocation
16132                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16133                    }
16134                }
16135            }
16136
16137            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16138                int loc = pkgLite.recommendedInstallLocation;
16139                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16140                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16141                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16142                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16143                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16144                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16145                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16146                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16147                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16148                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16149                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16150                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16151                } else {
16152                    // Override with defaults if needed.
16153                    loc = installLocationPolicy(pkgLite);
16154                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16155                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16156                    } else if (!onSd && !onInt) {
16157                        // Override install location with flags
16158                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16159                            // Set the flag to install on external media.
16160                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16161                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16162                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16163                            if (DEBUG_EPHEMERAL) {
16164                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16165                            }
16166                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16167                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16168                                    |PackageManager.INSTALL_INTERNAL);
16169                        } else {
16170                            // Make sure the flag for installing on external
16171                            // media is unset
16172                            installFlags |= PackageManager.INSTALL_INTERNAL;
16173                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16174                        }
16175                    }
16176                }
16177            }
16178
16179            final InstallArgs args = createInstallArgs(this);
16180            mArgs = args;
16181
16182            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16183                // TODO: http://b/22976637
16184                // Apps installed for "all" users use the device owner to verify the app
16185                UserHandle verifierUser = getUser();
16186                if (verifierUser == UserHandle.ALL) {
16187                    verifierUser = UserHandle.SYSTEM;
16188                }
16189
16190                /*
16191                 * Determine if we have any installed package verifiers. If we
16192                 * do, then we'll defer to them to verify the packages.
16193                 */
16194                final int requiredUid = mRequiredVerifierPackage == null ? -1
16195                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16196                                verifierUser.getIdentifier());
16197                final int installerUid =
16198                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16199                if (!origin.existing && requiredUid != -1
16200                        && isVerificationEnabled(
16201                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16202                    final Intent verification = new Intent(
16203                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16204                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16205                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16206                            PACKAGE_MIME_TYPE);
16207                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16208
16209                    // Query all live verifiers based on current user state
16210                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16211                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
16212
16213                    if (DEBUG_VERIFY) {
16214                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16215                                + verification.toString() + " with " + pkgLite.verifiers.length
16216                                + " optional verifiers");
16217                    }
16218
16219                    final int verificationId = mPendingVerificationToken++;
16220
16221                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16222
16223                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16224                            installerPackageName);
16225
16226                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16227                            installFlags);
16228
16229                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16230                            pkgLite.packageName);
16231
16232                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16233                            pkgLite.versionCode);
16234
16235                    if (verificationInfo != null) {
16236                        if (verificationInfo.originatingUri != null) {
16237                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16238                                    verificationInfo.originatingUri);
16239                        }
16240                        if (verificationInfo.referrer != null) {
16241                            verification.putExtra(Intent.EXTRA_REFERRER,
16242                                    verificationInfo.referrer);
16243                        }
16244                        if (verificationInfo.originatingUid >= 0) {
16245                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16246                                    verificationInfo.originatingUid);
16247                        }
16248                        if (verificationInfo.installerUid >= 0) {
16249                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16250                                    verificationInfo.installerUid);
16251                        }
16252                    }
16253
16254                    final PackageVerificationState verificationState = new PackageVerificationState(
16255                            requiredUid, args);
16256
16257                    mPendingVerification.append(verificationId, verificationState);
16258
16259                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16260                            receivers, verificationState);
16261
16262                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16263                    final long idleDuration = getVerificationTimeout();
16264
16265                    /*
16266                     * If any sufficient verifiers were listed in the package
16267                     * manifest, attempt to ask them.
16268                     */
16269                    if (sufficientVerifiers != null) {
16270                        final int N = sufficientVerifiers.size();
16271                        if (N == 0) {
16272                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16273                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16274                        } else {
16275                            for (int i = 0; i < N; i++) {
16276                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16277                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16278                                        verifierComponent.getPackageName(), idleDuration,
16279                                        verifierUser.getIdentifier(), false, "package verifier");
16280
16281                                final Intent sufficientIntent = new Intent(verification);
16282                                sufficientIntent.setComponent(verifierComponent);
16283                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16284                            }
16285                        }
16286                    }
16287
16288                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16289                            mRequiredVerifierPackage, receivers);
16290                    if (ret == PackageManager.INSTALL_SUCCEEDED
16291                            && mRequiredVerifierPackage != null) {
16292                        Trace.asyncTraceBegin(
16293                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16294                        /*
16295                         * Send the intent to the required verification agent,
16296                         * but only start the verification timeout after the
16297                         * target BroadcastReceivers have run.
16298                         */
16299                        verification.setComponent(requiredVerifierComponent);
16300                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16301                                mRequiredVerifierPackage, idleDuration,
16302                                verifierUser.getIdentifier(), false, "package verifier");
16303                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16304                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16305                                new BroadcastReceiver() {
16306                                    @Override
16307                                    public void onReceive(Context context, Intent intent) {
16308                                        final Message msg = mHandler
16309                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16310                                        msg.arg1 = verificationId;
16311                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16312                                    }
16313                                }, null, 0, null, null);
16314
16315                        /*
16316                         * We don't want the copy to proceed until verification
16317                         * succeeds, so null out this field.
16318                         */
16319                        mArgs = null;
16320                    }
16321                } else {
16322                    /*
16323                     * No package verification is enabled, so immediately start
16324                     * the remote call to initiate copy using temporary file.
16325                     */
16326                    ret = args.copyApk(mContainerService, true);
16327                }
16328            }
16329
16330            mRet = ret;
16331        }
16332
16333        @Override
16334        void handleReturnCode() {
16335            // If mArgs is null, then MCS couldn't be reached. When it
16336            // reconnects, it will try again to install. At that point, this
16337            // will succeed.
16338            if (mArgs != null) {
16339                processPendingInstall(mArgs, mRet);
16340            }
16341        }
16342
16343        @Override
16344        void handleServiceError() {
16345            mArgs = createInstallArgs(this);
16346            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16347        }
16348
16349        public boolean isForwardLocked() {
16350            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16351        }
16352    }
16353
16354    /**
16355     * Used during creation of InstallArgs
16356     *
16357     * @param installFlags package installation flags
16358     * @return true if should be installed on external storage
16359     */
16360    private static boolean installOnExternalAsec(int installFlags) {
16361        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16362            return false;
16363        }
16364        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16365            return true;
16366        }
16367        return false;
16368    }
16369
16370    /**
16371     * Used during creation of InstallArgs
16372     *
16373     * @param installFlags package installation flags
16374     * @return true if should be installed as forward locked
16375     */
16376    private static boolean installForwardLocked(int installFlags) {
16377        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16378    }
16379
16380    private InstallArgs createInstallArgs(InstallParams params) {
16381        if (params.move != null) {
16382            return new MoveInstallArgs(params);
16383        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16384            return new AsecInstallArgs(params);
16385        } else {
16386            return new FileInstallArgs(params);
16387        }
16388    }
16389
16390    /**
16391     * Create args that describe an existing installed package. Typically used
16392     * when cleaning up old installs, or used as a move source.
16393     */
16394    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16395            String resourcePath, String[] instructionSets) {
16396        final boolean isInAsec;
16397        if (installOnExternalAsec(installFlags)) {
16398            /* Apps on SD card are always in ASEC containers. */
16399            isInAsec = true;
16400        } else if (installForwardLocked(installFlags)
16401                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16402            /*
16403             * Forward-locked apps are only in ASEC containers if they're the
16404             * new style
16405             */
16406            isInAsec = true;
16407        } else {
16408            isInAsec = false;
16409        }
16410
16411        if (isInAsec) {
16412            return new AsecInstallArgs(codePath, instructionSets,
16413                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16414        } else {
16415            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16416        }
16417    }
16418
16419    static abstract class InstallArgs {
16420        /** @see InstallParams#origin */
16421        final OriginInfo origin;
16422        /** @see InstallParams#move */
16423        final MoveInfo move;
16424
16425        final IPackageInstallObserver2 observer;
16426        // Always refers to PackageManager flags only
16427        final int installFlags;
16428        final String installerPackageName;
16429        final String volumeUuid;
16430        final UserHandle user;
16431        final String abiOverride;
16432        final String[] installGrantPermissions;
16433        /** If non-null, drop an async trace when the install completes */
16434        final String traceMethod;
16435        final int traceCookie;
16436        final Certificate[][] certificates;
16437        final int installReason;
16438
16439        // The list of instruction sets supported by this app. This is currently
16440        // only used during the rmdex() phase to clean up resources. We can get rid of this
16441        // if we move dex files under the common app path.
16442        /* nullable */ String[] instructionSets;
16443
16444        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16445                int installFlags, String installerPackageName, String volumeUuid,
16446                UserHandle user, String[] instructionSets,
16447                String abiOverride, String[] installGrantPermissions,
16448                String traceMethod, int traceCookie, Certificate[][] certificates,
16449                int installReason) {
16450            this.origin = origin;
16451            this.move = move;
16452            this.installFlags = installFlags;
16453            this.observer = observer;
16454            this.installerPackageName = installerPackageName;
16455            this.volumeUuid = volumeUuid;
16456            this.user = user;
16457            this.instructionSets = instructionSets;
16458            this.abiOverride = abiOverride;
16459            this.installGrantPermissions = installGrantPermissions;
16460            this.traceMethod = traceMethod;
16461            this.traceCookie = traceCookie;
16462            this.certificates = certificates;
16463            this.installReason = installReason;
16464        }
16465
16466        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16467        abstract int doPreInstall(int status);
16468
16469        /**
16470         * Rename package into final resting place. All paths on the given
16471         * scanned package should be updated to reflect the rename.
16472         */
16473        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16474        abstract int doPostInstall(int status, int uid);
16475
16476        /** @see PackageSettingBase#codePathString */
16477        abstract String getCodePath();
16478        /** @see PackageSettingBase#resourcePathString */
16479        abstract String getResourcePath();
16480
16481        // Need installer lock especially for dex file removal.
16482        abstract void cleanUpResourcesLI();
16483        abstract boolean doPostDeleteLI(boolean delete);
16484
16485        /**
16486         * Called before the source arguments are copied. This is used mostly
16487         * for MoveParams when it needs to read the source file to put it in the
16488         * destination.
16489         */
16490        int doPreCopy() {
16491            return PackageManager.INSTALL_SUCCEEDED;
16492        }
16493
16494        /**
16495         * Called after the source arguments are copied. This is used mostly for
16496         * MoveParams when it needs to read the source file to put it in the
16497         * destination.
16498         */
16499        int doPostCopy(int uid) {
16500            return PackageManager.INSTALL_SUCCEEDED;
16501        }
16502
16503        protected boolean isFwdLocked() {
16504            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16505        }
16506
16507        protected boolean isExternalAsec() {
16508            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16509        }
16510
16511        protected boolean isEphemeral() {
16512            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16513        }
16514
16515        UserHandle getUser() {
16516            return user;
16517        }
16518    }
16519
16520    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16521        if (!allCodePaths.isEmpty()) {
16522            if (instructionSets == null) {
16523                throw new IllegalStateException("instructionSet == null");
16524            }
16525            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16526            for (String codePath : allCodePaths) {
16527                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16528                    try {
16529                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16530                    } catch (InstallerException ignored) {
16531                    }
16532                }
16533            }
16534        }
16535    }
16536
16537    /**
16538     * Logic to handle installation of non-ASEC applications, including copying
16539     * and renaming logic.
16540     */
16541    class FileInstallArgs extends InstallArgs {
16542        private File codeFile;
16543        private File resourceFile;
16544
16545        // Example topology:
16546        // /data/app/com.example/base.apk
16547        // /data/app/com.example/split_foo.apk
16548        // /data/app/com.example/lib/arm/libfoo.so
16549        // /data/app/com.example/lib/arm64/libfoo.so
16550        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16551
16552        /** New install */
16553        FileInstallArgs(InstallParams params) {
16554            super(params.origin, params.move, params.observer, params.installFlags,
16555                    params.installerPackageName, params.volumeUuid,
16556                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16557                    params.grantedRuntimePermissions,
16558                    params.traceMethod, params.traceCookie, params.certificates,
16559                    params.installReason);
16560            if (isFwdLocked()) {
16561                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16562            }
16563        }
16564
16565        /** Existing install */
16566        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16567            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16568                    null, null, null, 0, null /*certificates*/,
16569                    PackageManager.INSTALL_REASON_UNKNOWN);
16570            this.codeFile = (codePath != null) ? new File(codePath) : null;
16571            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16572        }
16573
16574        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16575            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16576            try {
16577                return doCopyApk(imcs, temp);
16578            } finally {
16579                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16580            }
16581        }
16582
16583        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16584            if (origin.staged) {
16585                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16586                codeFile = origin.file;
16587                resourceFile = origin.file;
16588                return PackageManager.INSTALL_SUCCEEDED;
16589            }
16590
16591            try {
16592                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16593                final File tempDir =
16594                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16595                codeFile = tempDir;
16596                resourceFile = tempDir;
16597            } catch (IOException e) {
16598                Slog.w(TAG, "Failed to create copy file: " + e);
16599                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16600            }
16601
16602            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16603                @Override
16604                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16605                    if (!FileUtils.isValidExtFilename(name)) {
16606                        throw new IllegalArgumentException("Invalid filename: " + name);
16607                    }
16608                    try {
16609                        final File file = new File(codeFile, name);
16610                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16611                                O_RDWR | O_CREAT, 0644);
16612                        Os.chmod(file.getAbsolutePath(), 0644);
16613                        return new ParcelFileDescriptor(fd);
16614                    } catch (ErrnoException e) {
16615                        throw new RemoteException("Failed to open: " + e.getMessage());
16616                    }
16617                }
16618            };
16619
16620            int ret = PackageManager.INSTALL_SUCCEEDED;
16621            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16622            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16623                Slog.e(TAG, "Failed to copy package");
16624                return ret;
16625            }
16626
16627            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16628            NativeLibraryHelper.Handle handle = null;
16629            try {
16630                handle = NativeLibraryHelper.Handle.create(codeFile);
16631                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16632                        abiOverride);
16633            } catch (IOException e) {
16634                Slog.e(TAG, "Copying native libraries failed", e);
16635                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16636            } finally {
16637                IoUtils.closeQuietly(handle);
16638            }
16639
16640            return ret;
16641        }
16642
16643        int doPreInstall(int status) {
16644            if (status != PackageManager.INSTALL_SUCCEEDED) {
16645                cleanUp();
16646            }
16647            return status;
16648        }
16649
16650        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16651            if (status != PackageManager.INSTALL_SUCCEEDED) {
16652                cleanUp();
16653                return false;
16654            }
16655
16656            final File targetDir = codeFile.getParentFile();
16657            final File beforeCodeFile = codeFile;
16658            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16659
16660            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16661            try {
16662                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16663            } catch (ErrnoException e) {
16664                Slog.w(TAG, "Failed to rename", e);
16665                return false;
16666            }
16667
16668            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16669                Slog.w(TAG, "Failed to restorecon");
16670                return false;
16671            }
16672
16673            // Reflect the rename internally
16674            codeFile = afterCodeFile;
16675            resourceFile = afterCodeFile;
16676
16677            // Reflect the rename in scanned details
16678            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16679            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16680                    afterCodeFile, pkg.baseCodePath));
16681            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16682                    afterCodeFile, pkg.splitCodePaths));
16683
16684            // Reflect the rename in app info
16685            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16686            pkg.setApplicationInfoCodePath(pkg.codePath);
16687            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16688            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16689            pkg.setApplicationInfoResourcePath(pkg.codePath);
16690            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16691            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16692
16693            return true;
16694        }
16695
16696        int doPostInstall(int status, int uid) {
16697            if (status != PackageManager.INSTALL_SUCCEEDED) {
16698                cleanUp();
16699            }
16700            return status;
16701        }
16702
16703        @Override
16704        String getCodePath() {
16705            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16706        }
16707
16708        @Override
16709        String getResourcePath() {
16710            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16711        }
16712
16713        private boolean cleanUp() {
16714            if (codeFile == null || !codeFile.exists()) {
16715                return false;
16716            }
16717
16718            removeCodePathLI(codeFile);
16719
16720            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16721                resourceFile.delete();
16722            }
16723
16724            return true;
16725        }
16726
16727        void cleanUpResourcesLI() {
16728            // Try enumerating all code paths before deleting
16729            List<String> allCodePaths = Collections.EMPTY_LIST;
16730            if (codeFile != null && codeFile.exists()) {
16731                try {
16732                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16733                    allCodePaths = pkg.getAllCodePaths();
16734                } catch (PackageParserException e) {
16735                    // Ignored; we tried our best
16736                }
16737            }
16738
16739            cleanUp();
16740            removeDexFiles(allCodePaths, instructionSets);
16741        }
16742
16743        boolean doPostDeleteLI(boolean delete) {
16744            // XXX err, shouldn't we respect the delete flag?
16745            cleanUpResourcesLI();
16746            return true;
16747        }
16748    }
16749
16750    private boolean isAsecExternal(String cid) {
16751        final String asecPath = PackageHelper.getSdFilesystem(cid);
16752        return !asecPath.startsWith(mAsecInternalPath);
16753    }
16754
16755    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16756            PackageManagerException {
16757        if (copyRet < 0) {
16758            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16759                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16760                throw new PackageManagerException(copyRet, message);
16761            }
16762        }
16763    }
16764
16765    /**
16766     * Extract the StorageManagerService "container ID" from the full code path of an
16767     * .apk.
16768     */
16769    static String cidFromCodePath(String fullCodePath) {
16770        int eidx = fullCodePath.lastIndexOf("/");
16771        String subStr1 = fullCodePath.substring(0, eidx);
16772        int sidx = subStr1.lastIndexOf("/");
16773        return subStr1.substring(sidx+1, eidx);
16774    }
16775
16776    /**
16777     * Logic to handle installation of ASEC applications, including copying and
16778     * renaming logic.
16779     */
16780    class AsecInstallArgs extends InstallArgs {
16781        static final String RES_FILE_NAME = "pkg.apk";
16782        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16783
16784        String cid;
16785        String packagePath;
16786        String resourcePath;
16787
16788        /** New install */
16789        AsecInstallArgs(InstallParams params) {
16790            super(params.origin, params.move, params.observer, params.installFlags,
16791                    params.installerPackageName, params.volumeUuid,
16792                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16793                    params.grantedRuntimePermissions,
16794                    params.traceMethod, params.traceCookie, params.certificates,
16795                    params.installReason);
16796        }
16797
16798        /** Existing install */
16799        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16800                        boolean isExternal, boolean isForwardLocked) {
16801            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16802                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16803                    instructionSets, null, null, null, 0, null /*certificates*/,
16804                    PackageManager.INSTALL_REASON_UNKNOWN);
16805            // Hackily pretend we're still looking at a full code path
16806            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16807                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16808            }
16809
16810            // Extract cid from fullCodePath
16811            int eidx = fullCodePath.lastIndexOf("/");
16812            String subStr1 = fullCodePath.substring(0, eidx);
16813            int sidx = subStr1.lastIndexOf("/");
16814            cid = subStr1.substring(sidx+1, eidx);
16815            setMountPath(subStr1);
16816        }
16817
16818        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16819            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16820                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16821                    instructionSets, null, null, null, 0, null /*certificates*/,
16822                    PackageManager.INSTALL_REASON_UNKNOWN);
16823            this.cid = cid;
16824            setMountPath(PackageHelper.getSdDir(cid));
16825        }
16826
16827        void createCopyFile() {
16828            cid = mInstallerService.allocateExternalStageCidLegacy();
16829        }
16830
16831        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16832            if (origin.staged && origin.cid != null) {
16833                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16834                cid = origin.cid;
16835                setMountPath(PackageHelper.getSdDir(cid));
16836                return PackageManager.INSTALL_SUCCEEDED;
16837            }
16838
16839            if (temp) {
16840                createCopyFile();
16841            } else {
16842                /*
16843                 * Pre-emptively destroy the container since it's destroyed if
16844                 * copying fails due to it existing anyway.
16845                 */
16846                PackageHelper.destroySdDir(cid);
16847            }
16848
16849            final String newMountPath = imcs.copyPackageToContainer(
16850                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16851                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16852
16853            if (newMountPath != null) {
16854                setMountPath(newMountPath);
16855                return PackageManager.INSTALL_SUCCEEDED;
16856            } else {
16857                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16858            }
16859        }
16860
16861        @Override
16862        String getCodePath() {
16863            return packagePath;
16864        }
16865
16866        @Override
16867        String getResourcePath() {
16868            return resourcePath;
16869        }
16870
16871        int doPreInstall(int status) {
16872            if (status != PackageManager.INSTALL_SUCCEEDED) {
16873                // Destroy container
16874                PackageHelper.destroySdDir(cid);
16875            } else {
16876                boolean mounted = PackageHelper.isContainerMounted(cid);
16877                if (!mounted) {
16878                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16879                            Process.SYSTEM_UID);
16880                    if (newMountPath != null) {
16881                        setMountPath(newMountPath);
16882                    } else {
16883                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16884                    }
16885                }
16886            }
16887            return status;
16888        }
16889
16890        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16891            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16892            String newMountPath = null;
16893            if (PackageHelper.isContainerMounted(cid)) {
16894                // Unmount the container
16895                if (!PackageHelper.unMountSdDir(cid)) {
16896                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16897                    return false;
16898                }
16899            }
16900            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16901                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16902                        " which might be stale. Will try to clean up.");
16903                // Clean up the stale container and proceed to recreate.
16904                if (!PackageHelper.destroySdDir(newCacheId)) {
16905                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16906                    return false;
16907                }
16908                // Successfully cleaned up stale container. Try to rename again.
16909                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16910                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16911                            + " inspite of cleaning it up.");
16912                    return false;
16913                }
16914            }
16915            if (!PackageHelper.isContainerMounted(newCacheId)) {
16916                Slog.w(TAG, "Mounting container " + newCacheId);
16917                newMountPath = PackageHelper.mountSdDir(newCacheId,
16918                        getEncryptKey(), Process.SYSTEM_UID);
16919            } else {
16920                newMountPath = PackageHelper.getSdDir(newCacheId);
16921            }
16922            if (newMountPath == null) {
16923                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16924                return false;
16925            }
16926            Log.i(TAG, "Succesfully renamed " + cid +
16927                    " to " + newCacheId +
16928                    " at new path: " + newMountPath);
16929            cid = newCacheId;
16930
16931            final File beforeCodeFile = new File(packagePath);
16932            setMountPath(newMountPath);
16933            final File afterCodeFile = new File(packagePath);
16934
16935            // Reflect the rename in scanned details
16936            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16937            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16938                    afterCodeFile, pkg.baseCodePath));
16939            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16940                    afterCodeFile, pkg.splitCodePaths));
16941
16942            // Reflect the rename in app info
16943            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16944            pkg.setApplicationInfoCodePath(pkg.codePath);
16945            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16946            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16947            pkg.setApplicationInfoResourcePath(pkg.codePath);
16948            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16949            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16950
16951            return true;
16952        }
16953
16954        private void setMountPath(String mountPath) {
16955            final File mountFile = new File(mountPath);
16956
16957            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16958            if (monolithicFile.exists()) {
16959                packagePath = monolithicFile.getAbsolutePath();
16960                if (isFwdLocked()) {
16961                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16962                } else {
16963                    resourcePath = packagePath;
16964                }
16965            } else {
16966                packagePath = mountFile.getAbsolutePath();
16967                resourcePath = packagePath;
16968            }
16969        }
16970
16971        int doPostInstall(int status, int uid) {
16972            if (status != PackageManager.INSTALL_SUCCEEDED) {
16973                cleanUp();
16974            } else {
16975                final int groupOwner;
16976                final String protectedFile;
16977                if (isFwdLocked()) {
16978                    groupOwner = UserHandle.getSharedAppGid(uid);
16979                    protectedFile = RES_FILE_NAME;
16980                } else {
16981                    groupOwner = -1;
16982                    protectedFile = null;
16983                }
16984
16985                if (uid < Process.FIRST_APPLICATION_UID
16986                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16987                    Slog.e(TAG, "Failed to finalize " + cid);
16988                    PackageHelper.destroySdDir(cid);
16989                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16990                }
16991
16992                boolean mounted = PackageHelper.isContainerMounted(cid);
16993                if (!mounted) {
16994                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16995                }
16996            }
16997            return status;
16998        }
16999
17000        private void cleanUp() {
17001            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17002
17003            // Destroy secure container
17004            PackageHelper.destroySdDir(cid);
17005        }
17006
17007        private List<String> getAllCodePaths() {
17008            final File codeFile = new File(getCodePath());
17009            if (codeFile != null && codeFile.exists()) {
17010                try {
17011                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17012                    return pkg.getAllCodePaths();
17013                } catch (PackageParserException e) {
17014                    // Ignored; we tried our best
17015                }
17016            }
17017            return Collections.EMPTY_LIST;
17018        }
17019
17020        void cleanUpResourcesLI() {
17021            // Enumerate all code paths before deleting
17022            cleanUpResourcesLI(getAllCodePaths());
17023        }
17024
17025        private void cleanUpResourcesLI(List<String> allCodePaths) {
17026            cleanUp();
17027            removeDexFiles(allCodePaths, instructionSets);
17028        }
17029
17030        String getPackageName() {
17031            return getAsecPackageName(cid);
17032        }
17033
17034        boolean doPostDeleteLI(boolean delete) {
17035            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17036            final List<String> allCodePaths = getAllCodePaths();
17037            boolean mounted = PackageHelper.isContainerMounted(cid);
17038            if (mounted) {
17039                // Unmount first
17040                if (PackageHelper.unMountSdDir(cid)) {
17041                    mounted = false;
17042                }
17043            }
17044            if (!mounted && delete) {
17045                cleanUpResourcesLI(allCodePaths);
17046            }
17047            return !mounted;
17048        }
17049
17050        @Override
17051        int doPreCopy() {
17052            if (isFwdLocked()) {
17053                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17054                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17055                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17056                }
17057            }
17058
17059            return PackageManager.INSTALL_SUCCEEDED;
17060        }
17061
17062        @Override
17063        int doPostCopy(int uid) {
17064            if (isFwdLocked()) {
17065                if (uid < Process.FIRST_APPLICATION_UID
17066                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17067                                RES_FILE_NAME)) {
17068                    Slog.e(TAG, "Failed to finalize " + cid);
17069                    PackageHelper.destroySdDir(cid);
17070                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17071                }
17072            }
17073
17074            return PackageManager.INSTALL_SUCCEEDED;
17075        }
17076    }
17077
17078    /**
17079     * Logic to handle movement of existing installed applications.
17080     */
17081    class MoveInstallArgs extends InstallArgs {
17082        private File codeFile;
17083        private File resourceFile;
17084
17085        /** New install */
17086        MoveInstallArgs(InstallParams params) {
17087            super(params.origin, params.move, params.observer, params.installFlags,
17088                    params.installerPackageName, params.volumeUuid,
17089                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17090                    params.grantedRuntimePermissions,
17091                    params.traceMethod, params.traceCookie, params.certificates,
17092                    params.installReason);
17093        }
17094
17095        int copyApk(IMediaContainerService imcs, boolean temp) {
17096            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17097                    + move.fromUuid + " to " + move.toUuid);
17098            synchronized (mInstaller) {
17099                try {
17100                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17101                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17102                } catch (InstallerException e) {
17103                    Slog.w(TAG, "Failed to move app", e);
17104                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17105                }
17106            }
17107
17108            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17109            resourceFile = codeFile;
17110            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17111
17112            return PackageManager.INSTALL_SUCCEEDED;
17113        }
17114
17115        int doPreInstall(int status) {
17116            if (status != PackageManager.INSTALL_SUCCEEDED) {
17117                cleanUp(move.toUuid);
17118            }
17119            return status;
17120        }
17121
17122        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17123            if (status != PackageManager.INSTALL_SUCCEEDED) {
17124                cleanUp(move.toUuid);
17125                return false;
17126            }
17127
17128            // Reflect the move in app info
17129            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17130            pkg.setApplicationInfoCodePath(pkg.codePath);
17131            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17132            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17133            pkg.setApplicationInfoResourcePath(pkg.codePath);
17134            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17135            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17136
17137            return true;
17138        }
17139
17140        int doPostInstall(int status, int uid) {
17141            if (status == PackageManager.INSTALL_SUCCEEDED) {
17142                cleanUp(move.fromUuid);
17143            } else {
17144                cleanUp(move.toUuid);
17145            }
17146            return status;
17147        }
17148
17149        @Override
17150        String getCodePath() {
17151            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17152        }
17153
17154        @Override
17155        String getResourcePath() {
17156            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17157        }
17158
17159        private boolean cleanUp(String volumeUuid) {
17160            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17161                    move.dataAppName);
17162            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17163            final int[] userIds = sUserManager.getUserIds();
17164            synchronized (mInstallLock) {
17165                // Clean up both app data and code
17166                // All package moves are frozen until finished
17167                for (int userId : userIds) {
17168                    try {
17169                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17170                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17171                    } catch (InstallerException e) {
17172                        Slog.w(TAG, String.valueOf(e));
17173                    }
17174                }
17175                removeCodePathLI(codeFile);
17176            }
17177            return true;
17178        }
17179
17180        void cleanUpResourcesLI() {
17181            throw new UnsupportedOperationException();
17182        }
17183
17184        boolean doPostDeleteLI(boolean delete) {
17185            throw new UnsupportedOperationException();
17186        }
17187    }
17188
17189    static String getAsecPackageName(String packageCid) {
17190        int idx = packageCid.lastIndexOf("-");
17191        if (idx == -1) {
17192            return packageCid;
17193        }
17194        return packageCid.substring(0, idx);
17195    }
17196
17197    // Utility method used to create code paths based on package name and available index.
17198    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17199        String idxStr = "";
17200        int idx = 1;
17201        // Fall back to default value of idx=1 if prefix is not
17202        // part of oldCodePath
17203        if (oldCodePath != null) {
17204            String subStr = oldCodePath;
17205            // Drop the suffix right away
17206            if (suffix != null && subStr.endsWith(suffix)) {
17207                subStr = subStr.substring(0, subStr.length() - suffix.length());
17208            }
17209            // If oldCodePath already contains prefix find out the
17210            // ending index to either increment or decrement.
17211            int sidx = subStr.lastIndexOf(prefix);
17212            if (sidx != -1) {
17213                subStr = subStr.substring(sidx + prefix.length());
17214                if (subStr != null) {
17215                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17216                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17217                    }
17218                    try {
17219                        idx = Integer.parseInt(subStr);
17220                        if (idx <= 1) {
17221                            idx++;
17222                        } else {
17223                            idx--;
17224                        }
17225                    } catch(NumberFormatException e) {
17226                    }
17227                }
17228            }
17229        }
17230        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17231        return prefix + idxStr;
17232    }
17233
17234    private File getNextCodePath(File targetDir, String packageName) {
17235        File result;
17236        SecureRandom random = new SecureRandom();
17237        byte[] bytes = new byte[16];
17238        do {
17239            random.nextBytes(bytes);
17240            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17241            result = new File(targetDir, packageName + "-" + suffix);
17242        } while (result.exists());
17243        return result;
17244    }
17245
17246    // Utility method that returns the relative package path with respect
17247    // to the installation directory. Like say for /data/data/com.test-1.apk
17248    // string com.test-1 is returned.
17249    static String deriveCodePathName(String codePath) {
17250        if (codePath == null) {
17251            return null;
17252        }
17253        final File codeFile = new File(codePath);
17254        final String name = codeFile.getName();
17255        if (codeFile.isDirectory()) {
17256            return name;
17257        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17258            final int lastDot = name.lastIndexOf('.');
17259            return name.substring(0, lastDot);
17260        } else {
17261            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17262            return null;
17263        }
17264    }
17265
17266    static class PackageInstalledInfo {
17267        String name;
17268        int uid;
17269        // The set of users that originally had this package installed.
17270        int[] origUsers;
17271        // The set of users that now have this package installed.
17272        int[] newUsers;
17273        PackageParser.Package pkg;
17274        int returnCode;
17275        String returnMsg;
17276        PackageRemovedInfo removedInfo;
17277        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17278
17279        public void setError(int code, String msg) {
17280            setReturnCode(code);
17281            setReturnMessage(msg);
17282            Slog.w(TAG, msg);
17283        }
17284
17285        public void setError(String msg, PackageParserException e) {
17286            setReturnCode(e.error);
17287            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17288            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17289            for (int i = 0; i < childCount; i++) {
17290                addedChildPackages.valueAt(i).setError(msg, e);
17291            }
17292            Slog.w(TAG, msg, e);
17293        }
17294
17295        public void setError(String msg, PackageManagerException e) {
17296            returnCode = e.error;
17297            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17298            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17299            for (int i = 0; i < childCount; i++) {
17300                addedChildPackages.valueAt(i).setError(msg, e);
17301            }
17302            Slog.w(TAG, msg, e);
17303        }
17304
17305        public void setReturnCode(int returnCode) {
17306            this.returnCode = returnCode;
17307            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17308            for (int i = 0; i < childCount; i++) {
17309                addedChildPackages.valueAt(i).returnCode = returnCode;
17310            }
17311        }
17312
17313        private void setReturnMessage(String returnMsg) {
17314            this.returnMsg = returnMsg;
17315            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17316            for (int i = 0; i < childCount; i++) {
17317                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17318            }
17319        }
17320
17321        // In some error cases we want to convey more info back to the observer
17322        String origPackage;
17323        String origPermission;
17324    }
17325
17326    /*
17327     * Install a non-existing package.
17328     */
17329    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17330            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17331            PackageInstalledInfo res, int installReason) {
17332        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17333
17334        // Remember this for later, in case we need to rollback this install
17335        String pkgName = pkg.packageName;
17336
17337        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17338
17339        synchronized(mPackages) {
17340            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17341            if (renamedPackage != null) {
17342                // A package with the same name is already installed, though
17343                // it has been renamed to an older name.  The package we
17344                // are trying to install should be installed as an update to
17345                // the existing one, but that has not been requested, so bail.
17346                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17347                        + " without first uninstalling package running as "
17348                        + renamedPackage);
17349                return;
17350            }
17351            if (mPackages.containsKey(pkgName)) {
17352                // Don't allow installation over an existing package with the same name.
17353                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17354                        + " without first uninstalling.");
17355                return;
17356            }
17357        }
17358
17359        try {
17360            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17361                    System.currentTimeMillis(), user);
17362
17363            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17364
17365            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17366                prepareAppDataAfterInstallLIF(newPackage);
17367
17368            } else {
17369                // Remove package from internal structures, but keep around any
17370                // data that might have already existed
17371                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17372                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17373            }
17374        } catch (PackageManagerException e) {
17375            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17376        }
17377
17378        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17379    }
17380
17381    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17382        // Can't rotate keys during boot or if sharedUser.
17383        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17384                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17385            return false;
17386        }
17387        // app is using upgradeKeySets; make sure all are valid
17388        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17389        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17390        for (int i = 0; i < upgradeKeySets.length; i++) {
17391            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17392                Slog.wtf(TAG, "Package "
17393                         + (oldPs.name != null ? oldPs.name : "<null>")
17394                         + " contains upgrade-key-set reference to unknown key-set: "
17395                         + upgradeKeySets[i]
17396                         + " reverting to signatures check.");
17397                return false;
17398            }
17399        }
17400        return true;
17401    }
17402
17403    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17404        // Upgrade keysets are being used.  Determine if new package has a superset of the
17405        // required keys.
17406        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17407        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17408        for (int i = 0; i < upgradeKeySets.length; i++) {
17409            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17410            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17411                return true;
17412            }
17413        }
17414        return false;
17415    }
17416
17417    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17418        try (DigestInputStream digestStream =
17419                new DigestInputStream(new FileInputStream(file), digest)) {
17420            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17421        }
17422    }
17423
17424    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17425            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17426            int installReason) {
17427        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17428
17429        final PackageParser.Package oldPackage;
17430        final PackageSetting ps;
17431        final String pkgName = pkg.packageName;
17432        final int[] allUsers;
17433        final int[] installedUsers;
17434
17435        synchronized(mPackages) {
17436            oldPackage = mPackages.get(pkgName);
17437            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17438
17439            // don't allow upgrade to target a release SDK from a pre-release SDK
17440            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17441                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17442            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17443                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17444            if (oldTargetsPreRelease
17445                    && !newTargetsPreRelease
17446                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17447                Slog.w(TAG, "Can't install package targeting released sdk");
17448                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17449                return;
17450            }
17451
17452            ps = mSettings.mPackages.get(pkgName);
17453
17454            // verify signatures are valid
17455            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17456                if (!checkUpgradeKeySetLP(ps, pkg)) {
17457                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17458                            "New package not signed by keys specified by upgrade-keysets: "
17459                                    + pkgName);
17460                    return;
17461                }
17462            } else {
17463                // default to original signature matching
17464                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17465                        != PackageManager.SIGNATURE_MATCH) {
17466                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17467                            "New package has a different signature: " + pkgName);
17468                    return;
17469                }
17470            }
17471
17472            // don't allow a system upgrade unless the upgrade hash matches
17473            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17474                byte[] digestBytes = null;
17475                try {
17476                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17477                    updateDigest(digest, new File(pkg.baseCodePath));
17478                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17479                        for (String path : pkg.splitCodePaths) {
17480                            updateDigest(digest, new File(path));
17481                        }
17482                    }
17483                    digestBytes = digest.digest();
17484                } catch (NoSuchAlgorithmException | IOException e) {
17485                    res.setError(INSTALL_FAILED_INVALID_APK,
17486                            "Could not compute hash: " + pkgName);
17487                    return;
17488                }
17489                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17490                    res.setError(INSTALL_FAILED_INVALID_APK,
17491                            "New package fails restrict-update check: " + pkgName);
17492                    return;
17493                }
17494                // retain upgrade restriction
17495                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17496            }
17497
17498            // Check for shared user id changes
17499            String invalidPackageName =
17500                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17501            if (invalidPackageName != null) {
17502                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17503                        "Package " + invalidPackageName + " tried to change user "
17504                                + oldPackage.mSharedUserId);
17505                return;
17506            }
17507
17508            // In case of rollback, remember per-user/profile install state
17509            allUsers = sUserManager.getUserIds();
17510            installedUsers = ps.queryInstalledUsers(allUsers, true);
17511
17512            // don't allow an upgrade from full to ephemeral
17513            if (isInstantApp) {
17514                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17515                    for (int currentUser : allUsers) {
17516                        if (!ps.getInstantApp(currentUser)) {
17517                            // can't downgrade from full to instant
17518                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17519                                    + " for user: " + currentUser);
17520                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17521                            return;
17522                        }
17523                    }
17524                } else if (!ps.getInstantApp(user.getIdentifier())) {
17525                    // can't downgrade from full to instant
17526                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17527                            + " for user: " + user.getIdentifier());
17528                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17529                    return;
17530                }
17531            }
17532        }
17533
17534        // Update what is removed
17535        res.removedInfo = new PackageRemovedInfo(this);
17536        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17537        res.removedInfo.removedPackage = oldPackage.packageName;
17538        res.removedInfo.installerPackageName = ps.installerPackageName;
17539        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17540        res.removedInfo.isUpdate = true;
17541        res.removedInfo.origUsers = installedUsers;
17542        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17543        for (int i = 0; i < installedUsers.length; i++) {
17544            final int userId = installedUsers[i];
17545            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17546        }
17547
17548        final int childCount = (oldPackage.childPackages != null)
17549                ? oldPackage.childPackages.size() : 0;
17550        for (int i = 0; i < childCount; i++) {
17551            boolean childPackageUpdated = false;
17552            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17553            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17554            if (res.addedChildPackages != null) {
17555                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17556                if (childRes != null) {
17557                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17558                    childRes.removedInfo.removedPackage = childPkg.packageName;
17559                    if (childPs != null) {
17560                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17561                    }
17562                    childRes.removedInfo.isUpdate = true;
17563                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17564                    childPackageUpdated = true;
17565                }
17566            }
17567            if (!childPackageUpdated) {
17568                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17569                childRemovedRes.removedPackage = childPkg.packageName;
17570                if (childPs != null) {
17571                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17572                }
17573                childRemovedRes.isUpdate = false;
17574                childRemovedRes.dataRemoved = true;
17575                synchronized (mPackages) {
17576                    if (childPs != null) {
17577                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17578                    }
17579                }
17580                if (res.removedInfo.removedChildPackages == null) {
17581                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17582                }
17583                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17584            }
17585        }
17586
17587        boolean sysPkg = (isSystemApp(oldPackage));
17588        if (sysPkg) {
17589            // Set the system/privileged flags as needed
17590            final boolean privileged =
17591                    (oldPackage.applicationInfo.privateFlags
17592                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17593            final int systemPolicyFlags = policyFlags
17594                    | PackageParser.PARSE_IS_SYSTEM
17595                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17596
17597            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17598                    user, allUsers, installerPackageName, res, installReason);
17599        } else {
17600            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17601                    user, allUsers, installerPackageName, res, installReason);
17602        }
17603    }
17604
17605    @Override
17606    public List<String> getPreviousCodePaths(String packageName) {
17607        final int callingUid = Binder.getCallingUid();
17608        final List<String> result = new ArrayList<>();
17609        if (getInstantAppPackageName(callingUid) != null) {
17610            return result;
17611        }
17612        final PackageSetting ps = mSettings.mPackages.get(packageName);
17613        if (ps != null
17614                && ps.oldCodePaths != null
17615                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17616            result.addAll(ps.oldCodePaths);
17617        }
17618        return result;
17619    }
17620
17621    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17622            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17623            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17624            int installReason) {
17625        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17626                + deletedPackage);
17627
17628        String pkgName = deletedPackage.packageName;
17629        boolean deletedPkg = true;
17630        boolean addedPkg = false;
17631        boolean updatedSettings = false;
17632        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17633        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17634                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17635
17636        final long origUpdateTime = (pkg.mExtras != null)
17637                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17638
17639        // First delete the existing package while retaining the data directory
17640        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17641                res.removedInfo, true, pkg)) {
17642            // If the existing package wasn't successfully deleted
17643            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17644            deletedPkg = false;
17645        } else {
17646            // Successfully deleted the old package; proceed with replace.
17647
17648            // If deleted package lived in a container, give users a chance to
17649            // relinquish resources before killing.
17650            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17651                if (DEBUG_INSTALL) {
17652                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17653                }
17654                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17655                final ArrayList<String> pkgList = new ArrayList<String>(1);
17656                pkgList.add(deletedPackage.applicationInfo.packageName);
17657                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17658            }
17659
17660            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17661                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17662            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17663
17664            try {
17665                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17666                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17667                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17668                        installReason);
17669
17670                // Update the in-memory copy of the previous code paths.
17671                PackageSetting ps = mSettings.mPackages.get(pkgName);
17672                if (!killApp) {
17673                    if (ps.oldCodePaths == null) {
17674                        ps.oldCodePaths = new ArraySet<>();
17675                    }
17676                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17677                    if (deletedPackage.splitCodePaths != null) {
17678                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17679                    }
17680                } else {
17681                    ps.oldCodePaths = null;
17682                }
17683                if (ps.childPackageNames != null) {
17684                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17685                        final String childPkgName = ps.childPackageNames.get(i);
17686                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17687                        childPs.oldCodePaths = ps.oldCodePaths;
17688                    }
17689                }
17690                // set instant app status, but, only if it's explicitly specified
17691                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17692                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17693                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17694                prepareAppDataAfterInstallLIF(newPackage);
17695                addedPkg = true;
17696                mDexManager.notifyPackageUpdated(newPackage.packageName,
17697                        newPackage.baseCodePath, newPackage.splitCodePaths);
17698            } catch (PackageManagerException e) {
17699                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17700            }
17701        }
17702
17703        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17704            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17705
17706            // Revert all internal state mutations and added folders for the failed install
17707            if (addedPkg) {
17708                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17709                        res.removedInfo, true, null);
17710            }
17711
17712            // Restore the old package
17713            if (deletedPkg) {
17714                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17715                File restoreFile = new File(deletedPackage.codePath);
17716                // Parse old package
17717                boolean oldExternal = isExternal(deletedPackage);
17718                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17719                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17720                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17721                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17722                try {
17723                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17724                            null);
17725                } catch (PackageManagerException e) {
17726                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17727                            + e.getMessage());
17728                    return;
17729                }
17730
17731                synchronized (mPackages) {
17732                    // Ensure the installer package name up to date
17733                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17734
17735                    // Update permissions for restored package
17736                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17737
17738                    mSettings.writeLPr();
17739                }
17740
17741                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17742            }
17743        } else {
17744            synchronized (mPackages) {
17745                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17746                if (ps != null) {
17747                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17748                    if (res.removedInfo.removedChildPackages != null) {
17749                        final int childCount = res.removedInfo.removedChildPackages.size();
17750                        // Iterate in reverse as we may modify the collection
17751                        for (int i = childCount - 1; i >= 0; i--) {
17752                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17753                            if (res.addedChildPackages.containsKey(childPackageName)) {
17754                                res.removedInfo.removedChildPackages.removeAt(i);
17755                            } else {
17756                                PackageRemovedInfo childInfo = res.removedInfo
17757                                        .removedChildPackages.valueAt(i);
17758                                childInfo.removedForAllUsers = mPackages.get(
17759                                        childInfo.removedPackage) == null;
17760                            }
17761                        }
17762                    }
17763                }
17764            }
17765        }
17766    }
17767
17768    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17769            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17770            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17771            int installReason) {
17772        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17773                + ", old=" + deletedPackage);
17774
17775        final boolean disabledSystem;
17776
17777        // Remove existing system package
17778        removePackageLI(deletedPackage, true);
17779
17780        synchronized (mPackages) {
17781            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17782        }
17783        if (!disabledSystem) {
17784            // We didn't need to disable the .apk as a current system package,
17785            // which means we are replacing another update that is already
17786            // installed.  We need to make sure to delete the older one's .apk.
17787            res.removedInfo.args = createInstallArgsForExisting(0,
17788                    deletedPackage.applicationInfo.getCodePath(),
17789                    deletedPackage.applicationInfo.getResourcePath(),
17790                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17791        } else {
17792            res.removedInfo.args = null;
17793        }
17794
17795        // Successfully disabled the old package. Now proceed with re-installation
17796        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17797                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17798        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17799
17800        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17801        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17802                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17803
17804        PackageParser.Package newPackage = null;
17805        try {
17806            // Add the package to the internal data structures
17807            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17808
17809            // Set the update and install times
17810            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17811            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17812                    System.currentTimeMillis());
17813
17814            // Update the package dynamic state if succeeded
17815            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17816                // Now that the install succeeded make sure we remove data
17817                // directories for any child package the update removed.
17818                final int deletedChildCount = (deletedPackage.childPackages != null)
17819                        ? deletedPackage.childPackages.size() : 0;
17820                final int newChildCount = (newPackage.childPackages != null)
17821                        ? newPackage.childPackages.size() : 0;
17822                for (int i = 0; i < deletedChildCount; i++) {
17823                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17824                    boolean childPackageDeleted = true;
17825                    for (int j = 0; j < newChildCount; j++) {
17826                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17827                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17828                            childPackageDeleted = false;
17829                            break;
17830                        }
17831                    }
17832                    if (childPackageDeleted) {
17833                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17834                                deletedChildPkg.packageName);
17835                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17836                            PackageRemovedInfo removedChildRes = res.removedInfo
17837                                    .removedChildPackages.get(deletedChildPkg.packageName);
17838                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17839                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17840                        }
17841                    }
17842                }
17843
17844                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17845                        installReason);
17846                prepareAppDataAfterInstallLIF(newPackage);
17847
17848                mDexManager.notifyPackageUpdated(newPackage.packageName,
17849                            newPackage.baseCodePath, newPackage.splitCodePaths);
17850            }
17851        } catch (PackageManagerException e) {
17852            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17853            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17854        }
17855
17856        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17857            // Re installation failed. Restore old information
17858            // Remove new pkg information
17859            if (newPackage != null) {
17860                removeInstalledPackageLI(newPackage, true);
17861            }
17862            // Add back the old system package
17863            try {
17864                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17865            } catch (PackageManagerException e) {
17866                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17867            }
17868
17869            synchronized (mPackages) {
17870                if (disabledSystem) {
17871                    enableSystemPackageLPw(deletedPackage);
17872                }
17873
17874                // Ensure the installer package name up to date
17875                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17876
17877                // Update permissions for restored package
17878                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17879
17880                mSettings.writeLPr();
17881            }
17882
17883            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17884                    + " after failed upgrade");
17885        }
17886    }
17887
17888    /**
17889     * Checks whether the parent or any of the child packages have a change shared
17890     * user. For a package to be a valid update the shred users of the parent and
17891     * the children should match. We may later support changing child shared users.
17892     * @param oldPkg The updated package.
17893     * @param newPkg The update package.
17894     * @return The shared user that change between the versions.
17895     */
17896    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17897            PackageParser.Package newPkg) {
17898        // Check parent shared user
17899        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17900            return newPkg.packageName;
17901        }
17902        // Check child shared users
17903        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17904        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17905        for (int i = 0; i < newChildCount; i++) {
17906            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17907            // If this child was present, did it have the same shared user?
17908            for (int j = 0; j < oldChildCount; j++) {
17909                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17910                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17911                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17912                    return newChildPkg.packageName;
17913                }
17914            }
17915        }
17916        return null;
17917    }
17918
17919    private void removeNativeBinariesLI(PackageSetting ps) {
17920        // Remove the lib path for the parent package
17921        if (ps != null) {
17922            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17923            // Remove the lib path for the child packages
17924            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17925            for (int i = 0; i < childCount; i++) {
17926                PackageSetting childPs = null;
17927                synchronized (mPackages) {
17928                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17929                }
17930                if (childPs != null) {
17931                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17932                            .legacyNativeLibraryPathString);
17933                }
17934            }
17935        }
17936    }
17937
17938    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17939        // Enable the parent package
17940        mSettings.enableSystemPackageLPw(pkg.packageName);
17941        // Enable the child packages
17942        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17943        for (int i = 0; i < childCount; i++) {
17944            PackageParser.Package childPkg = pkg.childPackages.get(i);
17945            mSettings.enableSystemPackageLPw(childPkg.packageName);
17946        }
17947    }
17948
17949    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17950            PackageParser.Package newPkg) {
17951        // Disable the parent package (parent always replaced)
17952        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17953        // Disable the child packages
17954        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17955        for (int i = 0; i < childCount; i++) {
17956            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17957            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17958            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17959        }
17960        return disabled;
17961    }
17962
17963    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17964            String installerPackageName) {
17965        // Enable the parent package
17966        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17967        // Enable the child packages
17968        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17969        for (int i = 0; i < childCount; i++) {
17970            PackageParser.Package childPkg = pkg.childPackages.get(i);
17971            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17972        }
17973    }
17974
17975    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17976        // Collect all used permissions in the UID
17977        ArraySet<String> usedPermissions = new ArraySet<>();
17978        final int packageCount = su.packages.size();
17979        for (int i = 0; i < packageCount; i++) {
17980            PackageSetting ps = su.packages.valueAt(i);
17981            if (ps.pkg == null) {
17982                continue;
17983            }
17984            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17985            for (int j = 0; j < requestedPermCount; j++) {
17986                String permission = ps.pkg.requestedPermissions.get(j);
17987                BasePermission bp = mSettings.mPermissions.get(permission);
17988                if (bp != null) {
17989                    usedPermissions.add(permission);
17990                }
17991            }
17992        }
17993
17994        PermissionsState permissionsState = su.getPermissionsState();
17995        // Prune install permissions
17996        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17997        final int installPermCount = installPermStates.size();
17998        for (int i = installPermCount - 1; i >= 0;  i--) {
17999            PermissionState permissionState = installPermStates.get(i);
18000            if (!usedPermissions.contains(permissionState.getName())) {
18001                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18002                if (bp != null) {
18003                    permissionsState.revokeInstallPermission(bp);
18004                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18005                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18006                }
18007            }
18008        }
18009
18010        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18011
18012        // Prune runtime permissions
18013        for (int userId : allUserIds) {
18014            List<PermissionState> runtimePermStates = permissionsState
18015                    .getRuntimePermissionStates(userId);
18016            final int runtimePermCount = runtimePermStates.size();
18017            for (int i = runtimePermCount - 1; i >= 0; i--) {
18018                PermissionState permissionState = runtimePermStates.get(i);
18019                if (!usedPermissions.contains(permissionState.getName())) {
18020                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18021                    if (bp != null) {
18022                        permissionsState.revokeRuntimePermission(bp, userId);
18023                        permissionsState.updatePermissionFlags(bp, userId,
18024                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18025                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18026                                runtimePermissionChangedUserIds, userId);
18027                    }
18028                }
18029            }
18030        }
18031
18032        return runtimePermissionChangedUserIds;
18033    }
18034
18035    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18036            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18037        // Update the parent package setting
18038        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18039                res, user, installReason);
18040        // Update the child packages setting
18041        final int childCount = (newPackage.childPackages != null)
18042                ? newPackage.childPackages.size() : 0;
18043        for (int i = 0; i < childCount; i++) {
18044            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18045            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18046            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18047                    childRes.origUsers, childRes, user, installReason);
18048        }
18049    }
18050
18051    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18052            String installerPackageName, int[] allUsers, int[] installedForUsers,
18053            PackageInstalledInfo res, UserHandle user, int installReason) {
18054        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18055
18056        String pkgName = newPackage.packageName;
18057        synchronized (mPackages) {
18058            //write settings. the installStatus will be incomplete at this stage.
18059            //note that the new package setting would have already been
18060            //added to mPackages. It hasn't been persisted yet.
18061            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18062            // TODO: Remove this write? It's also written at the end of this method
18063            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18064            mSettings.writeLPr();
18065            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18066        }
18067
18068        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18069        synchronized (mPackages) {
18070            updatePermissionsLPw(newPackage.packageName, newPackage,
18071                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18072                            ? UPDATE_PERMISSIONS_ALL : 0));
18073            // For system-bundled packages, we assume that installing an upgraded version
18074            // of the package implies that the user actually wants to run that new code,
18075            // so we enable the package.
18076            PackageSetting ps = mSettings.mPackages.get(pkgName);
18077            final int userId = user.getIdentifier();
18078            if (ps != null) {
18079                if (isSystemApp(newPackage)) {
18080                    if (DEBUG_INSTALL) {
18081                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18082                    }
18083                    // Enable system package for requested users
18084                    if (res.origUsers != null) {
18085                        for (int origUserId : res.origUsers) {
18086                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18087                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18088                                        origUserId, installerPackageName);
18089                            }
18090                        }
18091                    }
18092                    // Also convey the prior install/uninstall state
18093                    if (allUsers != null && installedForUsers != null) {
18094                        for (int currentUserId : allUsers) {
18095                            final boolean installed = ArrayUtils.contains(
18096                                    installedForUsers, currentUserId);
18097                            if (DEBUG_INSTALL) {
18098                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18099                            }
18100                            ps.setInstalled(installed, currentUserId);
18101                        }
18102                        // these install state changes will be persisted in the
18103                        // upcoming call to mSettings.writeLPr().
18104                    }
18105                }
18106                // It's implied that when a user requests installation, they want the app to be
18107                // installed and enabled.
18108                if (userId != UserHandle.USER_ALL) {
18109                    ps.setInstalled(true, userId);
18110                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18111                }
18112
18113                // When replacing an existing package, preserve the original install reason for all
18114                // users that had the package installed before.
18115                final Set<Integer> previousUserIds = new ArraySet<>();
18116                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18117                    final int installReasonCount = res.removedInfo.installReasons.size();
18118                    for (int i = 0; i < installReasonCount; i++) {
18119                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18120                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18121                        ps.setInstallReason(previousInstallReason, previousUserId);
18122                        previousUserIds.add(previousUserId);
18123                    }
18124                }
18125
18126                // Set install reason for users that are having the package newly installed.
18127                if (userId == UserHandle.USER_ALL) {
18128                    for (int currentUserId : sUserManager.getUserIds()) {
18129                        if (!previousUserIds.contains(currentUserId)) {
18130                            ps.setInstallReason(installReason, currentUserId);
18131                        }
18132                    }
18133                } else if (!previousUserIds.contains(userId)) {
18134                    ps.setInstallReason(installReason, userId);
18135                }
18136                mSettings.writeKernelMappingLPr(ps);
18137            }
18138            res.name = pkgName;
18139            res.uid = newPackage.applicationInfo.uid;
18140            res.pkg = newPackage;
18141            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18142            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18143            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18144            //to update install status
18145            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18146            mSettings.writeLPr();
18147            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18148        }
18149
18150        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18151    }
18152
18153    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18154        try {
18155            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18156            installPackageLI(args, res);
18157        } finally {
18158            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18159        }
18160    }
18161
18162    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18163        final int installFlags = args.installFlags;
18164        final String installerPackageName = args.installerPackageName;
18165        final String volumeUuid = args.volumeUuid;
18166        final File tmpPackageFile = new File(args.getCodePath());
18167        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18168        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18169                || (args.volumeUuid != null));
18170        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18171        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18172        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18173        boolean replace = false;
18174        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18175        if (args.move != null) {
18176            // moving a complete application; perform an initial scan on the new install location
18177            scanFlags |= SCAN_INITIAL;
18178        }
18179        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18180            scanFlags |= SCAN_DONT_KILL_APP;
18181        }
18182        if (instantApp) {
18183            scanFlags |= SCAN_AS_INSTANT_APP;
18184        }
18185        if (fullApp) {
18186            scanFlags |= SCAN_AS_FULL_APP;
18187        }
18188
18189        // Result object to be returned
18190        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18191
18192        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18193
18194        // Sanity check
18195        if (instantApp && (forwardLocked || onExternal)) {
18196            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18197                    + " external=" + onExternal);
18198            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18199            return;
18200        }
18201
18202        // Retrieve PackageSettings and parse package
18203        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18204                | PackageParser.PARSE_ENFORCE_CODE
18205                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18206                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18207                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18208                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18209        PackageParser pp = new PackageParser();
18210        pp.setSeparateProcesses(mSeparateProcesses);
18211        pp.setDisplayMetrics(mMetrics);
18212        pp.setCallback(mPackageParserCallback);
18213
18214        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18215        final PackageParser.Package pkg;
18216        try {
18217            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18218        } catch (PackageParserException e) {
18219            res.setError("Failed parse during installPackageLI", e);
18220            return;
18221        } finally {
18222            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18223        }
18224
18225        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18226        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18227            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18228            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18229                    "Instant app package must target O");
18230            return;
18231        }
18232        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18233            Slog.w(TAG, "Instant app package " + pkg.packageName
18234                    + " does not target targetSandboxVersion 2");
18235            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18236                    "Instant app package must use targetSanboxVersion 2");
18237            return;
18238        }
18239
18240        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18241            // Static shared libraries have synthetic package names
18242            renameStaticSharedLibraryPackage(pkg);
18243
18244            // No static shared libs on external storage
18245            if (onExternal) {
18246                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18247                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18248                        "Packages declaring static-shared libs cannot be updated");
18249                return;
18250            }
18251        }
18252
18253        // If we are installing a clustered package add results for the children
18254        if (pkg.childPackages != null) {
18255            synchronized (mPackages) {
18256                final int childCount = pkg.childPackages.size();
18257                for (int i = 0; i < childCount; i++) {
18258                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18259                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18260                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18261                    childRes.pkg = childPkg;
18262                    childRes.name = childPkg.packageName;
18263                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18264                    if (childPs != null) {
18265                        childRes.origUsers = childPs.queryInstalledUsers(
18266                                sUserManager.getUserIds(), true);
18267                    }
18268                    if ((mPackages.containsKey(childPkg.packageName))) {
18269                        childRes.removedInfo = new PackageRemovedInfo(this);
18270                        childRes.removedInfo.removedPackage = childPkg.packageName;
18271                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18272                    }
18273                    if (res.addedChildPackages == null) {
18274                        res.addedChildPackages = new ArrayMap<>();
18275                    }
18276                    res.addedChildPackages.put(childPkg.packageName, childRes);
18277                }
18278            }
18279        }
18280
18281        // If package doesn't declare API override, mark that we have an install
18282        // time CPU ABI override.
18283        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18284            pkg.cpuAbiOverride = args.abiOverride;
18285        }
18286
18287        String pkgName = res.name = pkg.packageName;
18288        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18289            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18290                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18291                return;
18292            }
18293        }
18294
18295        try {
18296            // either use what we've been given or parse directly from the APK
18297            if (args.certificates != null) {
18298                try {
18299                    PackageParser.populateCertificates(pkg, args.certificates);
18300                } catch (PackageParserException e) {
18301                    // there was something wrong with the certificates we were given;
18302                    // try to pull them from the APK
18303                    PackageParser.collectCertificates(pkg, parseFlags);
18304                }
18305            } else {
18306                PackageParser.collectCertificates(pkg, parseFlags);
18307            }
18308        } catch (PackageParserException e) {
18309            res.setError("Failed collect during installPackageLI", e);
18310            return;
18311        }
18312
18313        // Get rid of all references to package scan path via parser.
18314        pp = null;
18315        String oldCodePath = null;
18316        boolean systemApp = false;
18317        synchronized (mPackages) {
18318            // Check if installing already existing package
18319            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18320                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18321                if (pkg.mOriginalPackages != null
18322                        && pkg.mOriginalPackages.contains(oldName)
18323                        && mPackages.containsKey(oldName)) {
18324                    // This package is derived from an original package,
18325                    // and this device has been updating from that original
18326                    // name.  We must continue using the original name, so
18327                    // rename the new package here.
18328                    pkg.setPackageName(oldName);
18329                    pkgName = pkg.packageName;
18330                    replace = true;
18331                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18332                            + oldName + " pkgName=" + pkgName);
18333                } else if (mPackages.containsKey(pkgName)) {
18334                    // This package, under its official name, already exists
18335                    // on the device; we should replace it.
18336                    replace = true;
18337                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18338                }
18339
18340                // Child packages are installed through the parent package
18341                if (pkg.parentPackage != null) {
18342                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18343                            "Package " + pkg.packageName + " is child of package "
18344                                    + pkg.parentPackage.parentPackage + ". Child packages "
18345                                    + "can be updated only through the parent package.");
18346                    return;
18347                }
18348
18349                if (replace) {
18350                    // Prevent apps opting out from runtime permissions
18351                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18352                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18353                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18354                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18355                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18356                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18357                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18358                                        + " doesn't support runtime permissions but the old"
18359                                        + " target SDK " + oldTargetSdk + " does.");
18360                        return;
18361                    }
18362                    // Prevent apps from downgrading their targetSandbox.
18363                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18364                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18365                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18366                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18367                                "Package " + pkg.packageName + " new target sandbox "
18368                                + newTargetSandbox + " is incompatible with the previous value of"
18369                                + oldTargetSandbox + ".");
18370                        return;
18371                    }
18372
18373                    // Prevent installing of child packages
18374                    if (oldPackage.parentPackage != null) {
18375                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18376                                "Package " + pkg.packageName + " is child of package "
18377                                        + oldPackage.parentPackage + ". Child packages "
18378                                        + "can be updated only through the parent package.");
18379                        return;
18380                    }
18381                }
18382            }
18383
18384            PackageSetting ps = mSettings.mPackages.get(pkgName);
18385            if (ps != null) {
18386                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18387
18388                // Static shared libs have same package with different versions where
18389                // we internally use a synthetic package name to allow multiple versions
18390                // of the same package, therefore we need to compare signatures against
18391                // the package setting for the latest library version.
18392                PackageSetting signatureCheckPs = ps;
18393                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18394                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18395                    if (libraryEntry != null) {
18396                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18397                    }
18398                }
18399
18400                // Quick sanity check that we're signed correctly if updating;
18401                // we'll check this again later when scanning, but we want to
18402                // bail early here before tripping over redefined permissions.
18403                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18404                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18405                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18406                                + pkg.packageName + " upgrade keys do not match the "
18407                                + "previously installed version");
18408                        return;
18409                    }
18410                } else {
18411                    try {
18412                        verifySignaturesLP(signatureCheckPs, pkg);
18413                    } catch (PackageManagerException e) {
18414                        res.setError(e.error, e.getMessage());
18415                        return;
18416                    }
18417                }
18418
18419                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18420                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18421                    systemApp = (ps.pkg.applicationInfo.flags &
18422                            ApplicationInfo.FLAG_SYSTEM) != 0;
18423                }
18424                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18425            }
18426
18427            int N = pkg.permissions.size();
18428            for (int i = N-1; i >= 0; i--) {
18429                PackageParser.Permission perm = pkg.permissions.get(i);
18430                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18431
18432                // Don't allow anyone but the system to define ephemeral permissions.
18433                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18434                        && !systemApp) {
18435                    Slog.w(TAG, "Non-System package " + pkg.packageName
18436                            + " attempting to delcare ephemeral permission "
18437                            + perm.info.name + "; Removing ephemeral.");
18438                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18439                }
18440                // Check whether the newly-scanned package wants to define an already-defined perm
18441                if (bp != null) {
18442                    // If the defining package is signed with our cert, it's okay.  This
18443                    // also includes the "updating the same package" case, of course.
18444                    // "updating same package" could also involve key-rotation.
18445                    final boolean sigsOk;
18446                    if (bp.sourcePackage.equals(pkg.packageName)
18447                            && (bp.packageSetting instanceof PackageSetting)
18448                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18449                                    scanFlags))) {
18450                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18451                    } else {
18452                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18453                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18454                    }
18455                    if (!sigsOk) {
18456                        // If the owning package is the system itself, we log but allow
18457                        // install to proceed; we fail the install on all other permission
18458                        // redefinitions.
18459                        if (!bp.sourcePackage.equals("android")) {
18460                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18461                                    + pkg.packageName + " attempting to redeclare permission "
18462                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18463                            res.origPermission = perm.info.name;
18464                            res.origPackage = bp.sourcePackage;
18465                            return;
18466                        } else {
18467                            Slog.w(TAG, "Package " + pkg.packageName
18468                                    + " attempting to redeclare system permission "
18469                                    + perm.info.name + "; ignoring new declaration");
18470                            pkg.permissions.remove(i);
18471                        }
18472                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18473                        // Prevent apps to change protection level to dangerous from any other
18474                        // type as this would allow a privilege escalation where an app adds a
18475                        // normal/signature permission in other app's group and later redefines
18476                        // it as dangerous leading to the group auto-grant.
18477                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18478                                == PermissionInfo.PROTECTION_DANGEROUS) {
18479                            if (bp != null && !bp.isRuntime()) {
18480                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18481                                        + "non-runtime permission " + perm.info.name
18482                                        + " to runtime; keeping old protection level");
18483                                perm.info.protectionLevel = bp.protectionLevel;
18484                            }
18485                        }
18486                    }
18487                }
18488            }
18489        }
18490
18491        if (systemApp) {
18492            if (onExternal) {
18493                // Abort update; system app can't be replaced with app on sdcard
18494                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18495                        "Cannot install updates to system apps on sdcard");
18496                return;
18497            } else if (instantApp) {
18498                // Abort update; system app can't be replaced with an instant app
18499                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18500                        "Cannot update a system app with an instant app");
18501                return;
18502            }
18503        }
18504
18505        if (args.move != null) {
18506            // We did an in-place move, so dex is ready to roll
18507            scanFlags |= SCAN_NO_DEX;
18508            scanFlags |= SCAN_MOVE;
18509
18510            synchronized (mPackages) {
18511                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18512                if (ps == null) {
18513                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18514                            "Missing settings for moved package " + pkgName);
18515                }
18516
18517                // We moved the entire application as-is, so bring over the
18518                // previously derived ABI information.
18519                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18520                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18521            }
18522
18523        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18524            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18525            scanFlags |= SCAN_NO_DEX;
18526
18527            try {
18528                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18529                    args.abiOverride : pkg.cpuAbiOverride);
18530                final boolean extractNativeLibs = !pkg.isLibrary();
18531                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18532                        extractNativeLibs, mAppLib32InstallDir);
18533            } catch (PackageManagerException pme) {
18534                Slog.e(TAG, "Error deriving application ABI", pme);
18535                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18536                return;
18537            }
18538
18539            // Shared libraries for the package need to be updated.
18540            synchronized (mPackages) {
18541                try {
18542                    updateSharedLibrariesLPr(pkg, null);
18543                } catch (PackageManagerException e) {
18544                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18545                }
18546            }
18547
18548            // dexopt can take some time to complete, so, for instant apps, we skip this
18549            // step during installation. Instead, we'll take extra time the first time the
18550            // instant app starts. It's preferred to do it this way to provide continuous
18551            // progress to the user instead of mysteriously blocking somewhere in the
18552            // middle of running an instant app. The default behaviour can be overridden
18553            // via gservices.
18554            if (!instantApp || Global.getInt(
18555                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18556                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18557                // Do not run PackageDexOptimizer through the local performDexOpt
18558                // method because `pkg` may not be in `mPackages` yet.
18559                //
18560                // Also, don't fail application installs if the dexopt step fails.
18561                DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18562                        REASON_INSTALL,
18563                        DexoptOptions.DEXOPT_BOOT_COMPLETE);
18564                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18565                        null /* instructionSets */,
18566                        getOrCreateCompilerPackageStats(pkg),
18567                        mDexManager.isUsedByOtherApps(pkg.packageName),
18568                        dexoptOptions);
18569                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18570            }
18571
18572            // Notify BackgroundDexOptService that the package has been changed.
18573            // If this is an update of a package which used to fail to compile,
18574            // BDOS will remove it from its blacklist.
18575            // TODO: Layering violation
18576            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18577        }
18578
18579        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18580            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18581            return;
18582        }
18583
18584        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18585
18586        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18587                "installPackageLI")) {
18588            if (replace) {
18589                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18590                    // Static libs have a synthetic package name containing the version
18591                    // and cannot be updated as an update would get a new package name,
18592                    // unless this is the exact same version code which is useful for
18593                    // development.
18594                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18595                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18596                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18597                                + "static-shared libs cannot be updated");
18598                        return;
18599                    }
18600                }
18601                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18602                        installerPackageName, res, args.installReason);
18603            } else {
18604                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18605                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18606            }
18607        }
18608
18609        synchronized (mPackages) {
18610            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18611            if (ps != null) {
18612                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18613                ps.setUpdateAvailable(false /*updateAvailable*/);
18614            }
18615
18616            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18617            for (int i = 0; i < childCount; i++) {
18618                PackageParser.Package childPkg = pkg.childPackages.get(i);
18619                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18620                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18621                if (childPs != null) {
18622                    childRes.newUsers = childPs.queryInstalledUsers(
18623                            sUserManager.getUserIds(), true);
18624                }
18625            }
18626
18627            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18628                updateSequenceNumberLP(ps, res.newUsers);
18629                updateInstantAppInstallerLocked(pkgName);
18630            }
18631        }
18632    }
18633
18634    private void startIntentFilterVerifications(int userId, boolean replacing,
18635            PackageParser.Package pkg) {
18636        if (mIntentFilterVerifierComponent == null) {
18637            Slog.w(TAG, "No IntentFilter verification will not be done as "
18638                    + "there is no IntentFilterVerifier available!");
18639            return;
18640        }
18641
18642        final int verifierUid = getPackageUid(
18643                mIntentFilterVerifierComponent.getPackageName(),
18644                MATCH_DEBUG_TRIAGED_MISSING,
18645                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18646
18647        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18648        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18649        mHandler.sendMessage(msg);
18650
18651        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18652        for (int i = 0; i < childCount; i++) {
18653            PackageParser.Package childPkg = pkg.childPackages.get(i);
18654            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18655            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18656            mHandler.sendMessage(msg);
18657        }
18658    }
18659
18660    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18661            PackageParser.Package pkg) {
18662        int size = pkg.activities.size();
18663        if (size == 0) {
18664            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18665                    "No activity, so no need to verify any IntentFilter!");
18666            return;
18667        }
18668
18669        final boolean hasDomainURLs = hasDomainURLs(pkg);
18670        if (!hasDomainURLs) {
18671            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18672                    "No domain URLs, so no need to verify any IntentFilter!");
18673            return;
18674        }
18675
18676        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18677                + " if any IntentFilter from the " + size
18678                + " Activities needs verification ...");
18679
18680        int count = 0;
18681        final String packageName = pkg.packageName;
18682
18683        synchronized (mPackages) {
18684            // If this is a new install and we see that we've already run verification for this
18685            // package, we have nothing to do: it means the state was restored from backup.
18686            if (!replacing) {
18687                IntentFilterVerificationInfo ivi =
18688                        mSettings.getIntentFilterVerificationLPr(packageName);
18689                if (ivi != null) {
18690                    if (DEBUG_DOMAIN_VERIFICATION) {
18691                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18692                                + ivi.getStatusString());
18693                    }
18694                    return;
18695                }
18696            }
18697
18698            // If any filters need to be verified, then all need to be.
18699            boolean needToVerify = false;
18700            for (PackageParser.Activity a : pkg.activities) {
18701                for (ActivityIntentInfo filter : a.intents) {
18702                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18703                        if (DEBUG_DOMAIN_VERIFICATION) {
18704                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18705                        }
18706                        needToVerify = true;
18707                        break;
18708                    }
18709                }
18710            }
18711
18712            if (needToVerify) {
18713                final int verificationId = mIntentFilterVerificationToken++;
18714                for (PackageParser.Activity a : pkg.activities) {
18715                    for (ActivityIntentInfo filter : a.intents) {
18716                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18717                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18718                                    "Verification needed for IntentFilter:" + filter.toString());
18719                            mIntentFilterVerifier.addOneIntentFilterVerification(
18720                                    verifierUid, userId, verificationId, filter, packageName);
18721                            count++;
18722                        }
18723                    }
18724                }
18725            }
18726        }
18727
18728        if (count > 0) {
18729            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18730                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18731                    +  " for userId:" + userId);
18732            mIntentFilterVerifier.startVerifications(userId);
18733        } else {
18734            if (DEBUG_DOMAIN_VERIFICATION) {
18735                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18736            }
18737        }
18738    }
18739
18740    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18741        final ComponentName cn  = filter.activity.getComponentName();
18742        final String packageName = cn.getPackageName();
18743
18744        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18745                packageName);
18746        if (ivi == null) {
18747            return true;
18748        }
18749        int status = ivi.getStatus();
18750        switch (status) {
18751            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18752            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18753                return true;
18754
18755            default:
18756                // Nothing to do
18757                return false;
18758        }
18759    }
18760
18761    private static boolean isMultiArch(ApplicationInfo info) {
18762        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18763    }
18764
18765    private static boolean isExternal(PackageParser.Package pkg) {
18766        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18767    }
18768
18769    private static boolean isExternal(PackageSetting ps) {
18770        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18771    }
18772
18773    private static boolean isSystemApp(PackageParser.Package pkg) {
18774        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18775    }
18776
18777    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18778        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18779    }
18780
18781    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18782        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18783    }
18784
18785    private static boolean isSystemApp(PackageSetting ps) {
18786        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18787    }
18788
18789    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18790        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18791    }
18792
18793    private int packageFlagsToInstallFlags(PackageSetting ps) {
18794        int installFlags = 0;
18795        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18796            // This existing package was an external ASEC install when we have
18797            // the external flag without a UUID
18798            installFlags |= PackageManager.INSTALL_EXTERNAL;
18799        }
18800        if (ps.isForwardLocked()) {
18801            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18802        }
18803        return installFlags;
18804    }
18805
18806    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18807        if (isExternal(pkg)) {
18808            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18809                return StorageManager.UUID_PRIMARY_PHYSICAL;
18810            } else {
18811                return pkg.volumeUuid;
18812            }
18813        } else {
18814            return StorageManager.UUID_PRIVATE_INTERNAL;
18815        }
18816    }
18817
18818    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18819        if (isExternal(pkg)) {
18820            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18821                return mSettings.getExternalVersion();
18822            } else {
18823                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18824            }
18825        } else {
18826            return mSettings.getInternalVersion();
18827        }
18828    }
18829
18830    private void deleteTempPackageFiles() {
18831        final FilenameFilter filter = new FilenameFilter() {
18832            public boolean accept(File dir, String name) {
18833                return name.startsWith("vmdl") && name.endsWith(".tmp");
18834            }
18835        };
18836        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18837            file.delete();
18838        }
18839    }
18840
18841    @Override
18842    public void deletePackageAsUser(String packageName, int versionCode,
18843            IPackageDeleteObserver observer, int userId, int flags) {
18844        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18845                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18846    }
18847
18848    @Override
18849    public void deletePackageVersioned(VersionedPackage versionedPackage,
18850            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18851        final int callingUid = Binder.getCallingUid();
18852        mContext.enforceCallingOrSelfPermission(
18853                android.Manifest.permission.DELETE_PACKAGES, null);
18854        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18855        Preconditions.checkNotNull(versionedPackage);
18856        Preconditions.checkNotNull(observer);
18857        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18858                PackageManager.VERSION_CODE_HIGHEST,
18859                Integer.MAX_VALUE, "versionCode must be >= -1");
18860
18861        final String packageName = versionedPackage.getPackageName();
18862        final int versionCode = versionedPackage.getVersionCode();
18863        final String internalPackageName;
18864        synchronized (mPackages) {
18865            // Normalize package name to handle renamed packages and static libs
18866            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18867                    versionedPackage.getVersionCode());
18868        }
18869
18870        final int uid = Binder.getCallingUid();
18871        if (!isOrphaned(internalPackageName)
18872                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18873            try {
18874                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18875                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18876                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18877                observer.onUserActionRequired(intent);
18878            } catch (RemoteException re) {
18879            }
18880            return;
18881        }
18882        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18883        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18884        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18885            mContext.enforceCallingOrSelfPermission(
18886                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18887                    "deletePackage for user " + userId);
18888        }
18889
18890        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18891            try {
18892                observer.onPackageDeleted(packageName,
18893                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18894            } catch (RemoteException re) {
18895            }
18896            return;
18897        }
18898
18899        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18900            try {
18901                observer.onPackageDeleted(packageName,
18902                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18903            } catch (RemoteException re) {
18904            }
18905            return;
18906        }
18907
18908        if (DEBUG_REMOVE) {
18909            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18910                    + " deleteAllUsers: " + deleteAllUsers + " version="
18911                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18912                    ? "VERSION_CODE_HIGHEST" : versionCode));
18913        }
18914        // Queue up an async operation since the package deletion may take a little while.
18915        mHandler.post(new Runnable() {
18916            public void run() {
18917                mHandler.removeCallbacks(this);
18918                int returnCode;
18919                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18920                boolean doDeletePackage = true;
18921                if (ps != null) {
18922                    final boolean targetIsInstantApp =
18923                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18924                    doDeletePackage = !targetIsInstantApp
18925                            || canViewInstantApps;
18926                }
18927                if (doDeletePackage) {
18928                    if (!deleteAllUsers) {
18929                        returnCode = deletePackageX(internalPackageName, versionCode,
18930                                userId, deleteFlags);
18931                    } else {
18932                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18933                                internalPackageName, users);
18934                        // If nobody is blocking uninstall, proceed with delete for all users
18935                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18936                            returnCode = deletePackageX(internalPackageName, versionCode,
18937                                    userId, deleteFlags);
18938                        } else {
18939                            // Otherwise uninstall individually for users with blockUninstalls=false
18940                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18941                            for (int userId : users) {
18942                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18943                                    returnCode = deletePackageX(internalPackageName, versionCode,
18944                                            userId, userFlags);
18945                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18946                                        Slog.w(TAG, "Package delete failed for user " + userId
18947                                                + ", returnCode " + returnCode);
18948                                    }
18949                                }
18950                            }
18951                            // The app has only been marked uninstalled for certain users.
18952                            // We still need to report that delete was blocked
18953                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18954                        }
18955                    }
18956                } else {
18957                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18958                }
18959                try {
18960                    observer.onPackageDeleted(packageName, returnCode, null);
18961                } catch (RemoteException e) {
18962                    Log.i(TAG, "Observer no longer exists.");
18963                } //end catch
18964            } //end run
18965        });
18966    }
18967
18968    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18969        if (pkg.staticSharedLibName != null) {
18970            return pkg.manifestPackageName;
18971        }
18972        return pkg.packageName;
18973    }
18974
18975    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18976        // Handle renamed packages
18977        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18978        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18979
18980        // Is this a static library?
18981        SparseArray<SharedLibraryEntry> versionedLib =
18982                mStaticLibsByDeclaringPackage.get(packageName);
18983        if (versionedLib == null || versionedLib.size() <= 0) {
18984            return packageName;
18985        }
18986
18987        // Figure out which lib versions the caller can see
18988        SparseIntArray versionsCallerCanSee = null;
18989        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18990        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18991                && callingAppId != Process.ROOT_UID) {
18992            versionsCallerCanSee = new SparseIntArray();
18993            String libName = versionedLib.valueAt(0).info.getName();
18994            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18995            if (uidPackages != null) {
18996                for (String uidPackage : uidPackages) {
18997                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18998                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18999                    if (libIdx >= 0) {
19000                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19001                        versionsCallerCanSee.append(libVersion, libVersion);
19002                    }
19003                }
19004            }
19005        }
19006
19007        // Caller can see nothing - done
19008        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19009            return packageName;
19010        }
19011
19012        // Find the version the caller can see and the app version code
19013        SharedLibraryEntry highestVersion = null;
19014        final int versionCount = versionedLib.size();
19015        for (int i = 0; i < versionCount; i++) {
19016            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19017            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19018                    libEntry.info.getVersion()) < 0) {
19019                continue;
19020            }
19021            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19022            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19023                if (libVersionCode == versionCode) {
19024                    return libEntry.apk;
19025                }
19026            } else if (highestVersion == null) {
19027                highestVersion = libEntry;
19028            } else if (libVersionCode  > highestVersion.info
19029                    .getDeclaringPackage().getVersionCode()) {
19030                highestVersion = libEntry;
19031            }
19032        }
19033
19034        if (highestVersion != null) {
19035            return highestVersion.apk;
19036        }
19037
19038        return packageName;
19039    }
19040
19041    boolean isCallerVerifier(int callingUid) {
19042        final int callingUserId = UserHandle.getUserId(callingUid);
19043        return mRequiredVerifierPackage != null &&
19044                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19045    }
19046
19047    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19048        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19049              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19050            return true;
19051        }
19052        final int callingUserId = UserHandle.getUserId(callingUid);
19053        // If the caller installed the pkgName, then allow it to silently uninstall.
19054        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19055            return true;
19056        }
19057
19058        // Allow package verifier to silently uninstall.
19059        if (mRequiredVerifierPackage != null &&
19060                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19061            return true;
19062        }
19063
19064        // Allow package uninstaller to silently uninstall.
19065        if (mRequiredUninstallerPackage != null &&
19066                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19067            return true;
19068        }
19069
19070        // Allow storage manager to silently uninstall.
19071        if (mStorageManagerPackage != null &&
19072                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19073            return true;
19074        }
19075
19076        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19077        // uninstall for device owner provisioning.
19078        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19079                == PERMISSION_GRANTED) {
19080            return true;
19081        }
19082
19083        return false;
19084    }
19085
19086    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19087        int[] result = EMPTY_INT_ARRAY;
19088        for (int userId : userIds) {
19089            if (getBlockUninstallForUser(packageName, userId)) {
19090                result = ArrayUtils.appendInt(result, userId);
19091            }
19092        }
19093        return result;
19094    }
19095
19096    @Override
19097    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19098        final int callingUid = Binder.getCallingUid();
19099        if (getInstantAppPackageName(callingUid) != null
19100                && !isCallerSameApp(packageName, callingUid)) {
19101            return false;
19102        }
19103        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19104    }
19105
19106    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19107        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19108                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19109        try {
19110            if (dpm != null) {
19111                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19112                        /* callingUserOnly =*/ false);
19113                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19114                        : deviceOwnerComponentName.getPackageName();
19115                // Does the package contains the device owner?
19116                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19117                // this check is probably not needed, since DO should be registered as a device
19118                // admin on some user too. (Original bug for this: b/17657954)
19119                if (packageName.equals(deviceOwnerPackageName)) {
19120                    return true;
19121                }
19122                // Does it contain a device admin for any user?
19123                int[] users;
19124                if (userId == UserHandle.USER_ALL) {
19125                    users = sUserManager.getUserIds();
19126                } else {
19127                    users = new int[]{userId};
19128                }
19129                for (int i = 0; i < users.length; ++i) {
19130                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19131                        return true;
19132                    }
19133                }
19134            }
19135        } catch (RemoteException e) {
19136        }
19137        return false;
19138    }
19139
19140    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19141        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19142    }
19143
19144    /**
19145     *  This method is an internal method that could be get invoked either
19146     *  to delete an installed package or to clean up a failed installation.
19147     *  After deleting an installed package, a broadcast is sent to notify any
19148     *  listeners that the package has been removed. For cleaning up a failed
19149     *  installation, the broadcast is not necessary since the package's
19150     *  installation wouldn't have sent the initial broadcast either
19151     *  The key steps in deleting a package are
19152     *  deleting the package information in internal structures like mPackages,
19153     *  deleting the packages base directories through installd
19154     *  updating mSettings to reflect current status
19155     *  persisting settings for later use
19156     *  sending a broadcast if necessary
19157     */
19158    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19159        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19160        final boolean res;
19161
19162        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19163                ? UserHandle.USER_ALL : userId;
19164
19165        if (isPackageDeviceAdmin(packageName, removeUser)) {
19166            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19167            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19168        }
19169
19170        PackageSetting uninstalledPs = null;
19171        PackageParser.Package pkg = null;
19172
19173        // for the uninstall-updates case and restricted profiles, remember the per-
19174        // user handle installed state
19175        int[] allUsers;
19176        synchronized (mPackages) {
19177            uninstalledPs = mSettings.mPackages.get(packageName);
19178            if (uninstalledPs == null) {
19179                Slog.w(TAG, "Not removing non-existent package " + packageName);
19180                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19181            }
19182
19183            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19184                    && uninstalledPs.versionCode != versionCode) {
19185                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19186                        + uninstalledPs.versionCode + " != " + versionCode);
19187                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19188            }
19189
19190            // Static shared libs can be declared by any package, so let us not
19191            // allow removing a package if it provides a lib others depend on.
19192            pkg = mPackages.get(packageName);
19193
19194            allUsers = sUserManager.getUserIds();
19195
19196            if (pkg != null && pkg.staticSharedLibName != null) {
19197                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19198                        pkg.staticSharedLibVersion);
19199                if (libEntry != null) {
19200                    for (int currUserId : allUsers) {
19201                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19202                            continue;
19203                        }
19204                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19205                                libEntry.info, 0, currUserId);
19206                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19207                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19208                                    + " hosting lib " + libEntry.info.getName() + " version "
19209                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19210                                    + " for user " + currUserId);
19211                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19212                        }
19213                    }
19214                }
19215            }
19216
19217            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19218        }
19219
19220        final int freezeUser;
19221        if (isUpdatedSystemApp(uninstalledPs)
19222                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19223            // We're downgrading a system app, which will apply to all users, so
19224            // freeze them all during the downgrade
19225            freezeUser = UserHandle.USER_ALL;
19226        } else {
19227            freezeUser = removeUser;
19228        }
19229
19230        synchronized (mInstallLock) {
19231            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19232            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19233                    deleteFlags, "deletePackageX")) {
19234                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19235                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19236            }
19237            synchronized (mPackages) {
19238                if (res) {
19239                    if (pkg != null) {
19240                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19241                    }
19242                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19243                    updateInstantAppInstallerLocked(packageName);
19244                }
19245            }
19246        }
19247
19248        if (res) {
19249            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19250            info.sendPackageRemovedBroadcasts(killApp);
19251            info.sendSystemPackageUpdatedBroadcasts();
19252            info.sendSystemPackageAppearedBroadcasts();
19253        }
19254        // Force a gc here.
19255        Runtime.getRuntime().gc();
19256        // Delete the resources here after sending the broadcast to let
19257        // other processes clean up before deleting resources.
19258        if (info.args != null) {
19259            synchronized (mInstallLock) {
19260                info.args.doPostDeleteLI(true);
19261            }
19262        }
19263
19264        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19265    }
19266
19267    static class PackageRemovedInfo {
19268        final PackageSender packageSender;
19269        String removedPackage;
19270        String installerPackageName;
19271        int uid = -1;
19272        int removedAppId = -1;
19273        int[] origUsers;
19274        int[] removedUsers = null;
19275        int[] broadcastUsers = null;
19276        SparseArray<Integer> installReasons;
19277        boolean isRemovedPackageSystemUpdate = false;
19278        boolean isUpdate;
19279        boolean dataRemoved;
19280        boolean removedForAllUsers;
19281        boolean isStaticSharedLib;
19282        // Clean up resources deleted packages.
19283        InstallArgs args = null;
19284        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19285        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19286
19287        PackageRemovedInfo(PackageSender packageSender) {
19288            this.packageSender = packageSender;
19289        }
19290
19291        void sendPackageRemovedBroadcasts(boolean killApp) {
19292            sendPackageRemovedBroadcastInternal(killApp);
19293            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19294            for (int i = 0; i < childCount; i++) {
19295                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19296                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19297            }
19298        }
19299
19300        void sendSystemPackageUpdatedBroadcasts() {
19301            if (isRemovedPackageSystemUpdate) {
19302                sendSystemPackageUpdatedBroadcastsInternal();
19303                final int childCount = (removedChildPackages != null)
19304                        ? removedChildPackages.size() : 0;
19305                for (int i = 0; i < childCount; i++) {
19306                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19307                    if (childInfo.isRemovedPackageSystemUpdate) {
19308                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19309                    }
19310                }
19311            }
19312        }
19313
19314        void sendSystemPackageAppearedBroadcasts() {
19315            final int packageCount = (appearedChildPackages != null)
19316                    ? appearedChildPackages.size() : 0;
19317            for (int i = 0; i < packageCount; i++) {
19318                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19319                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19320                    true /*sendBootCompleted*/, false /*startReceiver*/,
19321                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19322            }
19323        }
19324
19325        private void sendSystemPackageUpdatedBroadcastsInternal() {
19326            Bundle extras = new Bundle(2);
19327            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19328            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19329            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19330                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19331            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19332                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19333            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19334                null, null, 0, removedPackage, null, null);
19335            if (installerPackageName != null) {
19336                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19337                        removedPackage, extras, 0 /*flags*/,
19338                        installerPackageName, null, null);
19339                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19340                        removedPackage, extras, 0 /*flags*/,
19341                        installerPackageName, null, null);
19342            }
19343        }
19344
19345        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19346            // Don't send static shared library removal broadcasts as these
19347            // libs are visible only the the apps that depend on them an one
19348            // cannot remove the library if it has a dependency.
19349            if (isStaticSharedLib) {
19350                return;
19351            }
19352            Bundle extras = new Bundle(2);
19353            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19354            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19355            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19356            if (isUpdate || isRemovedPackageSystemUpdate) {
19357                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19358            }
19359            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19360            if (removedPackage != null) {
19361                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19362                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19363                if (installerPackageName != null) {
19364                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19365                            removedPackage, extras, 0 /*flags*/,
19366                            installerPackageName, null, broadcastUsers);
19367                }
19368                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19369                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19370                        removedPackage, extras,
19371                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19372                        null, null, broadcastUsers);
19373                }
19374            }
19375            if (removedAppId >= 0) {
19376                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19377                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19378                    null, null, broadcastUsers);
19379            }
19380        }
19381
19382        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19383            removedUsers = userIds;
19384            if (removedUsers == null) {
19385                broadcastUsers = null;
19386                return;
19387            }
19388
19389            broadcastUsers = EMPTY_INT_ARRAY;
19390            for (int i = userIds.length - 1; i >= 0; --i) {
19391                final int userId = userIds[i];
19392                if (deletedPackageSetting.getInstantApp(userId)) {
19393                    continue;
19394                }
19395                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19396            }
19397        }
19398    }
19399
19400    /*
19401     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19402     * flag is not set, the data directory is removed as well.
19403     * make sure this flag is set for partially installed apps. If not its meaningless to
19404     * delete a partially installed application.
19405     */
19406    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19407            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19408        String packageName = ps.name;
19409        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19410        // Retrieve object to delete permissions for shared user later on
19411        final PackageParser.Package deletedPkg;
19412        final PackageSetting deletedPs;
19413        // reader
19414        synchronized (mPackages) {
19415            deletedPkg = mPackages.get(packageName);
19416            deletedPs = mSettings.mPackages.get(packageName);
19417            if (outInfo != null) {
19418                outInfo.removedPackage = packageName;
19419                outInfo.installerPackageName = ps.installerPackageName;
19420                outInfo.isStaticSharedLib = deletedPkg != null
19421                        && deletedPkg.staticSharedLibName != null;
19422                outInfo.populateUsers(deletedPs == null ? null
19423                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19424            }
19425        }
19426
19427        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19428
19429        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19430            final PackageParser.Package resolvedPkg;
19431            if (deletedPkg != null) {
19432                resolvedPkg = deletedPkg;
19433            } else {
19434                // We don't have a parsed package when it lives on an ejected
19435                // adopted storage device, so fake something together
19436                resolvedPkg = new PackageParser.Package(ps.name);
19437                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19438            }
19439            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19440                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19441            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19442            if (outInfo != null) {
19443                outInfo.dataRemoved = true;
19444            }
19445            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19446        }
19447
19448        int removedAppId = -1;
19449
19450        // writer
19451        synchronized (mPackages) {
19452            boolean installedStateChanged = false;
19453            if (deletedPs != null) {
19454                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19455                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19456                    clearDefaultBrowserIfNeeded(packageName);
19457                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19458                    removedAppId = mSettings.removePackageLPw(packageName);
19459                    if (outInfo != null) {
19460                        outInfo.removedAppId = removedAppId;
19461                    }
19462                    updatePermissionsLPw(deletedPs.name, null, 0);
19463                    if (deletedPs.sharedUser != null) {
19464                        // Remove permissions associated with package. Since runtime
19465                        // permissions are per user we have to kill the removed package
19466                        // or packages running under the shared user of the removed
19467                        // package if revoking the permissions requested only by the removed
19468                        // package is successful and this causes a change in gids.
19469                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19470                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19471                                    userId);
19472                            if (userIdToKill == UserHandle.USER_ALL
19473                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19474                                // If gids changed for this user, kill all affected packages.
19475                                mHandler.post(new Runnable() {
19476                                    @Override
19477                                    public void run() {
19478                                        // This has to happen with no lock held.
19479                                        killApplication(deletedPs.name, deletedPs.appId,
19480                                                KILL_APP_REASON_GIDS_CHANGED);
19481                                    }
19482                                });
19483                                break;
19484                            }
19485                        }
19486                    }
19487                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19488                }
19489                // make sure to preserve per-user disabled state if this removal was just
19490                // a downgrade of a system app to the factory package
19491                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19492                    if (DEBUG_REMOVE) {
19493                        Slog.d(TAG, "Propagating install state across downgrade");
19494                    }
19495                    for (int userId : allUserHandles) {
19496                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19497                        if (DEBUG_REMOVE) {
19498                            Slog.d(TAG, "    user " + userId + " => " + installed);
19499                        }
19500                        if (installed != ps.getInstalled(userId)) {
19501                            installedStateChanged = true;
19502                        }
19503                        ps.setInstalled(installed, userId);
19504                    }
19505                }
19506            }
19507            // can downgrade to reader
19508            if (writeSettings) {
19509                // Save settings now
19510                mSettings.writeLPr();
19511            }
19512            if (installedStateChanged) {
19513                mSettings.writeKernelMappingLPr(ps);
19514            }
19515        }
19516        if (removedAppId != -1) {
19517            // A user ID was deleted here. Go through all users and remove it
19518            // from KeyStore.
19519            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19520        }
19521    }
19522
19523    static boolean locationIsPrivileged(File path) {
19524        try {
19525            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19526                    .getCanonicalPath();
19527            return path.getCanonicalPath().startsWith(privilegedAppDir);
19528        } catch (IOException e) {
19529            Slog.e(TAG, "Unable to access code path " + path);
19530        }
19531        return false;
19532    }
19533
19534    /*
19535     * Tries to delete system package.
19536     */
19537    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19538            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19539            boolean writeSettings) {
19540        if (deletedPs.parentPackageName != null) {
19541            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19542            return false;
19543        }
19544
19545        final boolean applyUserRestrictions
19546                = (allUserHandles != null) && (outInfo.origUsers != null);
19547        final PackageSetting disabledPs;
19548        // Confirm if the system package has been updated
19549        // An updated system app can be deleted. This will also have to restore
19550        // the system pkg from system partition
19551        // reader
19552        synchronized (mPackages) {
19553            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19554        }
19555
19556        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19557                + " disabledPs=" + disabledPs);
19558
19559        if (disabledPs == null) {
19560            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19561            return false;
19562        } else if (DEBUG_REMOVE) {
19563            Slog.d(TAG, "Deleting system pkg from data partition");
19564        }
19565
19566        if (DEBUG_REMOVE) {
19567            if (applyUserRestrictions) {
19568                Slog.d(TAG, "Remembering install states:");
19569                for (int userId : allUserHandles) {
19570                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19571                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19572                }
19573            }
19574        }
19575
19576        // Delete the updated package
19577        outInfo.isRemovedPackageSystemUpdate = true;
19578        if (outInfo.removedChildPackages != null) {
19579            final int childCount = (deletedPs.childPackageNames != null)
19580                    ? deletedPs.childPackageNames.size() : 0;
19581            for (int i = 0; i < childCount; i++) {
19582                String childPackageName = deletedPs.childPackageNames.get(i);
19583                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19584                        .contains(childPackageName)) {
19585                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19586                            childPackageName);
19587                    if (childInfo != null) {
19588                        childInfo.isRemovedPackageSystemUpdate = true;
19589                    }
19590                }
19591            }
19592        }
19593
19594        if (disabledPs.versionCode < deletedPs.versionCode) {
19595            // Delete data for downgrades
19596            flags &= ~PackageManager.DELETE_KEEP_DATA;
19597        } else {
19598            // Preserve data by setting flag
19599            flags |= PackageManager.DELETE_KEEP_DATA;
19600        }
19601
19602        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19603                outInfo, writeSettings, disabledPs.pkg);
19604        if (!ret) {
19605            return false;
19606        }
19607
19608        // writer
19609        synchronized (mPackages) {
19610            // Reinstate the old system package
19611            enableSystemPackageLPw(disabledPs.pkg);
19612            // Remove any native libraries from the upgraded package.
19613            removeNativeBinariesLI(deletedPs);
19614        }
19615
19616        // Install the system package
19617        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19618        int parseFlags = mDefParseFlags
19619                | PackageParser.PARSE_MUST_BE_APK
19620                | PackageParser.PARSE_IS_SYSTEM
19621                | PackageParser.PARSE_IS_SYSTEM_DIR;
19622        if (locationIsPrivileged(disabledPs.codePath)) {
19623            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19624        }
19625
19626        final PackageParser.Package newPkg;
19627        try {
19628            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19629                0 /* currentTime */, null);
19630        } catch (PackageManagerException e) {
19631            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19632                    + e.getMessage());
19633            return false;
19634        }
19635
19636        try {
19637            // update shared libraries for the newly re-installed system package
19638            updateSharedLibrariesLPr(newPkg, null);
19639        } catch (PackageManagerException e) {
19640            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19641        }
19642
19643        prepareAppDataAfterInstallLIF(newPkg);
19644
19645        // writer
19646        synchronized (mPackages) {
19647            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19648
19649            // Propagate the permissions state as we do not want to drop on the floor
19650            // runtime permissions. The update permissions method below will take
19651            // care of removing obsolete permissions and grant install permissions.
19652            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19653            updatePermissionsLPw(newPkg.packageName, newPkg,
19654                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19655
19656            if (applyUserRestrictions) {
19657                boolean installedStateChanged = false;
19658                if (DEBUG_REMOVE) {
19659                    Slog.d(TAG, "Propagating install state across reinstall");
19660                }
19661                for (int userId : allUserHandles) {
19662                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19663                    if (DEBUG_REMOVE) {
19664                        Slog.d(TAG, "    user " + userId + " => " + installed);
19665                    }
19666                    if (installed != ps.getInstalled(userId)) {
19667                        installedStateChanged = true;
19668                    }
19669                    ps.setInstalled(installed, userId);
19670
19671                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19672                }
19673                // Regardless of writeSettings we need to ensure that this restriction
19674                // state propagation is persisted
19675                mSettings.writeAllUsersPackageRestrictionsLPr();
19676                if (installedStateChanged) {
19677                    mSettings.writeKernelMappingLPr(ps);
19678                }
19679            }
19680            // can downgrade to reader here
19681            if (writeSettings) {
19682                mSettings.writeLPr();
19683            }
19684        }
19685        return true;
19686    }
19687
19688    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19689            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19690            PackageRemovedInfo outInfo, boolean writeSettings,
19691            PackageParser.Package replacingPackage) {
19692        synchronized (mPackages) {
19693            if (outInfo != null) {
19694                outInfo.uid = ps.appId;
19695            }
19696
19697            if (outInfo != null && outInfo.removedChildPackages != null) {
19698                final int childCount = (ps.childPackageNames != null)
19699                        ? ps.childPackageNames.size() : 0;
19700                for (int i = 0; i < childCount; i++) {
19701                    String childPackageName = ps.childPackageNames.get(i);
19702                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19703                    if (childPs == null) {
19704                        return false;
19705                    }
19706                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19707                            childPackageName);
19708                    if (childInfo != null) {
19709                        childInfo.uid = childPs.appId;
19710                    }
19711                }
19712            }
19713        }
19714
19715        // Delete package data from internal structures and also remove data if flag is set
19716        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19717
19718        // Delete the child packages data
19719        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19720        for (int i = 0; i < childCount; i++) {
19721            PackageSetting childPs;
19722            synchronized (mPackages) {
19723                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19724            }
19725            if (childPs != null) {
19726                PackageRemovedInfo childOutInfo = (outInfo != null
19727                        && outInfo.removedChildPackages != null)
19728                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19729                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19730                        && (replacingPackage != null
19731                        && !replacingPackage.hasChildPackage(childPs.name))
19732                        ? flags & ~DELETE_KEEP_DATA : flags;
19733                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19734                        deleteFlags, writeSettings);
19735            }
19736        }
19737
19738        // Delete application code and resources only for parent packages
19739        if (ps.parentPackageName == null) {
19740            if (deleteCodeAndResources && (outInfo != null)) {
19741                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19742                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19743                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19744            }
19745        }
19746
19747        return true;
19748    }
19749
19750    @Override
19751    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19752            int userId) {
19753        mContext.enforceCallingOrSelfPermission(
19754                android.Manifest.permission.DELETE_PACKAGES, null);
19755        synchronized (mPackages) {
19756            // Cannot block uninstall of static shared libs as they are
19757            // considered a part of the using app (emulating static linking).
19758            // Also static libs are installed always on internal storage.
19759            PackageParser.Package pkg = mPackages.get(packageName);
19760            if (pkg != null && pkg.staticSharedLibName != null) {
19761                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19762                        + " providing static shared library: " + pkg.staticSharedLibName);
19763                return false;
19764            }
19765            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19766            mSettings.writePackageRestrictionsLPr(userId);
19767        }
19768        return true;
19769    }
19770
19771    @Override
19772    public boolean getBlockUninstallForUser(String packageName, int userId) {
19773        synchronized (mPackages) {
19774            final PackageSetting ps = mSettings.mPackages.get(packageName);
19775            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19776                return false;
19777            }
19778            return mSettings.getBlockUninstallLPr(userId, packageName);
19779        }
19780    }
19781
19782    @Override
19783    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19784        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19785        synchronized (mPackages) {
19786            PackageSetting ps = mSettings.mPackages.get(packageName);
19787            if (ps == null) {
19788                Log.w(TAG, "Package doesn't exist: " + packageName);
19789                return false;
19790            }
19791            if (systemUserApp) {
19792                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19793            } else {
19794                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19795            }
19796            mSettings.writeLPr();
19797        }
19798        return true;
19799    }
19800
19801    /*
19802     * This method handles package deletion in general
19803     */
19804    private boolean deletePackageLIF(String packageName, UserHandle user,
19805            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19806            PackageRemovedInfo outInfo, boolean writeSettings,
19807            PackageParser.Package replacingPackage) {
19808        if (packageName == null) {
19809            Slog.w(TAG, "Attempt to delete null packageName.");
19810            return false;
19811        }
19812
19813        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19814
19815        PackageSetting ps;
19816        synchronized (mPackages) {
19817            ps = mSettings.mPackages.get(packageName);
19818            if (ps == null) {
19819                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19820                return false;
19821            }
19822
19823            if (ps.parentPackageName != null && (!isSystemApp(ps)
19824                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19825                if (DEBUG_REMOVE) {
19826                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19827                            + ((user == null) ? UserHandle.USER_ALL : user));
19828                }
19829                final int removedUserId = (user != null) ? user.getIdentifier()
19830                        : UserHandle.USER_ALL;
19831                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19832                    return false;
19833                }
19834                markPackageUninstalledForUserLPw(ps, user);
19835                scheduleWritePackageRestrictionsLocked(user);
19836                return true;
19837            }
19838        }
19839
19840        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19841                && user.getIdentifier() != UserHandle.USER_ALL)) {
19842            // The caller is asking that the package only be deleted for a single
19843            // user.  To do this, we just mark its uninstalled state and delete
19844            // its data. If this is a system app, we only allow this to happen if
19845            // they have set the special DELETE_SYSTEM_APP which requests different
19846            // semantics than normal for uninstalling system apps.
19847            markPackageUninstalledForUserLPw(ps, user);
19848
19849            if (!isSystemApp(ps)) {
19850                // Do not uninstall the APK if an app should be cached
19851                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19852                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19853                    // Other user still have this package installed, so all
19854                    // we need to do is clear this user's data and save that
19855                    // it is uninstalled.
19856                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19857                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19858                        return false;
19859                    }
19860                    scheduleWritePackageRestrictionsLocked(user);
19861                    return true;
19862                } else {
19863                    // We need to set it back to 'installed' so the uninstall
19864                    // broadcasts will be sent correctly.
19865                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19866                    ps.setInstalled(true, user.getIdentifier());
19867                    mSettings.writeKernelMappingLPr(ps);
19868                }
19869            } else {
19870                // This is a system app, so we assume that the
19871                // other users still have this package installed, so all
19872                // we need to do is clear this user's data and save that
19873                // it is uninstalled.
19874                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19875                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19876                    return false;
19877                }
19878                scheduleWritePackageRestrictionsLocked(user);
19879                return true;
19880            }
19881        }
19882
19883        // If we are deleting a composite package for all users, keep track
19884        // of result for each child.
19885        if (ps.childPackageNames != null && outInfo != null) {
19886            synchronized (mPackages) {
19887                final int childCount = ps.childPackageNames.size();
19888                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19889                for (int i = 0; i < childCount; i++) {
19890                    String childPackageName = ps.childPackageNames.get(i);
19891                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19892                    childInfo.removedPackage = childPackageName;
19893                    childInfo.installerPackageName = ps.installerPackageName;
19894                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19895                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19896                    if (childPs != null) {
19897                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19898                    }
19899                }
19900            }
19901        }
19902
19903        boolean ret = false;
19904        if (isSystemApp(ps)) {
19905            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19906            // When an updated system application is deleted we delete the existing resources
19907            // as well and fall back to existing code in system partition
19908            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19909        } else {
19910            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19911            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19912                    outInfo, writeSettings, replacingPackage);
19913        }
19914
19915        // Take a note whether we deleted the package for all users
19916        if (outInfo != null) {
19917            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19918            if (outInfo.removedChildPackages != null) {
19919                synchronized (mPackages) {
19920                    final int childCount = outInfo.removedChildPackages.size();
19921                    for (int i = 0; i < childCount; i++) {
19922                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19923                        if (childInfo != null) {
19924                            childInfo.removedForAllUsers = mPackages.get(
19925                                    childInfo.removedPackage) == null;
19926                        }
19927                    }
19928                }
19929            }
19930            // If we uninstalled an update to a system app there may be some
19931            // child packages that appeared as they are declared in the system
19932            // app but were not declared in the update.
19933            if (isSystemApp(ps)) {
19934                synchronized (mPackages) {
19935                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19936                    final int childCount = (updatedPs.childPackageNames != null)
19937                            ? updatedPs.childPackageNames.size() : 0;
19938                    for (int i = 0; i < childCount; i++) {
19939                        String childPackageName = updatedPs.childPackageNames.get(i);
19940                        if (outInfo.removedChildPackages == null
19941                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19942                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19943                            if (childPs == null) {
19944                                continue;
19945                            }
19946                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19947                            installRes.name = childPackageName;
19948                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19949                            installRes.pkg = mPackages.get(childPackageName);
19950                            installRes.uid = childPs.pkg.applicationInfo.uid;
19951                            if (outInfo.appearedChildPackages == null) {
19952                                outInfo.appearedChildPackages = new ArrayMap<>();
19953                            }
19954                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19955                        }
19956                    }
19957                }
19958            }
19959        }
19960
19961        return ret;
19962    }
19963
19964    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19965        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19966                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19967        for (int nextUserId : userIds) {
19968            if (DEBUG_REMOVE) {
19969                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19970            }
19971            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19972                    false /*installed*/,
19973                    true /*stopped*/,
19974                    true /*notLaunched*/,
19975                    false /*hidden*/,
19976                    false /*suspended*/,
19977                    false /*instantApp*/,
19978                    null /*lastDisableAppCaller*/,
19979                    null /*enabledComponents*/,
19980                    null /*disabledComponents*/,
19981                    ps.readUserState(nextUserId).domainVerificationStatus,
19982                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19983        }
19984        mSettings.writeKernelMappingLPr(ps);
19985    }
19986
19987    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19988            PackageRemovedInfo outInfo) {
19989        final PackageParser.Package pkg;
19990        synchronized (mPackages) {
19991            pkg = mPackages.get(ps.name);
19992        }
19993
19994        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19995                : new int[] {userId};
19996        for (int nextUserId : userIds) {
19997            if (DEBUG_REMOVE) {
19998                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19999                        + nextUserId);
20000            }
20001
20002            destroyAppDataLIF(pkg, userId,
20003                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20004            destroyAppProfilesLIF(pkg, userId);
20005            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20006            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20007            schedulePackageCleaning(ps.name, nextUserId, false);
20008            synchronized (mPackages) {
20009                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20010                    scheduleWritePackageRestrictionsLocked(nextUserId);
20011                }
20012                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20013            }
20014        }
20015
20016        if (outInfo != null) {
20017            outInfo.removedPackage = ps.name;
20018            outInfo.installerPackageName = ps.installerPackageName;
20019            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20020            outInfo.removedAppId = ps.appId;
20021            outInfo.removedUsers = userIds;
20022            outInfo.broadcastUsers = userIds;
20023        }
20024
20025        return true;
20026    }
20027
20028    private final class ClearStorageConnection implements ServiceConnection {
20029        IMediaContainerService mContainerService;
20030
20031        @Override
20032        public void onServiceConnected(ComponentName name, IBinder service) {
20033            synchronized (this) {
20034                mContainerService = IMediaContainerService.Stub
20035                        .asInterface(Binder.allowBlocking(service));
20036                notifyAll();
20037            }
20038        }
20039
20040        @Override
20041        public void onServiceDisconnected(ComponentName name) {
20042        }
20043    }
20044
20045    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20046        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20047
20048        final boolean mounted;
20049        if (Environment.isExternalStorageEmulated()) {
20050            mounted = true;
20051        } else {
20052            final String status = Environment.getExternalStorageState();
20053
20054            mounted = status.equals(Environment.MEDIA_MOUNTED)
20055                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20056        }
20057
20058        if (!mounted) {
20059            return;
20060        }
20061
20062        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20063        int[] users;
20064        if (userId == UserHandle.USER_ALL) {
20065            users = sUserManager.getUserIds();
20066        } else {
20067            users = new int[] { userId };
20068        }
20069        final ClearStorageConnection conn = new ClearStorageConnection();
20070        if (mContext.bindServiceAsUser(
20071                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20072            try {
20073                for (int curUser : users) {
20074                    long timeout = SystemClock.uptimeMillis() + 5000;
20075                    synchronized (conn) {
20076                        long now;
20077                        while (conn.mContainerService == null &&
20078                                (now = SystemClock.uptimeMillis()) < timeout) {
20079                            try {
20080                                conn.wait(timeout - now);
20081                            } catch (InterruptedException e) {
20082                            }
20083                        }
20084                    }
20085                    if (conn.mContainerService == null) {
20086                        return;
20087                    }
20088
20089                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20090                    clearDirectory(conn.mContainerService,
20091                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20092                    if (allData) {
20093                        clearDirectory(conn.mContainerService,
20094                                userEnv.buildExternalStorageAppDataDirs(packageName));
20095                        clearDirectory(conn.mContainerService,
20096                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20097                    }
20098                }
20099            } finally {
20100                mContext.unbindService(conn);
20101            }
20102        }
20103    }
20104
20105    @Override
20106    public void clearApplicationProfileData(String packageName) {
20107        enforceSystemOrRoot("Only the system can clear all profile data");
20108
20109        final PackageParser.Package pkg;
20110        synchronized (mPackages) {
20111            pkg = mPackages.get(packageName);
20112        }
20113
20114        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20115            synchronized (mInstallLock) {
20116                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20117            }
20118        }
20119    }
20120
20121    @Override
20122    public void clearApplicationUserData(final String packageName,
20123            final IPackageDataObserver observer, final int userId) {
20124        mContext.enforceCallingOrSelfPermission(
20125                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20126
20127        final int callingUid = Binder.getCallingUid();
20128        enforceCrossUserPermission(callingUid, userId,
20129                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20130
20131        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20132        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
20133            return;
20134        }
20135        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20136            throw new SecurityException("Cannot clear data for a protected package: "
20137                    + packageName);
20138        }
20139        // Queue up an async operation since the package deletion may take a little while.
20140        mHandler.post(new Runnable() {
20141            public void run() {
20142                mHandler.removeCallbacks(this);
20143                final boolean succeeded;
20144                try (PackageFreezer freezer = freezePackage(packageName,
20145                        "clearApplicationUserData")) {
20146                    synchronized (mInstallLock) {
20147                        succeeded = clearApplicationUserDataLIF(packageName, userId);
20148                    }
20149                    clearExternalStorageDataSync(packageName, userId, true);
20150                    synchronized (mPackages) {
20151                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20152                                packageName, userId);
20153                    }
20154                }
20155                if (succeeded) {
20156                    // invoke DeviceStorageMonitor's update method to clear any notifications
20157                    DeviceStorageMonitorInternal dsm = LocalServices
20158                            .getService(DeviceStorageMonitorInternal.class);
20159                    if (dsm != null) {
20160                        dsm.checkMemory();
20161                    }
20162                }
20163                if(observer != null) {
20164                    try {
20165                        observer.onRemoveCompleted(packageName, succeeded);
20166                    } catch (RemoteException e) {
20167                        Log.i(TAG, "Observer no longer exists.");
20168                    }
20169                } //end if observer
20170            } //end run
20171        });
20172    }
20173
20174    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20175        if (packageName == null) {
20176            Slog.w(TAG, "Attempt to delete null packageName.");
20177            return false;
20178        }
20179
20180        // Try finding details about the requested package
20181        PackageParser.Package pkg;
20182        synchronized (mPackages) {
20183            pkg = mPackages.get(packageName);
20184            if (pkg == null) {
20185                final PackageSetting ps = mSettings.mPackages.get(packageName);
20186                if (ps != null) {
20187                    pkg = ps.pkg;
20188                }
20189            }
20190
20191            if (pkg == null) {
20192                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20193                return false;
20194            }
20195
20196            PackageSetting ps = (PackageSetting) pkg.mExtras;
20197            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20198        }
20199
20200        clearAppDataLIF(pkg, userId,
20201                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20202
20203        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20204        removeKeystoreDataIfNeeded(userId, appId);
20205
20206        UserManagerInternal umInternal = getUserManagerInternal();
20207        final int flags;
20208        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20209            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20210        } else if (umInternal.isUserRunning(userId)) {
20211            flags = StorageManager.FLAG_STORAGE_DE;
20212        } else {
20213            flags = 0;
20214        }
20215        prepareAppDataContentsLIF(pkg, userId, flags);
20216
20217        return true;
20218    }
20219
20220    /**
20221     * Reverts user permission state changes (permissions and flags) in
20222     * all packages for a given user.
20223     *
20224     * @param userId The device user for which to do a reset.
20225     */
20226    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20227        final int packageCount = mPackages.size();
20228        for (int i = 0; i < packageCount; i++) {
20229            PackageParser.Package pkg = mPackages.valueAt(i);
20230            PackageSetting ps = (PackageSetting) pkg.mExtras;
20231            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20232        }
20233    }
20234
20235    private void resetNetworkPolicies(int userId) {
20236        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20237    }
20238
20239    /**
20240     * Reverts user permission state changes (permissions and flags).
20241     *
20242     * @param ps The package for which to reset.
20243     * @param userId The device user for which to do a reset.
20244     */
20245    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20246            final PackageSetting ps, final int userId) {
20247        if (ps.pkg == null) {
20248            return;
20249        }
20250
20251        // These are flags that can change base on user actions.
20252        final int userSettableMask = FLAG_PERMISSION_USER_SET
20253                | FLAG_PERMISSION_USER_FIXED
20254                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20255                | FLAG_PERMISSION_REVIEW_REQUIRED;
20256
20257        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20258                | FLAG_PERMISSION_POLICY_FIXED;
20259
20260        boolean writeInstallPermissions = false;
20261        boolean writeRuntimePermissions = false;
20262
20263        final int permissionCount = ps.pkg.requestedPermissions.size();
20264        for (int i = 0; i < permissionCount; i++) {
20265            String permission = ps.pkg.requestedPermissions.get(i);
20266
20267            BasePermission bp = mSettings.mPermissions.get(permission);
20268            if (bp == null) {
20269                continue;
20270            }
20271
20272            // If shared user we just reset the state to which only this app contributed.
20273            if (ps.sharedUser != null) {
20274                boolean used = false;
20275                final int packageCount = ps.sharedUser.packages.size();
20276                for (int j = 0; j < packageCount; j++) {
20277                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20278                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20279                            && pkg.pkg.requestedPermissions.contains(permission)) {
20280                        used = true;
20281                        break;
20282                    }
20283                }
20284                if (used) {
20285                    continue;
20286                }
20287            }
20288
20289            PermissionsState permissionsState = ps.getPermissionsState();
20290
20291            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20292
20293            // Always clear the user settable flags.
20294            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20295                    bp.name) != null;
20296            // If permission review is enabled and this is a legacy app, mark the
20297            // permission as requiring a review as this is the initial state.
20298            int flags = 0;
20299            if (mPermissionReviewRequired
20300                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20301                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20302            }
20303            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20304                if (hasInstallState) {
20305                    writeInstallPermissions = true;
20306                } else {
20307                    writeRuntimePermissions = true;
20308                }
20309            }
20310
20311            // Below is only runtime permission handling.
20312            if (!bp.isRuntime()) {
20313                continue;
20314            }
20315
20316            // Never clobber system or policy.
20317            if ((oldFlags & policyOrSystemFlags) != 0) {
20318                continue;
20319            }
20320
20321            // If this permission was granted by default, make sure it is.
20322            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20323                if (permissionsState.grantRuntimePermission(bp, userId)
20324                        != PERMISSION_OPERATION_FAILURE) {
20325                    writeRuntimePermissions = true;
20326                }
20327            // If permission review is enabled the permissions for a legacy apps
20328            // are represented as constantly granted runtime ones, so don't revoke.
20329            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20330                // Otherwise, reset the permission.
20331                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20332                switch (revokeResult) {
20333                    case PERMISSION_OPERATION_SUCCESS:
20334                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20335                        writeRuntimePermissions = true;
20336                        final int appId = ps.appId;
20337                        mHandler.post(new Runnable() {
20338                            @Override
20339                            public void run() {
20340                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20341                            }
20342                        });
20343                    } break;
20344                }
20345            }
20346        }
20347
20348        // Synchronously write as we are taking permissions away.
20349        if (writeRuntimePermissions) {
20350            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20351        }
20352
20353        // Synchronously write as we are taking permissions away.
20354        if (writeInstallPermissions) {
20355            mSettings.writeLPr();
20356        }
20357    }
20358
20359    /**
20360     * Remove entries from the keystore daemon. Will only remove it if the
20361     * {@code appId} is valid.
20362     */
20363    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20364        if (appId < 0) {
20365            return;
20366        }
20367
20368        final KeyStore keyStore = KeyStore.getInstance();
20369        if (keyStore != null) {
20370            if (userId == UserHandle.USER_ALL) {
20371                for (final int individual : sUserManager.getUserIds()) {
20372                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20373                }
20374            } else {
20375                keyStore.clearUid(UserHandle.getUid(userId, appId));
20376            }
20377        } else {
20378            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20379        }
20380    }
20381
20382    @Override
20383    public void deleteApplicationCacheFiles(final String packageName,
20384            final IPackageDataObserver observer) {
20385        final int userId = UserHandle.getCallingUserId();
20386        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20387    }
20388
20389    @Override
20390    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20391            final IPackageDataObserver observer) {
20392        final int callingUid = Binder.getCallingUid();
20393        mContext.enforceCallingOrSelfPermission(
20394                android.Manifest.permission.DELETE_CACHE_FILES, null);
20395        enforceCrossUserPermission(callingUid, userId,
20396                /* requireFullPermission= */ true, /* checkShell= */ false,
20397                "delete application cache files");
20398        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20399                android.Manifest.permission.ACCESS_INSTANT_APPS);
20400
20401        final PackageParser.Package pkg;
20402        synchronized (mPackages) {
20403            pkg = mPackages.get(packageName);
20404        }
20405
20406        // Queue up an async operation since the package deletion may take a little while.
20407        mHandler.post(new Runnable() {
20408            public void run() {
20409                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20410                boolean doClearData = true;
20411                if (ps != null) {
20412                    final boolean targetIsInstantApp =
20413                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20414                    doClearData = !targetIsInstantApp
20415                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20416                }
20417                if (doClearData) {
20418                    synchronized (mInstallLock) {
20419                        final int flags = StorageManager.FLAG_STORAGE_DE
20420                                | StorageManager.FLAG_STORAGE_CE;
20421                        // We're only clearing cache files, so we don't care if the
20422                        // app is unfrozen and still able to run
20423                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20424                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20425                    }
20426                    clearExternalStorageDataSync(packageName, userId, false);
20427                }
20428                if (observer != null) {
20429                    try {
20430                        observer.onRemoveCompleted(packageName, true);
20431                    } catch (RemoteException e) {
20432                        Log.i(TAG, "Observer no longer exists.");
20433                    }
20434                }
20435            }
20436        });
20437    }
20438
20439    @Override
20440    public void getPackageSizeInfo(final String packageName, int userHandle,
20441            final IPackageStatsObserver observer) {
20442        throw new UnsupportedOperationException(
20443                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20444    }
20445
20446    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20447        final PackageSetting ps;
20448        synchronized (mPackages) {
20449            ps = mSettings.mPackages.get(packageName);
20450            if (ps == null) {
20451                Slog.w(TAG, "Failed to find settings for " + packageName);
20452                return false;
20453            }
20454        }
20455
20456        final String[] packageNames = { packageName };
20457        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20458        final String[] codePaths = { ps.codePathString };
20459
20460        try {
20461            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20462                    ps.appId, ceDataInodes, codePaths, stats);
20463
20464            // For now, ignore code size of packages on system partition
20465            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20466                stats.codeSize = 0;
20467            }
20468
20469            // External clients expect these to be tracked separately
20470            stats.dataSize -= stats.cacheSize;
20471
20472        } catch (InstallerException e) {
20473            Slog.w(TAG, String.valueOf(e));
20474            return false;
20475        }
20476
20477        return true;
20478    }
20479
20480    private int getUidTargetSdkVersionLockedLPr(int uid) {
20481        Object obj = mSettings.getUserIdLPr(uid);
20482        if (obj instanceof SharedUserSetting) {
20483            final SharedUserSetting sus = (SharedUserSetting) obj;
20484            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20485            final Iterator<PackageSetting> it = sus.packages.iterator();
20486            while (it.hasNext()) {
20487                final PackageSetting ps = it.next();
20488                if (ps.pkg != null) {
20489                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20490                    if (v < vers) vers = v;
20491                }
20492            }
20493            return vers;
20494        } else if (obj instanceof PackageSetting) {
20495            final PackageSetting ps = (PackageSetting) obj;
20496            if (ps.pkg != null) {
20497                return ps.pkg.applicationInfo.targetSdkVersion;
20498            }
20499        }
20500        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20501    }
20502
20503    @Override
20504    public void addPreferredActivity(IntentFilter filter, int match,
20505            ComponentName[] set, ComponentName activity, int userId) {
20506        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20507                "Adding preferred");
20508    }
20509
20510    private void addPreferredActivityInternal(IntentFilter filter, int match,
20511            ComponentName[] set, ComponentName activity, boolean always, int userId,
20512            String opname) {
20513        // writer
20514        int callingUid = Binder.getCallingUid();
20515        enforceCrossUserPermission(callingUid, userId,
20516                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20517        if (filter.countActions() == 0) {
20518            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20519            return;
20520        }
20521        synchronized (mPackages) {
20522            if (mContext.checkCallingOrSelfPermission(
20523                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20524                    != PackageManager.PERMISSION_GRANTED) {
20525                if (getUidTargetSdkVersionLockedLPr(callingUid)
20526                        < Build.VERSION_CODES.FROYO) {
20527                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20528                            + callingUid);
20529                    return;
20530                }
20531                mContext.enforceCallingOrSelfPermission(
20532                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20533            }
20534
20535            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20536            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20537                    + userId + ":");
20538            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20539            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20540            scheduleWritePackageRestrictionsLocked(userId);
20541            postPreferredActivityChangedBroadcast(userId);
20542        }
20543    }
20544
20545    private void postPreferredActivityChangedBroadcast(int userId) {
20546        mHandler.post(() -> {
20547            final IActivityManager am = ActivityManager.getService();
20548            if (am == null) {
20549                return;
20550            }
20551
20552            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20553            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20554            try {
20555                am.broadcastIntent(null, intent, null, null,
20556                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20557                        null, false, false, userId);
20558            } catch (RemoteException e) {
20559            }
20560        });
20561    }
20562
20563    @Override
20564    public void replacePreferredActivity(IntentFilter filter, int match,
20565            ComponentName[] set, ComponentName activity, int userId) {
20566        if (filter.countActions() != 1) {
20567            throw new IllegalArgumentException(
20568                    "replacePreferredActivity expects filter to have only 1 action.");
20569        }
20570        if (filter.countDataAuthorities() != 0
20571                || filter.countDataPaths() != 0
20572                || filter.countDataSchemes() > 1
20573                || filter.countDataTypes() != 0) {
20574            throw new IllegalArgumentException(
20575                    "replacePreferredActivity expects filter to have no data authorities, " +
20576                    "paths, or types; and at most one scheme.");
20577        }
20578
20579        final int callingUid = Binder.getCallingUid();
20580        enforceCrossUserPermission(callingUid, userId,
20581                true /* requireFullPermission */, false /* checkShell */,
20582                "replace preferred activity");
20583        synchronized (mPackages) {
20584            if (mContext.checkCallingOrSelfPermission(
20585                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20586                    != PackageManager.PERMISSION_GRANTED) {
20587                if (getUidTargetSdkVersionLockedLPr(callingUid)
20588                        < Build.VERSION_CODES.FROYO) {
20589                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20590                            + Binder.getCallingUid());
20591                    return;
20592                }
20593                mContext.enforceCallingOrSelfPermission(
20594                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20595            }
20596
20597            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20598            if (pir != null) {
20599                // Get all of the existing entries that exactly match this filter.
20600                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20601                if (existing != null && existing.size() == 1) {
20602                    PreferredActivity cur = existing.get(0);
20603                    if (DEBUG_PREFERRED) {
20604                        Slog.i(TAG, "Checking replace of preferred:");
20605                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20606                        if (!cur.mPref.mAlways) {
20607                            Slog.i(TAG, "  -- CUR; not mAlways!");
20608                        } else {
20609                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20610                            Slog.i(TAG, "  -- CUR: mSet="
20611                                    + Arrays.toString(cur.mPref.mSetComponents));
20612                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20613                            Slog.i(TAG, "  -- NEW: mMatch="
20614                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20615                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20616                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20617                        }
20618                    }
20619                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20620                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20621                            && cur.mPref.sameSet(set)) {
20622                        // Setting the preferred activity to what it happens to be already
20623                        if (DEBUG_PREFERRED) {
20624                            Slog.i(TAG, "Replacing with same preferred activity "
20625                                    + cur.mPref.mShortComponent + " for user "
20626                                    + userId + ":");
20627                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20628                        }
20629                        return;
20630                    }
20631                }
20632
20633                if (existing != null) {
20634                    if (DEBUG_PREFERRED) {
20635                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20636                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20637                    }
20638                    for (int i = 0; i < existing.size(); i++) {
20639                        PreferredActivity pa = existing.get(i);
20640                        if (DEBUG_PREFERRED) {
20641                            Slog.i(TAG, "Removing existing preferred activity "
20642                                    + pa.mPref.mComponent + ":");
20643                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20644                        }
20645                        pir.removeFilter(pa);
20646                    }
20647                }
20648            }
20649            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20650                    "Replacing preferred");
20651        }
20652    }
20653
20654    @Override
20655    public void clearPackagePreferredActivities(String packageName) {
20656        final int callingUid = Binder.getCallingUid();
20657        if (getInstantAppPackageName(callingUid) != null) {
20658            return;
20659        }
20660        // writer
20661        synchronized (mPackages) {
20662            PackageParser.Package pkg = mPackages.get(packageName);
20663            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20664                if (mContext.checkCallingOrSelfPermission(
20665                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20666                        != PackageManager.PERMISSION_GRANTED) {
20667                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20668                            < Build.VERSION_CODES.FROYO) {
20669                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20670                                + callingUid);
20671                        return;
20672                    }
20673                    mContext.enforceCallingOrSelfPermission(
20674                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20675                }
20676            }
20677            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20678            if (ps != null
20679                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20680                return;
20681            }
20682            int user = UserHandle.getCallingUserId();
20683            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20684                scheduleWritePackageRestrictionsLocked(user);
20685            }
20686        }
20687    }
20688
20689    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20690    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20691        ArrayList<PreferredActivity> removed = null;
20692        boolean changed = false;
20693        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20694            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20695            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20696            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20697                continue;
20698            }
20699            Iterator<PreferredActivity> it = pir.filterIterator();
20700            while (it.hasNext()) {
20701                PreferredActivity pa = it.next();
20702                // Mark entry for removal only if it matches the package name
20703                // and the entry is of type "always".
20704                if (packageName == null ||
20705                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20706                                && pa.mPref.mAlways)) {
20707                    if (removed == null) {
20708                        removed = new ArrayList<PreferredActivity>();
20709                    }
20710                    removed.add(pa);
20711                }
20712            }
20713            if (removed != null) {
20714                for (int j=0; j<removed.size(); j++) {
20715                    PreferredActivity pa = removed.get(j);
20716                    pir.removeFilter(pa);
20717                }
20718                changed = true;
20719            }
20720        }
20721        if (changed) {
20722            postPreferredActivityChangedBroadcast(userId);
20723        }
20724        return changed;
20725    }
20726
20727    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20728    private void clearIntentFilterVerificationsLPw(int userId) {
20729        final int packageCount = mPackages.size();
20730        for (int i = 0; i < packageCount; i++) {
20731            PackageParser.Package pkg = mPackages.valueAt(i);
20732            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20733        }
20734    }
20735
20736    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20737    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20738        if (userId == UserHandle.USER_ALL) {
20739            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20740                    sUserManager.getUserIds())) {
20741                for (int oneUserId : sUserManager.getUserIds()) {
20742                    scheduleWritePackageRestrictionsLocked(oneUserId);
20743                }
20744            }
20745        } else {
20746            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20747                scheduleWritePackageRestrictionsLocked(userId);
20748            }
20749        }
20750    }
20751
20752    /** Clears state for all users, and touches intent filter verification policy */
20753    void clearDefaultBrowserIfNeeded(String packageName) {
20754        for (int oneUserId : sUserManager.getUserIds()) {
20755            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20756        }
20757    }
20758
20759    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20760        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20761        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20762            if (packageName.equals(defaultBrowserPackageName)) {
20763                setDefaultBrowserPackageName(null, userId);
20764            }
20765        }
20766    }
20767
20768    @Override
20769    public void resetApplicationPreferences(int userId) {
20770        mContext.enforceCallingOrSelfPermission(
20771                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20772        final long identity = Binder.clearCallingIdentity();
20773        // writer
20774        try {
20775            synchronized (mPackages) {
20776                clearPackagePreferredActivitiesLPw(null, userId);
20777                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20778                // TODO: We have to reset the default SMS and Phone. This requires
20779                // significant refactoring to keep all default apps in the package
20780                // manager (cleaner but more work) or have the services provide
20781                // callbacks to the package manager to request a default app reset.
20782                applyFactoryDefaultBrowserLPw(userId);
20783                clearIntentFilterVerificationsLPw(userId);
20784                primeDomainVerificationsLPw(userId);
20785                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20786                scheduleWritePackageRestrictionsLocked(userId);
20787            }
20788            resetNetworkPolicies(userId);
20789        } finally {
20790            Binder.restoreCallingIdentity(identity);
20791        }
20792    }
20793
20794    @Override
20795    public int getPreferredActivities(List<IntentFilter> outFilters,
20796            List<ComponentName> outActivities, String packageName) {
20797        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20798            return 0;
20799        }
20800        int num = 0;
20801        final int userId = UserHandle.getCallingUserId();
20802        // reader
20803        synchronized (mPackages) {
20804            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20805            if (pir != null) {
20806                final Iterator<PreferredActivity> it = pir.filterIterator();
20807                while (it.hasNext()) {
20808                    final PreferredActivity pa = it.next();
20809                    if (packageName == null
20810                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20811                                    && pa.mPref.mAlways)) {
20812                        if (outFilters != null) {
20813                            outFilters.add(new IntentFilter(pa));
20814                        }
20815                        if (outActivities != null) {
20816                            outActivities.add(pa.mPref.mComponent);
20817                        }
20818                    }
20819                }
20820            }
20821        }
20822
20823        return num;
20824    }
20825
20826    @Override
20827    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20828            int userId) {
20829        int callingUid = Binder.getCallingUid();
20830        if (callingUid != Process.SYSTEM_UID) {
20831            throw new SecurityException(
20832                    "addPersistentPreferredActivity can only be run by the system");
20833        }
20834        if (filter.countActions() == 0) {
20835            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20836            return;
20837        }
20838        synchronized (mPackages) {
20839            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20840                    ":");
20841            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20842            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20843                    new PersistentPreferredActivity(filter, activity));
20844            scheduleWritePackageRestrictionsLocked(userId);
20845            postPreferredActivityChangedBroadcast(userId);
20846        }
20847    }
20848
20849    @Override
20850    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20851        int callingUid = Binder.getCallingUid();
20852        if (callingUid != Process.SYSTEM_UID) {
20853            throw new SecurityException(
20854                    "clearPackagePersistentPreferredActivities can only be run by the system");
20855        }
20856        ArrayList<PersistentPreferredActivity> removed = null;
20857        boolean changed = false;
20858        synchronized (mPackages) {
20859            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20860                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20861                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20862                        .valueAt(i);
20863                if (userId != thisUserId) {
20864                    continue;
20865                }
20866                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20867                while (it.hasNext()) {
20868                    PersistentPreferredActivity ppa = it.next();
20869                    // Mark entry for removal only if it matches the package name.
20870                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20871                        if (removed == null) {
20872                            removed = new ArrayList<PersistentPreferredActivity>();
20873                        }
20874                        removed.add(ppa);
20875                    }
20876                }
20877                if (removed != null) {
20878                    for (int j=0; j<removed.size(); j++) {
20879                        PersistentPreferredActivity ppa = removed.get(j);
20880                        ppir.removeFilter(ppa);
20881                    }
20882                    changed = true;
20883                }
20884            }
20885
20886            if (changed) {
20887                scheduleWritePackageRestrictionsLocked(userId);
20888                postPreferredActivityChangedBroadcast(userId);
20889            }
20890        }
20891    }
20892
20893    /**
20894     * Common machinery for picking apart a restored XML blob and passing
20895     * it to a caller-supplied functor to be applied to the running system.
20896     */
20897    private void restoreFromXml(XmlPullParser parser, int userId,
20898            String expectedStartTag, BlobXmlRestorer functor)
20899            throws IOException, XmlPullParserException {
20900        int type;
20901        while ((type = parser.next()) != XmlPullParser.START_TAG
20902                && type != XmlPullParser.END_DOCUMENT) {
20903        }
20904        if (type != XmlPullParser.START_TAG) {
20905            // oops didn't find a start tag?!
20906            if (DEBUG_BACKUP) {
20907                Slog.e(TAG, "Didn't find start tag during restore");
20908            }
20909            return;
20910        }
20911Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20912        // this is supposed to be TAG_PREFERRED_BACKUP
20913        if (!expectedStartTag.equals(parser.getName())) {
20914            if (DEBUG_BACKUP) {
20915                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20916            }
20917            return;
20918        }
20919
20920        // skip interfering stuff, then we're aligned with the backing implementation
20921        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20922Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20923        functor.apply(parser, userId);
20924    }
20925
20926    private interface BlobXmlRestorer {
20927        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20928    }
20929
20930    /**
20931     * Non-Binder method, support for the backup/restore mechanism: write the
20932     * full set of preferred activities in its canonical XML format.  Returns the
20933     * XML output as a byte array, or null if there is none.
20934     */
20935    @Override
20936    public byte[] getPreferredActivityBackup(int userId) {
20937        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20938            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20939        }
20940
20941        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20942        try {
20943            final XmlSerializer serializer = new FastXmlSerializer();
20944            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20945            serializer.startDocument(null, true);
20946            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20947
20948            synchronized (mPackages) {
20949                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20950            }
20951
20952            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20953            serializer.endDocument();
20954            serializer.flush();
20955        } catch (Exception e) {
20956            if (DEBUG_BACKUP) {
20957                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20958            }
20959            return null;
20960        }
20961
20962        return dataStream.toByteArray();
20963    }
20964
20965    @Override
20966    public void restorePreferredActivities(byte[] backup, int userId) {
20967        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20968            throw new SecurityException("Only the system may call restorePreferredActivities()");
20969        }
20970
20971        try {
20972            final XmlPullParser parser = Xml.newPullParser();
20973            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20974            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20975                    new BlobXmlRestorer() {
20976                        @Override
20977                        public void apply(XmlPullParser parser, int userId)
20978                                throws XmlPullParserException, IOException {
20979                            synchronized (mPackages) {
20980                                mSettings.readPreferredActivitiesLPw(parser, userId);
20981                            }
20982                        }
20983                    } );
20984        } catch (Exception e) {
20985            if (DEBUG_BACKUP) {
20986                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20987            }
20988        }
20989    }
20990
20991    /**
20992     * Non-Binder method, support for the backup/restore mechanism: write the
20993     * default browser (etc) settings in its canonical XML format.  Returns the default
20994     * browser XML representation as a byte array, or null if there is none.
20995     */
20996    @Override
20997    public byte[] getDefaultAppsBackup(int userId) {
20998        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20999            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21000        }
21001
21002        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21003        try {
21004            final XmlSerializer serializer = new FastXmlSerializer();
21005            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21006            serializer.startDocument(null, true);
21007            serializer.startTag(null, TAG_DEFAULT_APPS);
21008
21009            synchronized (mPackages) {
21010                mSettings.writeDefaultAppsLPr(serializer, userId);
21011            }
21012
21013            serializer.endTag(null, TAG_DEFAULT_APPS);
21014            serializer.endDocument();
21015            serializer.flush();
21016        } catch (Exception e) {
21017            if (DEBUG_BACKUP) {
21018                Slog.e(TAG, "Unable to write default apps for backup", e);
21019            }
21020            return null;
21021        }
21022
21023        return dataStream.toByteArray();
21024    }
21025
21026    @Override
21027    public void restoreDefaultApps(byte[] backup, int userId) {
21028        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21029            throw new SecurityException("Only the system may call restoreDefaultApps()");
21030        }
21031
21032        try {
21033            final XmlPullParser parser = Xml.newPullParser();
21034            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21035            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21036                    new BlobXmlRestorer() {
21037                        @Override
21038                        public void apply(XmlPullParser parser, int userId)
21039                                throws XmlPullParserException, IOException {
21040                            synchronized (mPackages) {
21041                                mSettings.readDefaultAppsLPw(parser, userId);
21042                            }
21043                        }
21044                    } );
21045        } catch (Exception e) {
21046            if (DEBUG_BACKUP) {
21047                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21048            }
21049        }
21050    }
21051
21052    @Override
21053    public byte[] getIntentFilterVerificationBackup(int userId) {
21054        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21055            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21056        }
21057
21058        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21059        try {
21060            final XmlSerializer serializer = new FastXmlSerializer();
21061            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21062            serializer.startDocument(null, true);
21063            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21064
21065            synchronized (mPackages) {
21066                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21067            }
21068
21069            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21070            serializer.endDocument();
21071            serializer.flush();
21072        } catch (Exception e) {
21073            if (DEBUG_BACKUP) {
21074                Slog.e(TAG, "Unable to write default apps for backup", e);
21075            }
21076            return null;
21077        }
21078
21079        return dataStream.toByteArray();
21080    }
21081
21082    @Override
21083    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21084        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21085            throw new SecurityException("Only the system may call restorePreferredActivities()");
21086        }
21087
21088        try {
21089            final XmlPullParser parser = Xml.newPullParser();
21090            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21091            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21092                    new BlobXmlRestorer() {
21093                        @Override
21094                        public void apply(XmlPullParser parser, int userId)
21095                                throws XmlPullParserException, IOException {
21096                            synchronized (mPackages) {
21097                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21098                                mSettings.writeLPr();
21099                            }
21100                        }
21101                    } );
21102        } catch (Exception e) {
21103            if (DEBUG_BACKUP) {
21104                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21105            }
21106        }
21107    }
21108
21109    @Override
21110    public byte[] getPermissionGrantBackup(int userId) {
21111        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21112            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21113        }
21114
21115        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21116        try {
21117            final XmlSerializer serializer = new FastXmlSerializer();
21118            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21119            serializer.startDocument(null, true);
21120            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21121
21122            synchronized (mPackages) {
21123                serializeRuntimePermissionGrantsLPr(serializer, userId);
21124            }
21125
21126            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21127            serializer.endDocument();
21128            serializer.flush();
21129        } catch (Exception e) {
21130            if (DEBUG_BACKUP) {
21131                Slog.e(TAG, "Unable to write default apps for backup", e);
21132            }
21133            return null;
21134        }
21135
21136        return dataStream.toByteArray();
21137    }
21138
21139    @Override
21140    public void restorePermissionGrants(byte[] backup, int userId) {
21141        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21142            throw new SecurityException("Only the system may call restorePermissionGrants()");
21143        }
21144
21145        try {
21146            final XmlPullParser parser = Xml.newPullParser();
21147            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21148            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21149                    new BlobXmlRestorer() {
21150                        @Override
21151                        public void apply(XmlPullParser parser, int userId)
21152                                throws XmlPullParserException, IOException {
21153                            synchronized (mPackages) {
21154                                processRestoredPermissionGrantsLPr(parser, userId);
21155                            }
21156                        }
21157                    } );
21158        } catch (Exception e) {
21159            if (DEBUG_BACKUP) {
21160                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21161            }
21162        }
21163    }
21164
21165    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21166            throws IOException {
21167        serializer.startTag(null, TAG_ALL_GRANTS);
21168
21169        final int N = mSettings.mPackages.size();
21170        for (int i = 0; i < N; i++) {
21171            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21172            boolean pkgGrantsKnown = false;
21173
21174            PermissionsState packagePerms = ps.getPermissionsState();
21175
21176            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21177                final int grantFlags = state.getFlags();
21178                // only look at grants that are not system/policy fixed
21179                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21180                    final boolean isGranted = state.isGranted();
21181                    // And only back up the user-twiddled state bits
21182                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21183                        final String packageName = mSettings.mPackages.keyAt(i);
21184                        if (!pkgGrantsKnown) {
21185                            serializer.startTag(null, TAG_GRANT);
21186                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21187                            pkgGrantsKnown = true;
21188                        }
21189
21190                        final boolean userSet =
21191                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21192                        final boolean userFixed =
21193                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21194                        final boolean revoke =
21195                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21196
21197                        serializer.startTag(null, TAG_PERMISSION);
21198                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21199                        if (isGranted) {
21200                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21201                        }
21202                        if (userSet) {
21203                            serializer.attribute(null, ATTR_USER_SET, "true");
21204                        }
21205                        if (userFixed) {
21206                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21207                        }
21208                        if (revoke) {
21209                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21210                        }
21211                        serializer.endTag(null, TAG_PERMISSION);
21212                    }
21213                }
21214            }
21215
21216            if (pkgGrantsKnown) {
21217                serializer.endTag(null, TAG_GRANT);
21218            }
21219        }
21220
21221        serializer.endTag(null, TAG_ALL_GRANTS);
21222    }
21223
21224    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21225            throws XmlPullParserException, IOException {
21226        String pkgName = null;
21227        int outerDepth = parser.getDepth();
21228        int type;
21229        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21230                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21231            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21232                continue;
21233            }
21234
21235            final String tagName = parser.getName();
21236            if (tagName.equals(TAG_GRANT)) {
21237                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21238                if (DEBUG_BACKUP) {
21239                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21240                }
21241            } else if (tagName.equals(TAG_PERMISSION)) {
21242
21243                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21244                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21245
21246                int newFlagSet = 0;
21247                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21248                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21249                }
21250                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21251                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21252                }
21253                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21254                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21255                }
21256                if (DEBUG_BACKUP) {
21257                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21258                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21259                }
21260                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21261                if (ps != null) {
21262                    // Already installed so we apply the grant immediately
21263                    if (DEBUG_BACKUP) {
21264                        Slog.v(TAG, "        + already installed; applying");
21265                    }
21266                    PermissionsState perms = ps.getPermissionsState();
21267                    BasePermission bp = mSettings.mPermissions.get(permName);
21268                    if (bp != null) {
21269                        if (isGranted) {
21270                            perms.grantRuntimePermission(bp, userId);
21271                        }
21272                        if (newFlagSet != 0) {
21273                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21274                        }
21275                    }
21276                } else {
21277                    // Need to wait for post-restore install to apply the grant
21278                    if (DEBUG_BACKUP) {
21279                        Slog.v(TAG, "        - not yet installed; saving for later");
21280                    }
21281                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21282                            isGranted, newFlagSet, userId);
21283                }
21284            } else {
21285                PackageManagerService.reportSettingsProblem(Log.WARN,
21286                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21287                XmlUtils.skipCurrentTag(parser);
21288            }
21289        }
21290
21291        scheduleWriteSettingsLocked();
21292        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21293    }
21294
21295    @Override
21296    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21297            int sourceUserId, int targetUserId, int flags) {
21298        mContext.enforceCallingOrSelfPermission(
21299                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21300        int callingUid = Binder.getCallingUid();
21301        enforceOwnerRights(ownerPackage, callingUid);
21302        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21303        if (intentFilter.countActions() == 0) {
21304            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21305            return;
21306        }
21307        synchronized (mPackages) {
21308            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21309                    ownerPackage, targetUserId, flags);
21310            CrossProfileIntentResolver resolver =
21311                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21312            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21313            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21314            if (existing != null) {
21315                int size = existing.size();
21316                for (int i = 0; i < size; i++) {
21317                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21318                        return;
21319                    }
21320                }
21321            }
21322            resolver.addFilter(newFilter);
21323            scheduleWritePackageRestrictionsLocked(sourceUserId);
21324        }
21325    }
21326
21327    @Override
21328    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21329        mContext.enforceCallingOrSelfPermission(
21330                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21331        final int callingUid = Binder.getCallingUid();
21332        enforceOwnerRights(ownerPackage, callingUid);
21333        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21334        synchronized (mPackages) {
21335            CrossProfileIntentResolver resolver =
21336                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21337            ArraySet<CrossProfileIntentFilter> set =
21338                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21339            for (CrossProfileIntentFilter filter : set) {
21340                if (filter.getOwnerPackage().equals(ownerPackage)) {
21341                    resolver.removeFilter(filter);
21342                }
21343            }
21344            scheduleWritePackageRestrictionsLocked(sourceUserId);
21345        }
21346    }
21347
21348    // Enforcing that callingUid is owning pkg on userId
21349    private void enforceOwnerRights(String pkg, int callingUid) {
21350        // The system owns everything.
21351        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21352            return;
21353        }
21354        final int callingUserId = UserHandle.getUserId(callingUid);
21355        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21356        if (pi == null) {
21357            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21358                    + callingUserId);
21359        }
21360        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21361            throw new SecurityException("Calling uid " + callingUid
21362                    + " does not own package " + pkg);
21363        }
21364    }
21365
21366    @Override
21367    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21368        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21369            return null;
21370        }
21371        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21372    }
21373
21374    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21375        UserManagerService ums = UserManagerService.getInstance();
21376        if (ums != null) {
21377            final UserInfo parent = ums.getProfileParent(userId);
21378            final int launcherUid = (parent != null) ? parent.id : userId;
21379            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21380            if (launcherComponent != null) {
21381                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21382                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21383                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21384                        .setPackage(launcherComponent.getPackageName());
21385                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21386            }
21387        }
21388    }
21389
21390    /**
21391     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21392     * then reports the most likely home activity or null if there are more than one.
21393     */
21394    private ComponentName getDefaultHomeActivity(int userId) {
21395        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21396        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21397        if (cn != null) {
21398            return cn;
21399        }
21400
21401        // Find the launcher with the highest priority and return that component if there are no
21402        // other home activity with the same priority.
21403        int lastPriority = Integer.MIN_VALUE;
21404        ComponentName lastComponent = null;
21405        final int size = allHomeCandidates.size();
21406        for (int i = 0; i < size; i++) {
21407            final ResolveInfo ri = allHomeCandidates.get(i);
21408            if (ri.priority > lastPriority) {
21409                lastComponent = ri.activityInfo.getComponentName();
21410                lastPriority = ri.priority;
21411            } else if (ri.priority == lastPriority) {
21412                // Two components found with same priority.
21413                lastComponent = null;
21414            }
21415        }
21416        return lastComponent;
21417    }
21418
21419    private Intent getHomeIntent() {
21420        Intent intent = new Intent(Intent.ACTION_MAIN);
21421        intent.addCategory(Intent.CATEGORY_HOME);
21422        intent.addCategory(Intent.CATEGORY_DEFAULT);
21423        return intent;
21424    }
21425
21426    private IntentFilter getHomeFilter() {
21427        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21428        filter.addCategory(Intent.CATEGORY_HOME);
21429        filter.addCategory(Intent.CATEGORY_DEFAULT);
21430        return filter;
21431    }
21432
21433    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21434            int userId) {
21435        Intent intent  = getHomeIntent();
21436        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21437                PackageManager.GET_META_DATA, userId);
21438        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21439                true, false, false, userId);
21440
21441        allHomeCandidates.clear();
21442        if (list != null) {
21443            for (ResolveInfo ri : list) {
21444                allHomeCandidates.add(ri);
21445            }
21446        }
21447        return (preferred == null || preferred.activityInfo == null)
21448                ? null
21449                : new ComponentName(preferred.activityInfo.packageName,
21450                        preferred.activityInfo.name);
21451    }
21452
21453    @Override
21454    public void setHomeActivity(ComponentName comp, int userId) {
21455        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21456            return;
21457        }
21458        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21459        getHomeActivitiesAsUser(homeActivities, userId);
21460
21461        boolean found = false;
21462
21463        final int size = homeActivities.size();
21464        final ComponentName[] set = new ComponentName[size];
21465        for (int i = 0; i < size; i++) {
21466            final ResolveInfo candidate = homeActivities.get(i);
21467            final ActivityInfo info = candidate.activityInfo;
21468            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21469            set[i] = activityName;
21470            if (!found && activityName.equals(comp)) {
21471                found = true;
21472            }
21473        }
21474        if (!found) {
21475            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21476                    + userId);
21477        }
21478        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21479                set, comp, userId);
21480    }
21481
21482    private @Nullable String getSetupWizardPackageName() {
21483        final Intent intent = new Intent(Intent.ACTION_MAIN);
21484        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21485
21486        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21487                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21488                        | MATCH_DISABLED_COMPONENTS,
21489                UserHandle.myUserId());
21490        if (matches.size() == 1) {
21491            return matches.get(0).getComponentInfo().packageName;
21492        } else {
21493            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21494                    + ": matches=" + matches);
21495            return null;
21496        }
21497    }
21498
21499    private @Nullable String getStorageManagerPackageName() {
21500        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21501
21502        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21503                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21504                        | MATCH_DISABLED_COMPONENTS,
21505                UserHandle.myUserId());
21506        if (matches.size() == 1) {
21507            return matches.get(0).getComponentInfo().packageName;
21508        } else {
21509            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21510                    + matches.size() + ": matches=" + matches);
21511            return null;
21512        }
21513    }
21514
21515    @Override
21516    public void setApplicationEnabledSetting(String appPackageName,
21517            int newState, int flags, int userId, String callingPackage) {
21518        if (!sUserManager.exists(userId)) return;
21519        if (callingPackage == null) {
21520            callingPackage = Integer.toString(Binder.getCallingUid());
21521        }
21522        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21523    }
21524
21525    @Override
21526    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21527        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21528        synchronized (mPackages) {
21529            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21530            if (pkgSetting != null) {
21531                pkgSetting.setUpdateAvailable(updateAvailable);
21532            }
21533        }
21534    }
21535
21536    @Override
21537    public void setComponentEnabledSetting(ComponentName componentName,
21538            int newState, int flags, int userId) {
21539        if (!sUserManager.exists(userId)) return;
21540        setEnabledSetting(componentName.getPackageName(),
21541                componentName.getClassName(), newState, flags, userId, null);
21542    }
21543
21544    private void setEnabledSetting(final String packageName, String className, int newState,
21545            final int flags, int userId, String callingPackage) {
21546        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21547              || newState == COMPONENT_ENABLED_STATE_ENABLED
21548              || newState == COMPONENT_ENABLED_STATE_DISABLED
21549              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21550              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21551            throw new IllegalArgumentException("Invalid new component state: "
21552                    + newState);
21553        }
21554        PackageSetting pkgSetting;
21555        final int callingUid = Binder.getCallingUid();
21556        final int permission;
21557        if (callingUid == Process.SYSTEM_UID) {
21558            permission = PackageManager.PERMISSION_GRANTED;
21559        } else {
21560            permission = mContext.checkCallingOrSelfPermission(
21561                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21562        }
21563        enforceCrossUserPermission(callingUid, userId,
21564                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21565        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21566        boolean sendNow = false;
21567        boolean isApp = (className == null);
21568        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21569        String componentName = isApp ? packageName : className;
21570        int packageUid = -1;
21571        ArrayList<String> components;
21572
21573        // reader
21574        synchronized (mPackages) {
21575            pkgSetting = mSettings.mPackages.get(packageName);
21576            if (pkgSetting == null) {
21577                if (!isCallerInstantApp) {
21578                    if (className == null) {
21579                        throw new IllegalArgumentException("Unknown package: " + packageName);
21580                    }
21581                    throw new IllegalArgumentException(
21582                            "Unknown component: " + packageName + "/" + className);
21583                } else {
21584                    // throw SecurityException to prevent leaking package information
21585                    throw new SecurityException(
21586                            "Attempt to change component state; "
21587                            + "pid=" + Binder.getCallingPid()
21588                            + ", uid=" + callingUid
21589                            + (className == null
21590                                    ? ", package=" + packageName
21591                                    : ", component=" + packageName + "/" + className));
21592                }
21593            }
21594        }
21595
21596        // Limit who can change which apps
21597        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21598            // Don't allow apps that don't have permission to modify other apps
21599            if (!allowedByPermission
21600                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21601                throw new SecurityException(
21602                        "Attempt to change component state; "
21603                        + "pid=" + Binder.getCallingPid()
21604                        + ", uid=" + callingUid
21605                        + (className == null
21606                                ? ", package=" + packageName
21607                                : ", component=" + packageName + "/" + className));
21608            }
21609            // Don't allow changing protected packages.
21610            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21611                throw new SecurityException("Cannot disable a protected package: " + packageName);
21612            }
21613        }
21614
21615        synchronized (mPackages) {
21616            if (callingUid == Process.SHELL_UID
21617                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21618                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21619                // unless it is a test package.
21620                int oldState = pkgSetting.getEnabled(userId);
21621                if (className == null
21622                    &&
21623                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21624                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21625                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21626                    &&
21627                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21628                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21629                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21630                    // ok
21631                } else {
21632                    throw new SecurityException(
21633                            "Shell cannot change component state for " + packageName + "/"
21634                            + className + " to " + newState);
21635                }
21636            }
21637            if (className == null) {
21638                // We're dealing with an application/package level state change
21639                if (pkgSetting.getEnabled(userId) == newState) {
21640                    // Nothing to do
21641                    return;
21642                }
21643                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21644                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21645                    // Don't care about who enables an app.
21646                    callingPackage = null;
21647                }
21648                pkgSetting.setEnabled(newState, userId, callingPackage);
21649                // pkgSetting.pkg.mSetEnabled = newState;
21650            } else {
21651                // We're dealing with a component level state change
21652                // First, verify that this is a valid class name.
21653                PackageParser.Package pkg = pkgSetting.pkg;
21654                if (pkg == null || !pkg.hasComponentClassName(className)) {
21655                    if (pkg != null &&
21656                            pkg.applicationInfo.targetSdkVersion >=
21657                                    Build.VERSION_CODES.JELLY_BEAN) {
21658                        throw new IllegalArgumentException("Component class " + className
21659                                + " does not exist in " + packageName);
21660                    } else {
21661                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21662                                + className + " does not exist in " + packageName);
21663                    }
21664                }
21665                switch (newState) {
21666                case COMPONENT_ENABLED_STATE_ENABLED:
21667                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21668                        return;
21669                    }
21670                    break;
21671                case COMPONENT_ENABLED_STATE_DISABLED:
21672                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21673                        return;
21674                    }
21675                    break;
21676                case COMPONENT_ENABLED_STATE_DEFAULT:
21677                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21678                        return;
21679                    }
21680                    break;
21681                default:
21682                    Slog.e(TAG, "Invalid new component state: " + newState);
21683                    return;
21684                }
21685            }
21686            scheduleWritePackageRestrictionsLocked(userId);
21687            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21688            final long callingId = Binder.clearCallingIdentity();
21689            try {
21690                updateInstantAppInstallerLocked(packageName);
21691            } finally {
21692                Binder.restoreCallingIdentity(callingId);
21693            }
21694            components = mPendingBroadcasts.get(userId, packageName);
21695            final boolean newPackage = components == null;
21696            if (newPackage) {
21697                components = new ArrayList<String>();
21698            }
21699            if (!components.contains(componentName)) {
21700                components.add(componentName);
21701            }
21702            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21703                sendNow = true;
21704                // Purge entry from pending broadcast list if another one exists already
21705                // since we are sending one right away.
21706                mPendingBroadcasts.remove(userId, packageName);
21707            } else {
21708                if (newPackage) {
21709                    mPendingBroadcasts.put(userId, packageName, components);
21710                }
21711                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21712                    // Schedule a message
21713                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21714                }
21715            }
21716        }
21717
21718        long callingId = Binder.clearCallingIdentity();
21719        try {
21720            if (sendNow) {
21721                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21722                sendPackageChangedBroadcast(packageName,
21723                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21724            }
21725        } finally {
21726            Binder.restoreCallingIdentity(callingId);
21727        }
21728    }
21729
21730    @Override
21731    public void flushPackageRestrictionsAsUser(int userId) {
21732        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21733            return;
21734        }
21735        if (!sUserManager.exists(userId)) {
21736            return;
21737        }
21738        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21739                false /* checkShell */, "flushPackageRestrictions");
21740        synchronized (mPackages) {
21741            mSettings.writePackageRestrictionsLPr(userId);
21742            mDirtyUsers.remove(userId);
21743            if (mDirtyUsers.isEmpty()) {
21744                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21745            }
21746        }
21747    }
21748
21749    private void sendPackageChangedBroadcast(String packageName,
21750            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21751        if (DEBUG_INSTALL)
21752            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21753                    + componentNames);
21754        Bundle extras = new Bundle(4);
21755        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21756        String nameList[] = new String[componentNames.size()];
21757        componentNames.toArray(nameList);
21758        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21759        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21760        extras.putInt(Intent.EXTRA_UID, packageUid);
21761        // If this is not reporting a change of the overall package, then only send it
21762        // to registered receivers.  We don't want to launch a swath of apps for every
21763        // little component state change.
21764        final int flags = !componentNames.contains(packageName)
21765                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21766        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21767                new int[] {UserHandle.getUserId(packageUid)});
21768    }
21769
21770    @Override
21771    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21772        if (!sUserManager.exists(userId)) return;
21773        final int callingUid = Binder.getCallingUid();
21774        if (getInstantAppPackageName(callingUid) != null) {
21775            return;
21776        }
21777        final int permission = mContext.checkCallingOrSelfPermission(
21778                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21779        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21780        enforceCrossUserPermission(callingUid, userId,
21781                true /* requireFullPermission */, true /* checkShell */, "stop package");
21782        // writer
21783        synchronized (mPackages) {
21784            final PackageSetting ps = mSettings.mPackages.get(packageName);
21785            if (!filterAppAccessLPr(ps, callingUid, userId)
21786                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21787                            allowedByPermission, callingUid, userId)) {
21788                scheduleWritePackageRestrictionsLocked(userId);
21789            }
21790        }
21791    }
21792
21793    @Override
21794    public String getInstallerPackageName(String packageName) {
21795        final int callingUid = Binder.getCallingUid();
21796        if (getInstantAppPackageName(callingUid) != null) {
21797            return null;
21798        }
21799        // reader
21800        synchronized (mPackages) {
21801            final PackageSetting ps = mSettings.mPackages.get(packageName);
21802            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21803                return null;
21804            }
21805            return mSettings.getInstallerPackageNameLPr(packageName);
21806        }
21807    }
21808
21809    public boolean isOrphaned(String packageName) {
21810        // reader
21811        synchronized (mPackages) {
21812            return mSettings.isOrphaned(packageName);
21813        }
21814    }
21815
21816    @Override
21817    public int getApplicationEnabledSetting(String packageName, int userId) {
21818        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21819        int callingUid = Binder.getCallingUid();
21820        enforceCrossUserPermission(callingUid, userId,
21821                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21822        // reader
21823        synchronized (mPackages) {
21824            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21825                return COMPONENT_ENABLED_STATE_DISABLED;
21826            }
21827            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21828        }
21829    }
21830
21831    @Override
21832    public int getComponentEnabledSetting(ComponentName component, int userId) {
21833        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21834        int callingUid = Binder.getCallingUid();
21835        enforceCrossUserPermission(callingUid, userId,
21836                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21837        synchronized (mPackages) {
21838            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21839                    component, TYPE_UNKNOWN, userId)) {
21840                return COMPONENT_ENABLED_STATE_DISABLED;
21841            }
21842            return mSettings.getComponentEnabledSettingLPr(component, userId);
21843        }
21844    }
21845
21846    @Override
21847    public void enterSafeMode() {
21848        enforceSystemOrRoot("Only the system can request entering safe mode");
21849
21850        if (!mSystemReady) {
21851            mSafeMode = true;
21852        }
21853    }
21854
21855    @Override
21856    public void systemReady() {
21857        enforceSystemOrRoot("Only the system can claim the system is ready");
21858
21859        mSystemReady = true;
21860        final ContentResolver resolver = mContext.getContentResolver();
21861        ContentObserver co = new ContentObserver(mHandler) {
21862            @Override
21863            public void onChange(boolean selfChange) {
21864                mEphemeralAppsDisabled =
21865                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21866                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21867            }
21868        };
21869        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21870                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21871                false, co, UserHandle.USER_SYSTEM);
21872        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21873                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21874        co.onChange(true);
21875
21876        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21877        // disabled after already being started.
21878        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21879                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21880
21881        // Read the compatibilty setting when the system is ready.
21882        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21883                mContext.getContentResolver(),
21884                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21885        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21886        if (DEBUG_SETTINGS) {
21887            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21888        }
21889
21890        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21891
21892        synchronized (mPackages) {
21893            // Verify that all of the preferred activity components actually
21894            // exist.  It is possible for applications to be updated and at
21895            // that point remove a previously declared activity component that
21896            // had been set as a preferred activity.  We try to clean this up
21897            // the next time we encounter that preferred activity, but it is
21898            // possible for the user flow to never be able to return to that
21899            // situation so here we do a sanity check to make sure we haven't
21900            // left any junk around.
21901            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21902            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21903                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21904                removed.clear();
21905                for (PreferredActivity pa : pir.filterSet()) {
21906                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21907                        removed.add(pa);
21908                    }
21909                }
21910                if (removed.size() > 0) {
21911                    for (int r=0; r<removed.size(); r++) {
21912                        PreferredActivity pa = removed.get(r);
21913                        Slog.w(TAG, "Removing dangling preferred activity: "
21914                                + pa.mPref.mComponent);
21915                        pir.removeFilter(pa);
21916                    }
21917                    mSettings.writePackageRestrictionsLPr(
21918                            mSettings.mPreferredActivities.keyAt(i));
21919                }
21920            }
21921
21922            for (int userId : UserManagerService.getInstance().getUserIds()) {
21923                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21924                    grantPermissionsUserIds = ArrayUtils.appendInt(
21925                            grantPermissionsUserIds, userId);
21926                }
21927            }
21928        }
21929        sUserManager.systemReady();
21930
21931        // If we upgraded grant all default permissions before kicking off.
21932        for (int userId : grantPermissionsUserIds) {
21933            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21934        }
21935
21936        // If we did not grant default permissions, we preload from this the
21937        // default permission exceptions lazily to ensure we don't hit the
21938        // disk on a new user creation.
21939        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21940            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21941        }
21942
21943        // Kick off any messages waiting for system ready
21944        if (mPostSystemReadyMessages != null) {
21945            for (Message msg : mPostSystemReadyMessages) {
21946                msg.sendToTarget();
21947            }
21948            mPostSystemReadyMessages = null;
21949        }
21950
21951        // Watch for external volumes that come and go over time
21952        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21953        storage.registerListener(mStorageListener);
21954
21955        mInstallerService.systemReady();
21956        mPackageDexOptimizer.systemReady();
21957
21958        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21959                StorageManagerInternal.class);
21960        StorageManagerInternal.addExternalStoragePolicy(
21961                new StorageManagerInternal.ExternalStorageMountPolicy() {
21962            @Override
21963            public int getMountMode(int uid, String packageName) {
21964                if (Process.isIsolated(uid)) {
21965                    return Zygote.MOUNT_EXTERNAL_NONE;
21966                }
21967                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21968                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21969                }
21970                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21971                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21972                }
21973                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21974                    return Zygote.MOUNT_EXTERNAL_READ;
21975                }
21976                return Zygote.MOUNT_EXTERNAL_WRITE;
21977            }
21978
21979            @Override
21980            public boolean hasExternalStorage(int uid, String packageName) {
21981                return true;
21982            }
21983        });
21984
21985        // Now that we're mostly running, clean up stale users and apps
21986        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21987        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21988
21989        if (mPrivappPermissionsViolations != null) {
21990            Slog.wtf(TAG,"Signature|privileged permissions not in "
21991                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21992            mPrivappPermissionsViolations = null;
21993        }
21994    }
21995
21996    public void waitForAppDataPrepared() {
21997        if (mPrepareAppDataFuture == null) {
21998            return;
21999        }
22000        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22001        mPrepareAppDataFuture = null;
22002    }
22003
22004    @Override
22005    public boolean isSafeMode() {
22006        // allow instant applications
22007        return mSafeMode;
22008    }
22009
22010    @Override
22011    public boolean hasSystemUidErrors() {
22012        // allow instant applications
22013        return mHasSystemUidErrors;
22014    }
22015
22016    static String arrayToString(int[] array) {
22017        StringBuffer buf = new StringBuffer(128);
22018        buf.append('[');
22019        if (array != null) {
22020            for (int i=0; i<array.length; i++) {
22021                if (i > 0) buf.append(", ");
22022                buf.append(array[i]);
22023            }
22024        }
22025        buf.append(']');
22026        return buf.toString();
22027    }
22028
22029    static class DumpState {
22030        public static final int DUMP_LIBS = 1 << 0;
22031        public static final int DUMP_FEATURES = 1 << 1;
22032        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22033        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22034        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22035        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22036        public static final int DUMP_PERMISSIONS = 1 << 6;
22037        public static final int DUMP_PACKAGES = 1 << 7;
22038        public static final int DUMP_SHARED_USERS = 1 << 8;
22039        public static final int DUMP_MESSAGES = 1 << 9;
22040        public static final int DUMP_PROVIDERS = 1 << 10;
22041        public static final int DUMP_VERIFIERS = 1 << 11;
22042        public static final int DUMP_PREFERRED = 1 << 12;
22043        public static final int DUMP_PREFERRED_XML = 1 << 13;
22044        public static final int DUMP_KEYSETS = 1 << 14;
22045        public static final int DUMP_VERSION = 1 << 15;
22046        public static final int DUMP_INSTALLS = 1 << 16;
22047        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22048        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22049        public static final int DUMP_FROZEN = 1 << 19;
22050        public static final int DUMP_DEXOPT = 1 << 20;
22051        public static final int DUMP_COMPILER_STATS = 1 << 21;
22052        public static final int DUMP_CHANGES = 1 << 22;
22053        public static final int DUMP_VOLUMES = 1 << 23;
22054
22055        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22056
22057        private int mTypes;
22058
22059        private int mOptions;
22060
22061        private boolean mTitlePrinted;
22062
22063        private SharedUserSetting mSharedUser;
22064
22065        public boolean isDumping(int type) {
22066            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22067                return true;
22068            }
22069
22070            return (mTypes & type) != 0;
22071        }
22072
22073        public void setDump(int type) {
22074            mTypes |= type;
22075        }
22076
22077        public boolean isOptionEnabled(int option) {
22078            return (mOptions & option) != 0;
22079        }
22080
22081        public void setOptionEnabled(int option) {
22082            mOptions |= option;
22083        }
22084
22085        public boolean onTitlePrinted() {
22086            final boolean printed = mTitlePrinted;
22087            mTitlePrinted = true;
22088            return printed;
22089        }
22090
22091        public boolean getTitlePrinted() {
22092            return mTitlePrinted;
22093        }
22094
22095        public void setTitlePrinted(boolean enabled) {
22096            mTitlePrinted = enabled;
22097        }
22098
22099        public SharedUserSetting getSharedUser() {
22100            return mSharedUser;
22101        }
22102
22103        public void setSharedUser(SharedUserSetting user) {
22104            mSharedUser = user;
22105        }
22106    }
22107
22108    @Override
22109    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22110            FileDescriptor err, String[] args, ShellCallback callback,
22111            ResultReceiver resultReceiver) {
22112        (new PackageManagerShellCommand(this)).exec(
22113                this, in, out, err, args, callback, resultReceiver);
22114    }
22115
22116    @Override
22117    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22118        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22119
22120        DumpState dumpState = new DumpState();
22121        boolean fullPreferred = false;
22122        boolean checkin = false;
22123
22124        String packageName = null;
22125        ArraySet<String> permissionNames = null;
22126
22127        int opti = 0;
22128        while (opti < args.length) {
22129            String opt = args[opti];
22130            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22131                break;
22132            }
22133            opti++;
22134
22135            if ("-a".equals(opt)) {
22136                // Right now we only know how to print all.
22137            } else if ("-h".equals(opt)) {
22138                pw.println("Package manager dump options:");
22139                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22140                pw.println("    --checkin: dump for a checkin");
22141                pw.println("    -f: print details of intent filters");
22142                pw.println("    -h: print this help");
22143                pw.println("  cmd may be one of:");
22144                pw.println("    l[ibraries]: list known shared libraries");
22145                pw.println("    f[eatures]: list device features");
22146                pw.println("    k[eysets]: print known keysets");
22147                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22148                pw.println("    perm[issions]: dump permissions");
22149                pw.println("    permission [name ...]: dump declaration and use of given permission");
22150                pw.println("    pref[erred]: print preferred package settings");
22151                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22152                pw.println("    prov[iders]: dump content providers");
22153                pw.println("    p[ackages]: dump installed packages");
22154                pw.println("    s[hared-users]: dump shared user IDs");
22155                pw.println("    m[essages]: print collected runtime messages");
22156                pw.println("    v[erifiers]: print package verifier info");
22157                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22158                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22159                pw.println("    version: print database version info");
22160                pw.println("    write: write current settings now");
22161                pw.println("    installs: details about install sessions");
22162                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22163                pw.println("    dexopt: dump dexopt state");
22164                pw.println("    compiler-stats: dump compiler statistics");
22165                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22166                pw.println("    <package.name>: info about given package");
22167                return;
22168            } else if ("--checkin".equals(opt)) {
22169                checkin = true;
22170            } else if ("-f".equals(opt)) {
22171                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22172            } else if ("--proto".equals(opt)) {
22173                dumpProto(fd);
22174                return;
22175            } else {
22176                pw.println("Unknown argument: " + opt + "; use -h for help");
22177            }
22178        }
22179
22180        // Is the caller requesting to dump a particular piece of data?
22181        if (opti < args.length) {
22182            String cmd = args[opti];
22183            opti++;
22184            // Is this a package name?
22185            if ("android".equals(cmd) || cmd.contains(".")) {
22186                packageName = cmd;
22187                // When dumping a single package, we always dump all of its
22188                // filter information since the amount of data will be reasonable.
22189                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22190            } else if ("check-permission".equals(cmd)) {
22191                if (opti >= args.length) {
22192                    pw.println("Error: check-permission missing permission argument");
22193                    return;
22194                }
22195                String perm = args[opti];
22196                opti++;
22197                if (opti >= args.length) {
22198                    pw.println("Error: check-permission missing package argument");
22199                    return;
22200                }
22201
22202                String pkg = args[opti];
22203                opti++;
22204                int user = UserHandle.getUserId(Binder.getCallingUid());
22205                if (opti < args.length) {
22206                    try {
22207                        user = Integer.parseInt(args[opti]);
22208                    } catch (NumberFormatException e) {
22209                        pw.println("Error: check-permission user argument is not a number: "
22210                                + args[opti]);
22211                        return;
22212                    }
22213                }
22214
22215                // Normalize package name to handle renamed packages and static libs
22216                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22217
22218                pw.println(checkPermission(perm, pkg, user));
22219                return;
22220            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22221                dumpState.setDump(DumpState.DUMP_LIBS);
22222            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22223                dumpState.setDump(DumpState.DUMP_FEATURES);
22224            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22225                if (opti >= args.length) {
22226                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22227                            | DumpState.DUMP_SERVICE_RESOLVERS
22228                            | DumpState.DUMP_RECEIVER_RESOLVERS
22229                            | DumpState.DUMP_CONTENT_RESOLVERS);
22230                } else {
22231                    while (opti < args.length) {
22232                        String name = args[opti];
22233                        if ("a".equals(name) || "activity".equals(name)) {
22234                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22235                        } else if ("s".equals(name) || "service".equals(name)) {
22236                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22237                        } else if ("r".equals(name) || "receiver".equals(name)) {
22238                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22239                        } else if ("c".equals(name) || "content".equals(name)) {
22240                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22241                        } else {
22242                            pw.println("Error: unknown resolver table type: " + name);
22243                            return;
22244                        }
22245                        opti++;
22246                    }
22247                }
22248            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22249                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22250            } else if ("permission".equals(cmd)) {
22251                if (opti >= args.length) {
22252                    pw.println("Error: permission requires permission name");
22253                    return;
22254                }
22255                permissionNames = new ArraySet<>();
22256                while (opti < args.length) {
22257                    permissionNames.add(args[opti]);
22258                    opti++;
22259                }
22260                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22261                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22262            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22263                dumpState.setDump(DumpState.DUMP_PREFERRED);
22264            } else if ("preferred-xml".equals(cmd)) {
22265                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22266                if (opti < args.length && "--full".equals(args[opti])) {
22267                    fullPreferred = true;
22268                    opti++;
22269                }
22270            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22271                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22272            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22273                dumpState.setDump(DumpState.DUMP_PACKAGES);
22274            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22275                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22276            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22277                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22278            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22279                dumpState.setDump(DumpState.DUMP_MESSAGES);
22280            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22281                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22282            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22283                    || "intent-filter-verifiers".equals(cmd)) {
22284                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22285            } else if ("version".equals(cmd)) {
22286                dumpState.setDump(DumpState.DUMP_VERSION);
22287            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22288                dumpState.setDump(DumpState.DUMP_KEYSETS);
22289            } else if ("installs".equals(cmd)) {
22290                dumpState.setDump(DumpState.DUMP_INSTALLS);
22291            } else if ("frozen".equals(cmd)) {
22292                dumpState.setDump(DumpState.DUMP_FROZEN);
22293            } else if ("volumes".equals(cmd)) {
22294                dumpState.setDump(DumpState.DUMP_VOLUMES);
22295            } else if ("dexopt".equals(cmd)) {
22296                dumpState.setDump(DumpState.DUMP_DEXOPT);
22297            } else if ("compiler-stats".equals(cmd)) {
22298                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22299            } else if ("changes".equals(cmd)) {
22300                dumpState.setDump(DumpState.DUMP_CHANGES);
22301            } else if ("write".equals(cmd)) {
22302                synchronized (mPackages) {
22303                    mSettings.writeLPr();
22304                    pw.println("Settings written.");
22305                    return;
22306                }
22307            }
22308        }
22309
22310        if (checkin) {
22311            pw.println("vers,1");
22312        }
22313
22314        // reader
22315        synchronized (mPackages) {
22316            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22317                if (!checkin) {
22318                    if (dumpState.onTitlePrinted())
22319                        pw.println();
22320                    pw.println("Database versions:");
22321                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22322                }
22323            }
22324
22325            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22326                if (!checkin) {
22327                    if (dumpState.onTitlePrinted())
22328                        pw.println();
22329                    pw.println("Verifiers:");
22330                    pw.print("  Required: ");
22331                    pw.print(mRequiredVerifierPackage);
22332                    pw.print(" (uid=");
22333                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22334                            UserHandle.USER_SYSTEM));
22335                    pw.println(")");
22336                } else if (mRequiredVerifierPackage != null) {
22337                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22338                    pw.print(",");
22339                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22340                            UserHandle.USER_SYSTEM));
22341                }
22342            }
22343
22344            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22345                    packageName == null) {
22346                if (mIntentFilterVerifierComponent != null) {
22347                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22348                    if (!checkin) {
22349                        if (dumpState.onTitlePrinted())
22350                            pw.println();
22351                        pw.println("Intent Filter Verifier:");
22352                        pw.print("  Using: ");
22353                        pw.print(verifierPackageName);
22354                        pw.print(" (uid=");
22355                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22356                                UserHandle.USER_SYSTEM));
22357                        pw.println(")");
22358                    } else if (verifierPackageName != null) {
22359                        pw.print("ifv,"); pw.print(verifierPackageName);
22360                        pw.print(",");
22361                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22362                                UserHandle.USER_SYSTEM));
22363                    }
22364                } else {
22365                    pw.println();
22366                    pw.println("No Intent Filter Verifier available!");
22367                }
22368            }
22369
22370            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22371                boolean printedHeader = false;
22372                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22373                while (it.hasNext()) {
22374                    String libName = it.next();
22375                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22376                    if (versionedLib == null) {
22377                        continue;
22378                    }
22379                    final int versionCount = versionedLib.size();
22380                    for (int i = 0; i < versionCount; i++) {
22381                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22382                        if (!checkin) {
22383                            if (!printedHeader) {
22384                                if (dumpState.onTitlePrinted())
22385                                    pw.println();
22386                                pw.println("Libraries:");
22387                                printedHeader = true;
22388                            }
22389                            pw.print("  ");
22390                        } else {
22391                            pw.print("lib,");
22392                        }
22393                        pw.print(libEntry.info.getName());
22394                        if (libEntry.info.isStatic()) {
22395                            pw.print(" version=" + libEntry.info.getVersion());
22396                        }
22397                        if (!checkin) {
22398                            pw.print(" -> ");
22399                        }
22400                        if (libEntry.path != null) {
22401                            pw.print(" (jar) ");
22402                            pw.print(libEntry.path);
22403                        } else {
22404                            pw.print(" (apk) ");
22405                            pw.print(libEntry.apk);
22406                        }
22407                        pw.println();
22408                    }
22409                }
22410            }
22411
22412            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22413                if (dumpState.onTitlePrinted())
22414                    pw.println();
22415                if (!checkin) {
22416                    pw.println("Features:");
22417                }
22418
22419                synchronized (mAvailableFeatures) {
22420                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22421                        if (checkin) {
22422                            pw.print("feat,");
22423                            pw.print(feat.name);
22424                            pw.print(",");
22425                            pw.println(feat.version);
22426                        } else {
22427                            pw.print("  ");
22428                            pw.print(feat.name);
22429                            if (feat.version > 0) {
22430                                pw.print(" version=");
22431                                pw.print(feat.version);
22432                            }
22433                            pw.println();
22434                        }
22435                    }
22436                }
22437            }
22438
22439            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22440                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22441                        : "Activity Resolver Table:", "  ", packageName,
22442                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22443                    dumpState.setTitlePrinted(true);
22444                }
22445            }
22446            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22447                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22448                        : "Receiver Resolver Table:", "  ", packageName,
22449                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22450                    dumpState.setTitlePrinted(true);
22451                }
22452            }
22453            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22454                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22455                        : "Service Resolver Table:", "  ", packageName,
22456                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22457                    dumpState.setTitlePrinted(true);
22458                }
22459            }
22460            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22461                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22462                        : "Provider Resolver Table:", "  ", packageName,
22463                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22464                    dumpState.setTitlePrinted(true);
22465                }
22466            }
22467
22468            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22469                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22470                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22471                    int user = mSettings.mPreferredActivities.keyAt(i);
22472                    if (pir.dump(pw,
22473                            dumpState.getTitlePrinted()
22474                                ? "\nPreferred Activities User " + user + ":"
22475                                : "Preferred Activities User " + user + ":", "  ",
22476                            packageName, true, false)) {
22477                        dumpState.setTitlePrinted(true);
22478                    }
22479                }
22480            }
22481
22482            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22483                pw.flush();
22484                FileOutputStream fout = new FileOutputStream(fd);
22485                BufferedOutputStream str = new BufferedOutputStream(fout);
22486                XmlSerializer serializer = new FastXmlSerializer();
22487                try {
22488                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22489                    serializer.startDocument(null, true);
22490                    serializer.setFeature(
22491                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22492                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22493                    serializer.endDocument();
22494                    serializer.flush();
22495                } catch (IllegalArgumentException e) {
22496                    pw.println("Failed writing: " + e);
22497                } catch (IllegalStateException e) {
22498                    pw.println("Failed writing: " + e);
22499                } catch (IOException e) {
22500                    pw.println("Failed writing: " + e);
22501                }
22502            }
22503
22504            if (!checkin
22505                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22506                    && packageName == null) {
22507                pw.println();
22508                int count = mSettings.mPackages.size();
22509                if (count == 0) {
22510                    pw.println("No applications!");
22511                    pw.println();
22512                } else {
22513                    final String prefix = "  ";
22514                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22515                    if (allPackageSettings.size() == 0) {
22516                        pw.println("No domain preferred apps!");
22517                        pw.println();
22518                    } else {
22519                        pw.println("App verification status:");
22520                        pw.println();
22521                        count = 0;
22522                        for (PackageSetting ps : allPackageSettings) {
22523                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22524                            if (ivi == null || ivi.getPackageName() == null) continue;
22525                            pw.println(prefix + "Package: " + ivi.getPackageName());
22526                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22527                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22528                            pw.println();
22529                            count++;
22530                        }
22531                        if (count == 0) {
22532                            pw.println(prefix + "No app verification established.");
22533                            pw.println();
22534                        }
22535                        for (int userId : sUserManager.getUserIds()) {
22536                            pw.println("App linkages for user " + userId + ":");
22537                            pw.println();
22538                            count = 0;
22539                            for (PackageSetting ps : allPackageSettings) {
22540                                final long status = ps.getDomainVerificationStatusForUser(userId);
22541                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22542                                        && !DEBUG_DOMAIN_VERIFICATION) {
22543                                    continue;
22544                                }
22545                                pw.println(prefix + "Package: " + ps.name);
22546                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22547                                String statusStr = IntentFilterVerificationInfo.
22548                                        getStatusStringFromValue(status);
22549                                pw.println(prefix + "Status:  " + statusStr);
22550                                pw.println();
22551                                count++;
22552                            }
22553                            if (count == 0) {
22554                                pw.println(prefix + "No configured app linkages.");
22555                                pw.println();
22556                            }
22557                        }
22558                    }
22559                }
22560            }
22561
22562            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22563                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22564                if (packageName == null && permissionNames == null) {
22565                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22566                        if (iperm == 0) {
22567                            if (dumpState.onTitlePrinted())
22568                                pw.println();
22569                            pw.println("AppOp Permissions:");
22570                        }
22571                        pw.print("  AppOp Permission ");
22572                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22573                        pw.println(":");
22574                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22575                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22576                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22577                        }
22578                    }
22579                }
22580            }
22581
22582            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22583                boolean printedSomething = false;
22584                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22585                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22586                        continue;
22587                    }
22588                    if (!printedSomething) {
22589                        if (dumpState.onTitlePrinted())
22590                            pw.println();
22591                        pw.println("Registered ContentProviders:");
22592                        printedSomething = true;
22593                    }
22594                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22595                    pw.print("    "); pw.println(p.toString());
22596                }
22597                printedSomething = false;
22598                for (Map.Entry<String, PackageParser.Provider> entry :
22599                        mProvidersByAuthority.entrySet()) {
22600                    PackageParser.Provider p = entry.getValue();
22601                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22602                        continue;
22603                    }
22604                    if (!printedSomething) {
22605                        if (dumpState.onTitlePrinted())
22606                            pw.println();
22607                        pw.println("ContentProvider Authorities:");
22608                        printedSomething = true;
22609                    }
22610                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22611                    pw.print("    "); pw.println(p.toString());
22612                    if (p.info != null && p.info.applicationInfo != null) {
22613                        final String appInfo = p.info.applicationInfo.toString();
22614                        pw.print("      applicationInfo="); pw.println(appInfo);
22615                    }
22616                }
22617            }
22618
22619            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22620                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22621            }
22622
22623            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22624                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22625            }
22626
22627            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22628                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22629            }
22630
22631            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22632                if (dumpState.onTitlePrinted()) pw.println();
22633                pw.println("Package Changes:");
22634                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22635                final int K = mChangedPackages.size();
22636                for (int i = 0; i < K; i++) {
22637                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22638                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22639                    final int N = changes.size();
22640                    if (N == 0) {
22641                        pw.print("    "); pw.println("No packages changed");
22642                    } else {
22643                        for (int j = 0; j < N; j++) {
22644                            final String pkgName = changes.valueAt(j);
22645                            final int sequenceNumber = changes.keyAt(j);
22646                            pw.print("    ");
22647                            pw.print("seq=");
22648                            pw.print(sequenceNumber);
22649                            pw.print(", package=");
22650                            pw.println(pkgName);
22651                        }
22652                    }
22653                }
22654            }
22655
22656            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22657                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22658            }
22659
22660            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22661                // XXX should handle packageName != null by dumping only install data that
22662                // the given package is involved with.
22663                if (dumpState.onTitlePrinted()) pw.println();
22664
22665                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22666                ipw.println();
22667                ipw.println("Frozen packages:");
22668                ipw.increaseIndent();
22669                if (mFrozenPackages.size() == 0) {
22670                    ipw.println("(none)");
22671                } else {
22672                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22673                        ipw.println(mFrozenPackages.valueAt(i));
22674                    }
22675                }
22676                ipw.decreaseIndent();
22677            }
22678
22679            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22680                if (dumpState.onTitlePrinted()) pw.println();
22681
22682                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22683                ipw.println();
22684                ipw.println("Loaded volumes:");
22685                ipw.increaseIndent();
22686                if (mLoadedVolumes.size() == 0) {
22687                    ipw.println("(none)");
22688                } else {
22689                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22690                        ipw.println(mLoadedVolumes.valueAt(i));
22691                    }
22692                }
22693                ipw.decreaseIndent();
22694            }
22695
22696            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22697                if (dumpState.onTitlePrinted()) pw.println();
22698                dumpDexoptStateLPr(pw, packageName);
22699            }
22700
22701            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22702                if (dumpState.onTitlePrinted()) pw.println();
22703                dumpCompilerStatsLPr(pw, packageName);
22704            }
22705
22706            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22707                if (dumpState.onTitlePrinted()) pw.println();
22708                mSettings.dumpReadMessagesLPr(pw, dumpState);
22709
22710                pw.println();
22711                pw.println("Package warning messages:");
22712                BufferedReader in = null;
22713                String line = null;
22714                try {
22715                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22716                    while ((line = in.readLine()) != null) {
22717                        if (line.contains("ignored: updated version")) continue;
22718                        pw.println(line);
22719                    }
22720                } catch (IOException ignored) {
22721                } finally {
22722                    IoUtils.closeQuietly(in);
22723                }
22724            }
22725
22726            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22727                BufferedReader in = null;
22728                String line = null;
22729                try {
22730                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22731                    while ((line = in.readLine()) != null) {
22732                        if (line.contains("ignored: updated version")) continue;
22733                        pw.print("msg,");
22734                        pw.println(line);
22735                    }
22736                } catch (IOException ignored) {
22737                } finally {
22738                    IoUtils.closeQuietly(in);
22739                }
22740            }
22741        }
22742
22743        // PackageInstaller should be called outside of mPackages lock
22744        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22745            // XXX should handle packageName != null by dumping only install data that
22746            // the given package is involved with.
22747            if (dumpState.onTitlePrinted()) pw.println();
22748            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22749        }
22750    }
22751
22752    private void dumpProto(FileDescriptor fd) {
22753        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22754
22755        synchronized (mPackages) {
22756            final long requiredVerifierPackageToken =
22757                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22758            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22759            proto.write(
22760                    PackageServiceDumpProto.PackageShortProto.UID,
22761                    getPackageUid(
22762                            mRequiredVerifierPackage,
22763                            MATCH_DEBUG_TRIAGED_MISSING,
22764                            UserHandle.USER_SYSTEM));
22765            proto.end(requiredVerifierPackageToken);
22766
22767            if (mIntentFilterVerifierComponent != null) {
22768                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22769                final long verifierPackageToken =
22770                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22771                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22772                proto.write(
22773                        PackageServiceDumpProto.PackageShortProto.UID,
22774                        getPackageUid(
22775                                verifierPackageName,
22776                                MATCH_DEBUG_TRIAGED_MISSING,
22777                                UserHandle.USER_SYSTEM));
22778                proto.end(verifierPackageToken);
22779            }
22780
22781            dumpSharedLibrariesProto(proto);
22782            dumpFeaturesProto(proto);
22783            mSettings.dumpPackagesProto(proto);
22784            mSettings.dumpSharedUsersProto(proto);
22785            dumpMessagesProto(proto);
22786        }
22787        proto.flush();
22788    }
22789
22790    private void dumpMessagesProto(ProtoOutputStream proto) {
22791        BufferedReader in = null;
22792        String line = null;
22793        try {
22794            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22795            while ((line = in.readLine()) != null) {
22796                if (line.contains("ignored: updated version")) continue;
22797                proto.write(PackageServiceDumpProto.MESSAGES, line);
22798            }
22799        } catch (IOException ignored) {
22800        } finally {
22801            IoUtils.closeQuietly(in);
22802        }
22803    }
22804
22805    private void dumpFeaturesProto(ProtoOutputStream proto) {
22806        synchronized (mAvailableFeatures) {
22807            final int count = mAvailableFeatures.size();
22808            for (int i = 0; i < count; i++) {
22809                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22810                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22811                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22812                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22813                proto.end(featureToken);
22814            }
22815        }
22816    }
22817
22818    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22819        final int count = mSharedLibraries.size();
22820        for (int i = 0; i < count; i++) {
22821            final String libName = mSharedLibraries.keyAt(i);
22822            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22823            if (versionedLib == null) {
22824                continue;
22825            }
22826            final int versionCount = versionedLib.size();
22827            for (int j = 0; j < versionCount; j++) {
22828                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22829                final long sharedLibraryToken =
22830                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22831                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22832                final boolean isJar = (libEntry.path != null);
22833                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22834                if (isJar) {
22835                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22836                } else {
22837                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22838                }
22839                proto.end(sharedLibraryToken);
22840            }
22841        }
22842    }
22843
22844    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22845        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22846        ipw.println();
22847        ipw.println("Dexopt state:");
22848        ipw.increaseIndent();
22849        Collection<PackageParser.Package> packages = null;
22850        if (packageName != null) {
22851            PackageParser.Package targetPackage = mPackages.get(packageName);
22852            if (targetPackage != null) {
22853                packages = Collections.singletonList(targetPackage);
22854            } else {
22855                ipw.println("Unable to find package: " + packageName);
22856                return;
22857            }
22858        } else {
22859            packages = mPackages.values();
22860        }
22861
22862        for (PackageParser.Package pkg : packages) {
22863            ipw.println("[" + pkg.packageName + "]");
22864            ipw.increaseIndent();
22865            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22866            ipw.decreaseIndent();
22867        }
22868    }
22869
22870    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22871        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22872        ipw.println();
22873        ipw.println("Compiler stats:");
22874        ipw.increaseIndent();
22875        Collection<PackageParser.Package> packages = null;
22876        if (packageName != null) {
22877            PackageParser.Package targetPackage = mPackages.get(packageName);
22878            if (targetPackage != null) {
22879                packages = Collections.singletonList(targetPackage);
22880            } else {
22881                ipw.println("Unable to find package: " + packageName);
22882                return;
22883            }
22884        } else {
22885            packages = mPackages.values();
22886        }
22887
22888        for (PackageParser.Package pkg : packages) {
22889            ipw.println("[" + pkg.packageName + "]");
22890            ipw.increaseIndent();
22891
22892            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22893            if (stats == null) {
22894                ipw.println("(No recorded stats)");
22895            } else {
22896                stats.dump(ipw);
22897            }
22898            ipw.decreaseIndent();
22899        }
22900    }
22901
22902    private String dumpDomainString(String packageName) {
22903        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22904                .getList();
22905        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22906
22907        ArraySet<String> result = new ArraySet<>();
22908        if (iviList.size() > 0) {
22909            for (IntentFilterVerificationInfo ivi : iviList) {
22910                for (String host : ivi.getDomains()) {
22911                    result.add(host);
22912                }
22913            }
22914        }
22915        if (filters != null && filters.size() > 0) {
22916            for (IntentFilter filter : filters) {
22917                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22918                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22919                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22920                    result.addAll(filter.getHostsList());
22921                }
22922            }
22923        }
22924
22925        StringBuilder sb = new StringBuilder(result.size() * 16);
22926        for (String domain : result) {
22927            if (sb.length() > 0) sb.append(" ");
22928            sb.append(domain);
22929        }
22930        return sb.toString();
22931    }
22932
22933    // ------- apps on sdcard specific code -------
22934    static final boolean DEBUG_SD_INSTALL = false;
22935
22936    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22937
22938    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22939
22940    private boolean mMediaMounted = false;
22941
22942    static String getEncryptKey() {
22943        try {
22944            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22945                    SD_ENCRYPTION_KEYSTORE_NAME);
22946            if (sdEncKey == null) {
22947                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22948                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22949                if (sdEncKey == null) {
22950                    Slog.e(TAG, "Failed to create encryption keys");
22951                    return null;
22952                }
22953            }
22954            return sdEncKey;
22955        } catch (NoSuchAlgorithmException nsae) {
22956            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22957            return null;
22958        } catch (IOException ioe) {
22959            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22960            return null;
22961        }
22962    }
22963
22964    /*
22965     * Update media status on PackageManager.
22966     */
22967    @Override
22968    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22969        enforceSystemOrRoot("Media status can only be updated by the system");
22970        // reader; this apparently protects mMediaMounted, but should probably
22971        // be a different lock in that case.
22972        synchronized (mPackages) {
22973            Log.i(TAG, "Updating external media status from "
22974                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22975                    + (mediaStatus ? "mounted" : "unmounted"));
22976            if (DEBUG_SD_INSTALL)
22977                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22978                        + ", mMediaMounted=" + mMediaMounted);
22979            if (mediaStatus == mMediaMounted) {
22980                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22981                        : 0, -1);
22982                mHandler.sendMessage(msg);
22983                return;
22984            }
22985            mMediaMounted = mediaStatus;
22986        }
22987        // Queue up an async operation since the package installation may take a
22988        // little while.
22989        mHandler.post(new Runnable() {
22990            public void run() {
22991                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22992            }
22993        });
22994    }
22995
22996    /**
22997     * Called by StorageManagerService when the initial ASECs to scan are available.
22998     * Should block until all the ASEC containers are finished being scanned.
22999     */
23000    public void scanAvailableAsecs() {
23001        updateExternalMediaStatusInner(true, false, false);
23002    }
23003
23004    /*
23005     * Collect information of applications on external media, map them against
23006     * existing containers and update information based on current mount status.
23007     * Please note that we always have to report status if reportStatus has been
23008     * set to true especially when unloading packages.
23009     */
23010    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23011            boolean externalStorage) {
23012        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23013        int[] uidArr = EmptyArray.INT;
23014
23015        final String[] list = PackageHelper.getSecureContainerList();
23016        if (ArrayUtils.isEmpty(list)) {
23017            Log.i(TAG, "No secure containers found");
23018        } else {
23019            // Process list of secure containers and categorize them
23020            // as active or stale based on their package internal state.
23021
23022            // reader
23023            synchronized (mPackages) {
23024                for (String cid : list) {
23025                    // Leave stages untouched for now; installer service owns them
23026                    if (PackageInstallerService.isStageName(cid)) continue;
23027
23028                    if (DEBUG_SD_INSTALL)
23029                        Log.i(TAG, "Processing container " + cid);
23030                    String pkgName = getAsecPackageName(cid);
23031                    if (pkgName == null) {
23032                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23033                        continue;
23034                    }
23035                    if (DEBUG_SD_INSTALL)
23036                        Log.i(TAG, "Looking for pkg : " + pkgName);
23037
23038                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23039                    if (ps == null) {
23040                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23041                        continue;
23042                    }
23043
23044                    /*
23045                     * Skip packages that are not external if we're unmounting
23046                     * external storage.
23047                     */
23048                    if (externalStorage && !isMounted && !isExternal(ps)) {
23049                        continue;
23050                    }
23051
23052                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23053                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23054                    // The package status is changed only if the code path
23055                    // matches between settings and the container id.
23056                    if (ps.codePathString != null
23057                            && ps.codePathString.startsWith(args.getCodePath())) {
23058                        if (DEBUG_SD_INSTALL) {
23059                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23060                                    + " at code path: " + ps.codePathString);
23061                        }
23062
23063                        // We do have a valid package installed on sdcard
23064                        processCids.put(args, ps.codePathString);
23065                        final int uid = ps.appId;
23066                        if (uid != -1) {
23067                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23068                        }
23069                    } else {
23070                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23071                                + ps.codePathString);
23072                    }
23073                }
23074            }
23075
23076            Arrays.sort(uidArr);
23077        }
23078
23079        // Process packages with valid entries.
23080        if (isMounted) {
23081            if (DEBUG_SD_INSTALL)
23082                Log.i(TAG, "Loading packages");
23083            loadMediaPackages(processCids, uidArr, externalStorage);
23084            startCleaningPackages();
23085            mInstallerService.onSecureContainersAvailable();
23086        } else {
23087            if (DEBUG_SD_INSTALL)
23088                Log.i(TAG, "Unloading packages");
23089            unloadMediaPackages(processCids, uidArr, reportStatus);
23090        }
23091    }
23092
23093    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23094            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23095        final int size = infos.size();
23096        final String[] packageNames = new String[size];
23097        final int[] packageUids = new int[size];
23098        for (int i = 0; i < size; i++) {
23099            final ApplicationInfo info = infos.get(i);
23100            packageNames[i] = info.packageName;
23101            packageUids[i] = info.uid;
23102        }
23103        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23104                finishedReceiver);
23105    }
23106
23107    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23108            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23109        sendResourcesChangedBroadcast(mediaStatus, replacing,
23110                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23111    }
23112
23113    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23114            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23115        int size = pkgList.length;
23116        if (size > 0) {
23117            // Send broadcasts here
23118            Bundle extras = new Bundle();
23119            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23120            if (uidArr != null) {
23121                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23122            }
23123            if (replacing) {
23124                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23125            }
23126            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23127                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23128            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23129        }
23130    }
23131
23132   /*
23133     * Look at potentially valid container ids from processCids If package
23134     * information doesn't match the one on record or package scanning fails,
23135     * the cid is added to list of removeCids. We currently don't delete stale
23136     * containers.
23137     */
23138    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23139            boolean externalStorage) {
23140        ArrayList<String> pkgList = new ArrayList<String>();
23141        Set<AsecInstallArgs> keys = processCids.keySet();
23142
23143        for (AsecInstallArgs args : keys) {
23144            String codePath = processCids.get(args);
23145            if (DEBUG_SD_INSTALL)
23146                Log.i(TAG, "Loading container : " + args.cid);
23147            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23148            try {
23149                // Make sure there are no container errors first.
23150                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23151                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23152                            + " when installing from sdcard");
23153                    continue;
23154                }
23155                // Check code path here.
23156                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23157                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23158                            + " does not match one in settings " + codePath);
23159                    continue;
23160                }
23161                // Parse package
23162                int parseFlags = mDefParseFlags;
23163                if (args.isExternalAsec()) {
23164                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23165                }
23166                if (args.isFwdLocked()) {
23167                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23168                }
23169
23170                synchronized (mInstallLock) {
23171                    PackageParser.Package pkg = null;
23172                    try {
23173                        // Sadly we don't know the package name yet to freeze it
23174                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23175                                SCAN_IGNORE_FROZEN, 0, null);
23176                    } catch (PackageManagerException e) {
23177                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23178                    }
23179                    // Scan the package
23180                    if (pkg != null) {
23181                        /*
23182                         * TODO why is the lock being held? doPostInstall is
23183                         * called in other places without the lock. This needs
23184                         * to be straightened out.
23185                         */
23186                        // writer
23187                        synchronized (mPackages) {
23188                            retCode = PackageManager.INSTALL_SUCCEEDED;
23189                            pkgList.add(pkg.packageName);
23190                            // Post process args
23191                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23192                                    pkg.applicationInfo.uid);
23193                        }
23194                    } else {
23195                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23196                    }
23197                }
23198
23199            } finally {
23200                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23201                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23202                }
23203            }
23204        }
23205        // writer
23206        synchronized (mPackages) {
23207            // If the platform SDK has changed since the last time we booted,
23208            // we need to re-grant app permission to catch any new ones that
23209            // appear. This is really a hack, and means that apps can in some
23210            // cases get permissions that the user didn't initially explicitly
23211            // allow... it would be nice to have some better way to handle
23212            // this situation.
23213            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23214                    : mSettings.getInternalVersion();
23215            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23216                    : StorageManager.UUID_PRIVATE_INTERNAL;
23217
23218            int updateFlags = UPDATE_PERMISSIONS_ALL;
23219            if (ver.sdkVersion != mSdkVersion) {
23220                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23221                        + mSdkVersion + "; regranting permissions for external");
23222                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23223            }
23224            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23225
23226            // Yay, everything is now upgraded
23227            ver.forceCurrent();
23228
23229            // can downgrade to reader
23230            // Persist settings
23231            mSettings.writeLPr();
23232        }
23233        // Send a broadcast to let everyone know we are done processing
23234        if (pkgList.size() > 0) {
23235            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23236        }
23237    }
23238
23239   /*
23240     * Utility method to unload a list of specified containers
23241     */
23242    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23243        // Just unmount all valid containers.
23244        for (AsecInstallArgs arg : cidArgs) {
23245            synchronized (mInstallLock) {
23246                arg.doPostDeleteLI(false);
23247           }
23248       }
23249   }
23250
23251    /*
23252     * Unload packages mounted on external media. This involves deleting package
23253     * data from internal structures, sending broadcasts about disabled packages,
23254     * gc'ing to free up references, unmounting all secure containers
23255     * corresponding to packages on external media, and posting a
23256     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23257     * that we always have to post this message if status has been requested no
23258     * matter what.
23259     */
23260    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23261            final boolean reportStatus) {
23262        if (DEBUG_SD_INSTALL)
23263            Log.i(TAG, "unloading media packages");
23264        ArrayList<String> pkgList = new ArrayList<String>();
23265        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23266        final Set<AsecInstallArgs> keys = processCids.keySet();
23267        for (AsecInstallArgs args : keys) {
23268            String pkgName = args.getPackageName();
23269            if (DEBUG_SD_INSTALL)
23270                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23271            // Delete package internally
23272            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23273            synchronized (mInstallLock) {
23274                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23275                final boolean res;
23276                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23277                        "unloadMediaPackages")) {
23278                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23279                            null);
23280                }
23281                if (res) {
23282                    pkgList.add(pkgName);
23283                } else {
23284                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23285                    failedList.add(args);
23286                }
23287            }
23288        }
23289
23290        // reader
23291        synchronized (mPackages) {
23292            // We didn't update the settings after removing each package;
23293            // write them now for all packages.
23294            mSettings.writeLPr();
23295        }
23296
23297        // We have to absolutely send UPDATED_MEDIA_STATUS only
23298        // after confirming that all the receivers processed the ordered
23299        // broadcast when packages get disabled, force a gc to clean things up.
23300        // and unload all the containers.
23301        if (pkgList.size() > 0) {
23302            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23303                    new IIntentReceiver.Stub() {
23304                public void performReceive(Intent intent, int resultCode, String data,
23305                        Bundle extras, boolean ordered, boolean sticky,
23306                        int sendingUser) throws RemoteException {
23307                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23308                            reportStatus ? 1 : 0, 1, keys);
23309                    mHandler.sendMessage(msg);
23310                }
23311            });
23312        } else {
23313            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23314                    keys);
23315            mHandler.sendMessage(msg);
23316        }
23317    }
23318
23319    private void loadPrivatePackages(final VolumeInfo vol) {
23320        mHandler.post(new Runnable() {
23321            @Override
23322            public void run() {
23323                loadPrivatePackagesInner(vol);
23324            }
23325        });
23326    }
23327
23328    private void loadPrivatePackagesInner(VolumeInfo vol) {
23329        final String volumeUuid = vol.fsUuid;
23330        if (TextUtils.isEmpty(volumeUuid)) {
23331            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23332            return;
23333        }
23334
23335        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23336        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23337        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23338
23339        final VersionInfo ver;
23340        final List<PackageSetting> packages;
23341        synchronized (mPackages) {
23342            ver = mSettings.findOrCreateVersion(volumeUuid);
23343            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23344        }
23345
23346        for (PackageSetting ps : packages) {
23347            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23348            synchronized (mInstallLock) {
23349                final PackageParser.Package pkg;
23350                try {
23351                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23352                    loaded.add(pkg.applicationInfo);
23353
23354                } catch (PackageManagerException e) {
23355                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23356                }
23357
23358                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23359                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23360                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23361                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23362                }
23363            }
23364        }
23365
23366        // Reconcile app data for all started/unlocked users
23367        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23368        final UserManager um = mContext.getSystemService(UserManager.class);
23369        UserManagerInternal umInternal = getUserManagerInternal();
23370        for (UserInfo user : um.getUsers()) {
23371            final int flags;
23372            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23373                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23374            } else if (umInternal.isUserRunning(user.id)) {
23375                flags = StorageManager.FLAG_STORAGE_DE;
23376            } else {
23377                continue;
23378            }
23379
23380            try {
23381                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23382                synchronized (mInstallLock) {
23383                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23384                }
23385            } catch (IllegalStateException e) {
23386                // Device was probably ejected, and we'll process that event momentarily
23387                Slog.w(TAG, "Failed to prepare storage: " + e);
23388            }
23389        }
23390
23391        synchronized (mPackages) {
23392            int updateFlags = UPDATE_PERMISSIONS_ALL;
23393            if (ver.sdkVersion != mSdkVersion) {
23394                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23395                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23396                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23397            }
23398            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23399
23400            // Yay, everything is now upgraded
23401            ver.forceCurrent();
23402
23403            mSettings.writeLPr();
23404        }
23405
23406        for (PackageFreezer freezer : freezers) {
23407            freezer.close();
23408        }
23409
23410        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23411        sendResourcesChangedBroadcast(true, false, loaded, null);
23412        mLoadedVolumes.add(vol.getId());
23413    }
23414
23415    private void unloadPrivatePackages(final VolumeInfo vol) {
23416        mHandler.post(new Runnable() {
23417            @Override
23418            public void run() {
23419                unloadPrivatePackagesInner(vol);
23420            }
23421        });
23422    }
23423
23424    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23425        final String volumeUuid = vol.fsUuid;
23426        if (TextUtils.isEmpty(volumeUuid)) {
23427            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23428            return;
23429        }
23430
23431        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23432        synchronized (mInstallLock) {
23433        synchronized (mPackages) {
23434            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23435            for (PackageSetting ps : packages) {
23436                if (ps.pkg == null) continue;
23437
23438                final ApplicationInfo info = ps.pkg.applicationInfo;
23439                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23440                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23441
23442                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23443                        "unloadPrivatePackagesInner")) {
23444                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23445                            false, null)) {
23446                        unloaded.add(info);
23447                    } else {
23448                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23449                    }
23450                }
23451
23452                // Try very hard to release any references to this package
23453                // so we don't risk the system server being killed due to
23454                // open FDs
23455                AttributeCache.instance().removePackage(ps.name);
23456            }
23457
23458            mSettings.writeLPr();
23459        }
23460        }
23461
23462        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23463        sendResourcesChangedBroadcast(false, false, unloaded, null);
23464        mLoadedVolumes.remove(vol.getId());
23465
23466        // Try very hard to release any references to this path so we don't risk
23467        // the system server being killed due to open FDs
23468        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23469
23470        for (int i = 0; i < 3; i++) {
23471            System.gc();
23472            System.runFinalization();
23473        }
23474    }
23475
23476    private void assertPackageKnown(String volumeUuid, String packageName)
23477            throws PackageManagerException {
23478        synchronized (mPackages) {
23479            // Normalize package name to handle renamed packages
23480            packageName = normalizePackageNameLPr(packageName);
23481
23482            final PackageSetting ps = mSettings.mPackages.get(packageName);
23483            if (ps == null) {
23484                throw new PackageManagerException("Package " + packageName + " is unknown");
23485            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23486                throw new PackageManagerException(
23487                        "Package " + packageName + " found on unknown volume " + volumeUuid
23488                                + "; expected volume " + ps.volumeUuid);
23489            }
23490        }
23491    }
23492
23493    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23494            throws PackageManagerException {
23495        synchronized (mPackages) {
23496            // Normalize package name to handle renamed packages
23497            packageName = normalizePackageNameLPr(packageName);
23498
23499            final PackageSetting ps = mSettings.mPackages.get(packageName);
23500            if (ps == null) {
23501                throw new PackageManagerException("Package " + packageName + " is unknown");
23502            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23503                throw new PackageManagerException(
23504                        "Package " + packageName + " found on unknown volume " + volumeUuid
23505                                + "; expected volume " + ps.volumeUuid);
23506            } else if (!ps.getInstalled(userId)) {
23507                throw new PackageManagerException(
23508                        "Package " + packageName + " not installed for user " + userId);
23509            }
23510        }
23511    }
23512
23513    private List<String> collectAbsoluteCodePaths() {
23514        synchronized (mPackages) {
23515            List<String> codePaths = new ArrayList<>();
23516            final int packageCount = mSettings.mPackages.size();
23517            for (int i = 0; i < packageCount; i++) {
23518                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23519                codePaths.add(ps.codePath.getAbsolutePath());
23520            }
23521            return codePaths;
23522        }
23523    }
23524
23525    /**
23526     * Examine all apps present on given mounted volume, and destroy apps that
23527     * aren't expected, either due to uninstallation or reinstallation on
23528     * another volume.
23529     */
23530    private void reconcileApps(String volumeUuid) {
23531        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23532        List<File> filesToDelete = null;
23533
23534        final File[] files = FileUtils.listFilesOrEmpty(
23535                Environment.getDataAppDirectory(volumeUuid));
23536        for (File file : files) {
23537            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23538                    && !PackageInstallerService.isStageName(file.getName());
23539            if (!isPackage) {
23540                // Ignore entries which are not packages
23541                continue;
23542            }
23543
23544            String absolutePath = file.getAbsolutePath();
23545
23546            boolean pathValid = false;
23547            final int absoluteCodePathCount = absoluteCodePaths.size();
23548            for (int i = 0; i < absoluteCodePathCount; i++) {
23549                String absoluteCodePath = absoluteCodePaths.get(i);
23550                if (absolutePath.startsWith(absoluteCodePath)) {
23551                    pathValid = true;
23552                    break;
23553                }
23554            }
23555
23556            if (!pathValid) {
23557                if (filesToDelete == null) {
23558                    filesToDelete = new ArrayList<>();
23559                }
23560                filesToDelete.add(file);
23561            }
23562        }
23563
23564        if (filesToDelete != null) {
23565            final int fileToDeleteCount = filesToDelete.size();
23566            for (int i = 0; i < fileToDeleteCount; i++) {
23567                File fileToDelete = filesToDelete.get(i);
23568                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23569                synchronized (mInstallLock) {
23570                    removeCodePathLI(fileToDelete);
23571                }
23572            }
23573        }
23574    }
23575
23576    /**
23577     * Reconcile all app data for the given user.
23578     * <p>
23579     * Verifies that directories exist and that ownership and labeling is
23580     * correct for all installed apps on all mounted volumes.
23581     */
23582    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23583        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23584        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23585            final String volumeUuid = vol.getFsUuid();
23586            synchronized (mInstallLock) {
23587                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23588            }
23589        }
23590    }
23591
23592    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23593            boolean migrateAppData) {
23594        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23595    }
23596
23597    /**
23598     * Reconcile all app data on given mounted volume.
23599     * <p>
23600     * Destroys app data that isn't expected, either due to uninstallation or
23601     * reinstallation on another volume.
23602     * <p>
23603     * Verifies that directories exist and that ownership and labeling is
23604     * correct for all installed apps.
23605     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23606     */
23607    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23608            boolean migrateAppData, boolean onlyCoreApps) {
23609        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23610                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23611        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23612
23613        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23614        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23615
23616        // First look for stale data that doesn't belong, and check if things
23617        // have changed since we did our last restorecon
23618        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23619            if (StorageManager.isFileEncryptedNativeOrEmulated()
23620                    && !StorageManager.isUserKeyUnlocked(userId)) {
23621                throw new RuntimeException(
23622                        "Yikes, someone asked us to reconcile CE storage while " + userId
23623                                + " was still locked; this would have caused massive data loss!");
23624            }
23625
23626            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23627            for (File file : files) {
23628                final String packageName = file.getName();
23629                try {
23630                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23631                } catch (PackageManagerException e) {
23632                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23633                    try {
23634                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23635                                StorageManager.FLAG_STORAGE_CE, 0);
23636                    } catch (InstallerException e2) {
23637                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23638                    }
23639                }
23640            }
23641        }
23642        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23643            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23644            for (File file : files) {
23645                final String packageName = file.getName();
23646                try {
23647                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23648                } catch (PackageManagerException e) {
23649                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23650                    try {
23651                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23652                                StorageManager.FLAG_STORAGE_DE, 0);
23653                    } catch (InstallerException e2) {
23654                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23655                    }
23656                }
23657            }
23658        }
23659
23660        // Ensure that data directories are ready to roll for all packages
23661        // installed for this volume and user
23662        final List<PackageSetting> packages;
23663        synchronized (mPackages) {
23664            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23665        }
23666        int preparedCount = 0;
23667        for (PackageSetting ps : packages) {
23668            final String packageName = ps.name;
23669            if (ps.pkg == null) {
23670                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23671                // TODO: might be due to legacy ASEC apps; we should circle back
23672                // and reconcile again once they're scanned
23673                continue;
23674            }
23675            // Skip non-core apps if requested
23676            if (onlyCoreApps && !ps.pkg.coreApp) {
23677                result.add(packageName);
23678                continue;
23679            }
23680
23681            if (ps.getInstalled(userId)) {
23682                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23683                preparedCount++;
23684            }
23685        }
23686
23687        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23688        return result;
23689    }
23690
23691    /**
23692     * Prepare app data for the given app just after it was installed or
23693     * upgraded. This method carefully only touches users that it's installed
23694     * for, and it forces a restorecon to handle any seinfo changes.
23695     * <p>
23696     * Verifies that directories exist and that ownership and labeling is
23697     * correct for all installed apps. If there is an ownership mismatch, it
23698     * will try recovering system apps by wiping data; third-party app data is
23699     * left intact.
23700     * <p>
23701     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23702     */
23703    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23704        final PackageSetting ps;
23705        synchronized (mPackages) {
23706            ps = mSettings.mPackages.get(pkg.packageName);
23707            mSettings.writeKernelMappingLPr(ps);
23708        }
23709
23710        final UserManager um = mContext.getSystemService(UserManager.class);
23711        UserManagerInternal umInternal = getUserManagerInternal();
23712        for (UserInfo user : um.getUsers()) {
23713            final int flags;
23714            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23715                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23716            } else if (umInternal.isUserRunning(user.id)) {
23717                flags = StorageManager.FLAG_STORAGE_DE;
23718            } else {
23719                continue;
23720            }
23721
23722            if (ps.getInstalled(user.id)) {
23723                // TODO: when user data is locked, mark that we're still dirty
23724                prepareAppDataLIF(pkg, user.id, flags);
23725            }
23726        }
23727    }
23728
23729    /**
23730     * Prepare app data for the given app.
23731     * <p>
23732     * Verifies that directories exist and that ownership and labeling is
23733     * correct for all installed apps. If there is an ownership mismatch, this
23734     * will try recovering system apps by wiping data; third-party app data is
23735     * left intact.
23736     */
23737    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23738        if (pkg == null) {
23739            Slog.wtf(TAG, "Package was null!", new Throwable());
23740            return;
23741        }
23742        prepareAppDataLeafLIF(pkg, userId, flags);
23743        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23744        for (int i = 0; i < childCount; i++) {
23745            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23746        }
23747    }
23748
23749    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23750            boolean maybeMigrateAppData) {
23751        prepareAppDataLIF(pkg, userId, flags);
23752
23753        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23754            // We may have just shuffled around app data directories, so
23755            // prepare them one more time
23756            prepareAppDataLIF(pkg, userId, flags);
23757        }
23758    }
23759
23760    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23761        if (DEBUG_APP_DATA) {
23762            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23763                    + Integer.toHexString(flags));
23764        }
23765
23766        final String volumeUuid = pkg.volumeUuid;
23767        final String packageName = pkg.packageName;
23768        final ApplicationInfo app = pkg.applicationInfo;
23769        final int appId = UserHandle.getAppId(app.uid);
23770
23771        Preconditions.checkNotNull(app.seInfo);
23772
23773        long ceDataInode = -1;
23774        try {
23775            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23776                    appId, app.seInfo, app.targetSdkVersion);
23777        } catch (InstallerException e) {
23778            if (app.isSystemApp()) {
23779                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23780                        + ", but trying to recover: " + e);
23781                destroyAppDataLeafLIF(pkg, userId, flags);
23782                try {
23783                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23784                            appId, app.seInfo, app.targetSdkVersion);
23785                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23786                } catch (InstallerException e2) {
23787                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23788                }
23789            } else {
23790                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23791            }
23792        }
23793
23794        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23795            // TODO: mark this structure as dirty so we persist it!
23796            synchronized (mPackages) {
23797                final PackageSetting ps = mSettings.mPackages.get(packageName);
23798                if (ps != null) {
23799                    ps.setCeDataInode(ceDataInode, userId);
23800                }
23801            }
23802        }
23803
23804        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23805    }
23806
23807    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23808        if (pkg == null) {
23809            Slog.wtf(TAG, "Package was null!", new Throwable());
23810            return;
23811        }
23812        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23813        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23814        for (int i = 0; i < childCount; i++) {
23815            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23816        }
23817    }
23818
23819    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23820        final String volumeUuid = pkg.volumeUuid;
23821        final String packageName = pkg.packageName;
23822        final ApplicationInfo app = pkg.applicationInfo;
23823
23824        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23825            // Create a native library symlink only if we have native libraries
23826            // and if the native libraries are 32 bit libraries. We do not provide
23827            // this symlink for 64 bit libraries.
23828            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23829                final String nativeLibPath = app.nativeLibraryDir;
23830                try {
23831                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23832                            nativeLibPath, userId);
23833                } catch (InstallerException e) {
23834                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23835                }
23836            }
23837        }
23838    }
23839
23840    /**
23841     * For system apps on non-FBE devices, this method migrates any existing
23842     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23843     * requested by the app.
23844     */
23845    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23846        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23847                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23848            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23849                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23850            try {
23851                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23852                        storageTarget);
23853            } catch (InstallerException e) {
23854                logCriticalInfo(Log.WARN,
23855                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23856            }
23857            return true;
23858        } else {
23859            return false;
23860        }
23861    }
23862
23863    public PackageFreezer freezePackage(String packageName, String killReason) {
23864        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23865    }
23866
23867    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23868        return new PackageFreezer(packageName, userId, killReason);
23869    }
23870
23871    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23872            String killReason) {
23873        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23874    }
23875
23876    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23877            String killReason) {
23878        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23879            return new PackageFreezer();
23880        } else {
23881            return freezePackage(packageName, userId, killReason);
23882        }
23883    }
23884
23885    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23886            String killReason) {
23887        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23888    }
23889
23890    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23891            String killReason) {
23892        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23893            return new PackageFreezer();
23894        } else {
23895            return freezePackage(packageName, userId, killReason);
23896        }
23897    }
23898
23899    /**
23900     * Class that freezes and kills the given package upon creation, and
23901     * unfreezes it upon closing. This is typically used when doing surgery on
23902     * app code/data to prevent the app from running while you're working.
23903     */
23904    private class PackageFreezer implements AutoCloseable {
23905        private final String mPackageName;
23906        private final PackageFreezer[] mChildren;
23907
23908        private final boolean mWeFroze;
23909
23910        private final AtomicBoolean mClosed = new AtomicBoolean();
23911        private final CloseGuard mCloseGuard = CloseGuard.get();
23912
23913        /**
23914         * Create and return a stub freezer that doesn't actually do anything,
23915         * typically used when someone requested
23916         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23917         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23918         */
23919        public PackageFreezer() {
23920            mPackageName = null;
23921            mChildren = null;
23922            mWeFroze = false;
23923            mCloseGuard.open("close");
23924        }
23925
23926        public PackageFreezer(String packageName, int userId, String killReason) {
23927            synchronized (mPackages) {
23928                mPackageName = packageName;
23929                mWeFroze = mFrozenPackages.add(mPackageName);
23930
23931                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23932                if (ps != null) {
23933                    killApplication(ps.name, ps.appId, userId, killReason);
23934                }
23935
23936                final PackageParser.Package p = mPackages.get(packageName);
23937                if (p != null && p.childPackages != null) {
23938                    final int N = p.childPackages.size();
23939                    mChildren = new PackageFreezer[N];
23940                    for (int i = 0; i < N; i++) {
23941                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23942                                userId, killReason);
23943                    }
23944                } else {
23945                    mChildren = null;
23946                }
23947            }
23948            mCloseGuard.open("close");
23949        }
23950
23951        @Override
23952        protected void finalize() throws Throwable {
23953            try {
23954                if (mCloseGuard != null) {
23955                    mCloseGuard.warnIfOpen();
23956                }
23957
23958                close();
23959            } finally {
23960                super.finalize();
23961            }
23962        }
23963
23964        @Override
23965        public void close() {
23966            mCloseGuard.close();
23967            if (mClosed.compareAndSet(false, true)) {
23968                synchronized (mPackages) {
23969                    if (mWeFroze) {
23970                        mFrozenPackages.remove(mPackageName);
23971                    }
23972
23973                    if (mChildren != null) {
23974                        for (PackageFreezer freezer : mChildren) {
23975                            freezer.close();
23976                        }
23977                    }
23978                }
23979            }
23980        }
23981    }
23982
23983    /**
23984     * Verify that given package is currently frozen.
23985     */
23986    private void checkPackageFrozen(String packageName) {
23987        synchronized (mPackages) {
23988            if (!mFrozenPackages.contains(packageName)) {
23989                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23990            }
23991        }
23992    }
23993
23994    @Override
23995    public int movePackage(final String packageName, final String volumeUuid) {
23996        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23997
23998        final int callingUid = Binder.getCallingUid();
23999        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24000        final int moveId = mNextMoveId.getAndIncrement();
24001        mHandler.post(new Runnable() {
24002            @Override
24003            public void run() {
24004                try {
24005                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24006                } catch (PackageManagerException e) {
24007                    Slog.w(TAG, "Failed to move " + packageName, e);
24008                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24009                }
24010            }
24011        });
24012        return moveId;
24013    }
24014
24015    private void movePackageInternal(final String packageName, final String volumeUuid,
24016            final int moveId, final int callingUid, UserHandle user)
24017                    throws PackageManagerException {
24018        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24019        final PackageManager pm = mContext.getPackageManager();
24020
24021        final boolean currentAsec;
24022        final String currentVolumeUuid;
24023        final File codeFile;
24024        final String installerPackageName;
24025        final String packageAbiOverride;
24026        final int appId;
24027        final String seinfo;
24028        final String label;
24029        final int targetSdkVersion;
24030        final PackageFreezer freezer;
24031        final int[] installedUserIds;
24032
24033        // reader
24034        synchronized (mPackages) {
24035            final PackageParser.Package pkg = mPackages.get(packageName);
24036            final PackageSetting ps = mSettings.mPackages.get(packageName);
24037            if (pkg == null
24038                    || ps == null
24039                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24040                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24041            }
24042            if (pkg.applicationInfo.isSystemApp()) {
24043                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24044                        "Cannot move system application");
24045            }
24046
24047            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24048            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24049                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24050            if (isInternalStorage && !allow3rdPartyOnInternal) {
24051                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24052                        "3rd party apps are not allowed on internal storage");
24053            }
24054
24055            if (pkg.applicationInfo.isExternalAsec()) {
24056                currentAsec = true;
24057                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24058            } else if (pkg.applicationInfo.isForwardLocked()) {
24059                currentAsec = true;
24060                currentVolumeUuid = "forward_locked";
24061            } else {
24062                currentAsec = false;
24063                currentVolumeUuid = ps.volumeUuid;
24064
24065                final File probe = new File(pkg.codePath);
24066                final File probeOat = new File(probe, "oat");
24067                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24068                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24069                            "Move only supported for modern cluster style installs");
24070                }
24071            }
24072
24073            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24074                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24075                        "Package already moved to " + volumeUuid);
24076            }
24077            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24078                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24079                        "Device admin cannot be moved");
24080            }
24081
24082            if (mFrozenPackages.contains(packageName)) {
24083                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24084                        "Failed to move already frozen package");
24085            }
24086
24087            codeFile = new File(pkg.codePath);
24088            installerPackageName = ps.installerPackageName;
24089            packageAbiOverride = ps.cpuAbiOverrideString;
24090            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24091            seinfo = pkg.applicationInfo.seInfo;
24092            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24093            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24094            freezer = freezePackage(packageName, "movePackageInternal");
24095            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24096        }
24097
24098        final Bundle extras = new Bundle();
24099        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24100        extras.putString(Intent.EXTRA_TITLE, label);
24101        mMoveCallbacks.notifyCreated(moveId, extras);
24102
24103        int installFlags;
24104        final boolean moveCompleteApp;
24105        final File measurePath;
24106
24107        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24108            installFlags = INSTALL_INTERNAL;
24109            moveCompleteApp = !currentAsec;
24110            measurePath = Environment.getDataAppDirectory(volumeUuid);
24111        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24112            installFlags = INSTALL_EXTERNAL;
24113            moveCompleteApp = false;
24114            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24115        } else {
24116            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24117            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24118                    || !volume.isMountedWritable()) {
24119                freezer.close();
24120                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24121                        "Move location not mounted private volume");
24122            }
24123
24124            Preconditions.checkState(!currentAsec);
24125
24126            installFlags = INSTALL_INTERNAL;
24127            moveCompleteApp = true;
24128            measurePath = Environment.getDataAppDirectory(volumeUuid);
24129        }
24130
24131        // If we're moving app data around, we need all the users unlocked
24132        if (moveCompleteApp) {
24133            for (int userId : installedUserIds) {
24134                if (StorageManager.isFileEncryptedNativeOrEmulated()
24135                        && !StorageManager.isUserKeyUnlocked(userId)) {
24136                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24137                            "User " + userId + " must be unlocked");
24138                }
24139            }
24140        }
24141
24142        final PackageStats stats = new PackageStats(null, -1);
24143        synchronized (mInstaller) {
24144            for (int userId : installedUserIds) {
24145                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24146                    freezer.close();
24147                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24148                            "Failed to measure package size");
24149                }
24150            }
24151        }
24152
24153        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24154                + stats.dataSize);
24155
24156        final long startFreeBytes = measurePath.getUsableSpace();
24157        final long sizeBytes;
24158        if (moveCompleteApp) {
24159            sizeBytes = stats.codeSize + stats.dataSize;
24160        } else {
24161            sizeBytes = stats.codeSize;
24162        }
24163
24164        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24165            freezer.close();
24166            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24167                    "Not enough free space to move");
24168        }
24169
24170        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24171
24172        final CountDownLatch installedLatch = new CountDownLatch(1);
24173        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24174            @Override
24175            public void onUserActionRequired(Intent intent) throws RemoteException {
24176                throw new IllegalStateException();
24177            }
24178
24179            @Override
24180            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24181                    Bundle extras) throws RemoteException {
24182                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24183                        + PackageManager.installStatusToString(returnCode, msg));
24184
24185                installedLatch.countDown();
24186                freezer.close();
24187
24188                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24189                switch (status) {
24190                    case PackageInstaller.STATUS_SUCCESS:
24191                        mMoveCallbacks.notifyStatusChanged(moveId,
24192                                PackageManager.MOVE_SUCCEEDED);
24193                        break;
24194                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24195                        mMoveCallbacks.notifyStatusChanged(moveId,
24196                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24197                        break;
24198                    default:
24199                        mMoveCallbacks.notifyStatusChanged(moveId,
24200                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24201                        break;
24202                }
24203            }
24204        };
24205
24206        final MoveInfo move;
24207        if (moveCompleteApp) {
24208            // Kick off a thread to report progress estimates
24209            new Thread() {
24210                @Override
24211                public void run() {
24212                    while (true) {
24213                        try {
24214                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24215                                break;
24216                            }
24217                        } catch (InterruptedException ignored) {
24218                        }
24219
24220                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24221                        final int progress = 10 + (int) MathUtils.constrain(
24222                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24223                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24224                    }
24225                }
24226            }.start();
24227
24228            final String dataAppName = codeFile.getName();
24229            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24230                    dataAppName, appId, seinfo, targetSdkVersion);
24231        } else {
24232            move = null;
24233        }
24234
24235        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24236
24237        final Message msg = mHandler.obtainMessage(INIT_COPY);
24238        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24239        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24240                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24241                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24242                PackageManager.INSTALL_REASON_UNKNOWN);
24243        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24244        msg.obj = params;
24245
24246        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24247                System.identityHashCode(msg.obj));
24248        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24249                System.identityHashCode(msg.obj));
24250
24251        mHandler.sendMessage(msg);
24252    }
24253
24254    @Override
24255    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24256        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24257
24258        final int realMoveId = mNextMoveId.getAndIncrement();
24259        final Bundle extras = new Bundle();
24260        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24261        mMoveCallbacks.notifyCreated(realMoveId, extras);
24262
24263        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24264            @Override
24265            public void onCreated(int moveId, Bundle extras) {
24266                // Ignored
24267            }
24268
24269            @Override
24270            public void onStatusChanged(int moveId, int status, long estMillis) {
24271                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24272            }
24273        };
24274
24275        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24276        storage.setPrimaryStorageUuid(volumeUuid, callback);
24277        return realMoveId;
24278    }
24279
24280    @Override
24281    public int getMoveStatus(int moveId) {
24282        mContext.enforceCallingOrSelfPermission(
24283                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24284        return mMoveCallbacks.mLastStatus.get(moveId);
24285    }
24286
24287    @Override
24288    public void registerMoveCallback(IPackageMoveObserver callback) {
24289        mContext.enforceCallingOrSelfPermission(
24290                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24291        mMoveCallbacks.register(callback);
24292    }
24293
24294    @Override
24295    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24296        mContext.enforceCallingOrSelfPermission(
24297                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24298        mMoveCallbacks.unregister(callback);
24299    }
24300
24301    @Override
24302    public boolean setInstallLocation(int loc) {
24303        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24304                null);
24305        if (getInstallLocation() == loc) {
24306            return true;
24307        }
24308        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24309                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24310            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24311                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24312            return true;
24313        }
24314        return false;
24315   }
24316
24317    @Override
24318    public int getInstallLocation() {
24319        // allow instant app access
24320        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24321                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24322                PackageHelper.APP_INSTALL_AUTO);
24323    }
24324
24325    /** Called by UserManagerService */
24326    void cleanUpUser(UserManagerService userManager, int userHandle) {
24327        synchronized (mPackages) {
24328            mDirtyUsers.remove(userHandle);
24329            mUserNeedsBadging.delete(userHandle);
24330            mSettings.removeUserLPw(userHandle);
24331            mPendingBroadcasts.remove(userHandle);
24332            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24333            removeUnusedPackagesLPw(userManager, userHandle);
24334        }
24335    }
24336
24337    /**
24338     * We're removing userHandle and would like to remove any downloaded packages
24339     * that are no longer in use by any other user.
24340     * @param userHandle the user being removed
24341     */
24342    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24343        final boolean DEBUG_CLEAN_APKS = false;
24344        int [] users = userManager.getUserIds();
24345        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24346        while (psit.hasNext()) {
24347            PackageSetting ps = psit.next();
24348            if (ps.pkg == null) {
24349                continue;
24350            }
24351            final String packageName = ps.pkg.packageName;
24352            // Skip over if system app
24353            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24354                continue;
24355            }
24356            if (DEBUG_CLEAN_APKS) {
24357                Slog.i(TAG, "Checking package " + packageName);
24358            }
24359            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24360            if (keep) {
24361                if (DEBUG_CLEAN_APKS) {
24362                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24363                }
24364            } else {
24365                for (int i = 0; i < users.length; i++) {
24366                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24367                        keep = true;
24368                        if (DEBUG_CLEAN_APKS) {
24369                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24370                                    + users[i]);
24371                        }
24372                        break;
24373                    }
24374                }
24375            }
24376            if (!keep) {
24377                if (DEBUG_CLEAN_APKS) {
24378                    Slog.i(TAG, "  Removing package " + packageName);
24379                }
24380                mHandler.post(new Runnable() {
24381                    public void run() {
24382                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24383                                userHandle, 0);
24384                    } //end run
24385                });
24386            }
24387        }
24388    }
24389
24390    /** Called by UserManagerService */
24391    void createNewUser(int userId, String[] disallowedPackages) {
24392        synchronized (mInstallLock) {
24393            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24394        }
24395        synchronized (mPackages) {
24396            scheduleWritePackageRestrictionsLocked(userId);
24397            scheduleWritePackageListLocked(userId);
24398            applyFactoryDefaultBrowserLPw(userId);
24399            primeDomainVerificationsLPw(userId);
24400        }
24401    }
24402
24403    void onNewUserCreated(final int userId) {
24404        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24405        // If permission review for legacy apps is required, we represent
24406        // dagerous permissions for such apps as always granted runtime
24407        // permissions to keep per user flag state whether review is needed.
24408        // Hence, if a new user is added we have to propagate dangerous
24409        // permission grants for these legacy apps.
24410        if (mPermissionReviewRequired) {
24411            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24412                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24413        }
24414    }
24415
24416    @Override
24417    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24418        mContext.enforceCallingOrSelfPermission(
24419                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24420                "Only package verification agents can read the verifier device identity");
24421
24422        synchronized (mPackages) {
24423            return mSettings.getVerifierDeviceIdentityLPw();
24424        }
24425    }
24426
24427    @Override
24428    public void setPermissionEnforced(String permission, boolean enforced) {
24429        // TODO: Now that we no longer change GID for storage, this should to away.
24430        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24431                "setPermissionEnforced");
24432        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24433            synchronized (mPackages) {
24434                if (mSettings.mReadExternalStorageEnforced == null
24435                        || mSettings.mReadExternalStorageEnforced != enforced) {
24436                    mSettings.mReadExternalStorageEnforced = enforced;
24437                    mSettings.writeLPr();
24438                }
24439            }
24440            // kill any non-foreground processes so we restart them and
24441            // grant/revoke the GID.
24442            final IActivityManager am = ActivityManager.getService();
24443            if (am != null) {
24444                final long token = Binder.clearCallingIdentity();
24445                try {
24446                    am.killProcessesBelowForeground("setPermissionEnforcement");
24447                } catch (RemoteException e) {
24448                } finally {
24449                    Binder.restoreCallingIdentity(token);
24450                }
24451            }
24452        } else {
24453            throw new IllegalArgumentException("No selective enforcement for " + permission);
24454        }
24455    }
24456
24457    @Override
24458    @Deprecated
24459    public boolean isPermissionEnforced(String permission) {
24460        // allow instant applications
24461        return true;
24462    }
24463
24464    @Override
24465    public boolean isStorageLow() {
24466        // allow instant applications
24467        final long token = Binder.clearCallingIdentity();
24468        try {
24469            final DeviceStorageMonitorInternal
24470                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24471            if (dsm != null) {
24472                return dsm.isMemoryLow();
24473            } else {
24474                return false;
24475            }
24476        } finally {
24477            Binder.restoreCallingIdentity(token);
24478        }
24479    }
24480
24481    @Override
24482    public IPackageInstaller getPackageInstaller() {
24483        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24484            return null;
24485        }
24486        return mInstallerService;
24487    }
24488
24489    private boolean userNeedsBadging(int userId) {
24490        int index = mUserNeedsBadging.indexOfKey(userId);
24491        if (index < 0) {
24492            final UserInfo userInfo;
24493            final long token = Binder.clearCallingIdentity();
24494            try {
24495                userInfo = sUserManager.getUserInfo(userId);
24496            } finally {
24497                Binder.restoreCallingIdentity(token);
24498            }
24499            final boolean b;
24500            if (userInfo != null && userInfo.isManagedProfile()) {
24501                b = true;
24502            } else {
24503                b = false;
24504            }
24505            mUserNeedsBadging.put(userId, b);
24506            return b;
24507        }
24508        return mUserNeedsBadging.valueAt(index);
24509    }
24510
24511    @Override
24512    public KeySet getKeySetByAlias(String packageName, String alias) {
24513        if (packageName == null || alias == null) {
24514            return null;
24515        }
24516        synchronized(mPackages) {
24517            final PackageParser.Package pkg = mPackages.get(packageName);
24518            if (pkg == null) {
24519                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24520                throw new IllegalArgumentException("Unknown package: " + packageName);
24521            }
24522            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24523            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24524                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24525                throw new IllegalArgumentException("Unknown package: " + packageName);
24526            }
24527            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24528            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24529        }
24530    }
24531
24532    @Override
24533    public KeySet getSigningKeySet(String packageName) {
24534        if (packageName == null) {
24535            return null;
24536        }
24537        synchronized(mPackages) {
24538            final int callingUid = Binder.getCallingUid();
24539            final int callingUserId = UserHandle.getUserId(callingUid);
24540            final PackageParser.Package pkg = mPackages.get(packageName);
24541            if (pkg == null) {
24542                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24543                throw new IllegalArgumentException("Unknown package: " + packageName);
24544            }
24545            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24546            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24547                // filter and pretend the package doesn't exist
24548                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24549                        + ", uid:" + callingUid);
24550                throw new IllegalArgumentException("Unknown package: " + packageName);
24551            }
24552            if (pkg.applicationInfo.uid != callingUid
24553                    && Process.SYSTEM_UID != callingUid) {
24554                throw new SecurityException("May not access signing KeySet of other apps.");
24555            }
24556            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24557            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24558        }
24559    }
24560
24561    @Override
24562    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24563        final int callingUid = Binder.getCallingUid();
24564        if (getInstantAppPackageName(callingUid) != null) {
24565            return false;
24566        }
24567        if (packageName == null || ks == null) {
24568            return false;
24569        }
24570        synchronized(mPackages) {
24571            final PackageParser.Package pkg = mPackages.get(packageName);
24572            if (pkg == null
24573                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24574                            UserHandle.getUserId(callingUid))) {
24575                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24576                throw new IllegalArgumentException("Unknown package: " + packageName);
24577            }
24578            IBinder ksh = ks.getToken();
24579            if (ksh instanceof KeySetHandle) {
24580                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24581                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24582            }
24583            return false;
24584        }
24585    }
24586
24587    @Override
24588    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24589        final int callingUid = Binder.getCallingUid();
24590        if (getInstantAppPackageName(callingUid) != null) {
24591            return false;
24592        }
24593        if (packageName == null || ks == null) {
24594            return false;
24595        }
24596        synchronized(mPackages) {
24597            final PackageParser.Package pkg = mPackages.get(packageName);
24598            if (pkg == null
24599                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24600                            UserHandle.getUserId(callingUid))) {
24601                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24602                throw new IllegalArgumentException("Unknown package: " + packageName);
24603            }
24604            IBinder ksh = ks.getToken();
24605            if (ksh instanceof KeySetHandle) {
24606                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24607                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24608            }
24609            return false;
24610        }
24611    }
24612
24613    private void deletePackageIfUnusedLPr(final String packageName) {
24614        PackageSetting ps = mSettings.mPackages.get(packageName);
24615        if (ps == null) {
24616            return;
24617        }
24618        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24619            // TODO Implement atomic delete if package is unused
24620            // It is currently possible that the package will be deleted even if it is installed
24621            // after this method returns.
24622            mHandler.post(new Runnable() {
24623                public void run() {
24624                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24625                            0, PackageManager.DELETE_ALL_USERS);
24626                }
24627            });
24628        }
24629    }
24630
24631    /**
24632     * Check and throw if the given before/after packages would be considered a
24633     * downgrade.
24634     */
24635    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24636            throws PackageManagerException {
24637        if (after.versionCode < before.mVersionCode) {
24638            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24639                    "Update version code " + after.versionCode + " is older than current "
24640                    + before.mVersionCode);
24641        } else if (after.versionCode == before.mVersionCode) {
24642            if (after.baseRevisionCode < before.baseRevisionCode) {
24643                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24644                        "Update base revision code " + after.baseRevisionCode
24645                        + " is older than current " + before.baseRevisionCode);
24646            }
24647
24648            if (!ArrayUtils.isEmpty(after.splitNames)) {
24649                for (int i = 0; i < after.splitNames.length; i++) {
24650                    final String splitName = after.splitNames[i];
24651                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24652                    if (j != -1) {
24653                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24654                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24655                                    "Update split " + splitName + " revision code "
24656                                    + after.splitRevisionCodes[i] + " is older than current "
24657                                    + before.splitRevisionCodes[j]);
24658                        }
24659                    }
24660                }
24661            }
24662        }
24663    }
24664
24665    private static class MoveCallbacks extends Handler {
24666        private static final int MSG_CREATED = 1;
24667        private static final int MSG_STATUS_CHANGED = 2;
24668
24669        private final RemoteCallbackList<IPackageMoveObserver>
24670                mCallbacks = new RemoteCallbackList<>();
24671
24672        private final SparseIntArray mLastStatus = new SparseIntArray();
24673
24674        public MoveCallbacks(Looper looper) {
24675            super(looper);
24676        }
24677
24678        public void register(IPackageMoveObserver callback) {
24679            mCallbacks.register(callback);
24680        }
24681
24682        public void unregister(IPackageMoveObserver callback) {
24683            mCallbacks.unregister(callback);
24684        }
24685
24686        @Override
24687        public void handleMessage(Message msg) {
24688            final SomeArgs args = (SomeArgs) msg.obj;
24689            final int n = mCallbacks.beginBroadcast();
24690            for (int i = 0; i < n; i++) {
24691                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24692                try {
24693                    invokeCallback(callback, msg.what, args);
24694                } catch (RemoteException ignored) {
24695                }
24696            }
24697            mCallbacks.finishBroadcast();
24698            args.recycle();
24699        }
24700
24701        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24702                throws RemoteException {
24703            switch (what) {
24704                case MSG_CREATED: {
24705                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24706                    break;
24707                }
24708                case MSG_STATUS_CHANGED: {
24709                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24710                    break;
24711                }
24712            }
24713        }
24714
24715        private void notifyCreated(int moveId, Bundle extras) {
24716            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24717
24718            final SomeArgs args = SomeArgs.obtain();
24719            args.argi1 = moveId;
24720            args.arg2 = extras;
24721            obtainMessage(MSG_CREATED, args).sendToTarget();
24722        }
24723
24724        private void notifyStatusChanged(int moveId, int status) {
24725            notifyStatusChanged(moveId, status, -1);
24726        }
24727
24728        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24729            Slog.v(TAG, "Move " + moveId + " status " + status);
24730
24731            final SomeArgs args = SomeArgs.obtain();
24732            args.argi1 = moveId;
24733            args.argi2 = status;
24734            args.arg3 = estMillis;
24735            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24736
24737            synchronized (mLastStatus) {
24738                mLastStatus.put(moveId, status);
24739            }
24740        }
24741    }
24742
24743    private final static class OnPermissionChangeListeners extends Handler {
24744        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24745
24746        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24747                new RemoteCallbackList<>();
24748
24749        public OnPermissionChangeListeners(Looper looper) {
24750            super(looper);
24751        }
24752
24753        @Override
24754        public void handleMessage(Message msg) {
24755            switch (msg.what) {
24756                case MSG_ON_PERMISSIONS_CHANGED: {
24757                    final int uid = msg.arg1;
24758                    handleOnPermissionsChanged(uid);
24759                } break;
24760            }
24761        }
24762
24763        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24764            mPermissionListeners.register(listener);
24765
24766        }
24767
24768        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24769            mPermissionListeners.unregister(listener);
24770        }
24771
24772        public void onPermissionsChanged(int uid) {
24773            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24774                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24775            }
24776        }
24777
24778        private void handleOnPermissionsChanged(int uid) {
24779            final int count = mPermissionListeners.beginBroadcast();
24780            try {
24781                for (int i = 0; i < count; i++) {
24782                    IOnPermissionsChangeListener callback = mPermissionListeners
24783                            .getBroadcastItem(i);
24784                    try {
24785                        callback.onPermissionsChanged(uid);
24786                    } catch (RemoteException e) {
24787                        Log.e(TAG, "Permission listener is dead", e);
24788                    }
24789                }
24790            } finally {
24791                mPermissionListeners.finishBroadcast();
24792            }
24793        }
24794    }
24795
24796    private class PackageManagerNative extends IPackageManagerNative.Stub {
24797        @Override
24798        public String[] getNamesForUids(int[] uids) throws RemoteException {
24799            final String[] results = PackageManagerService.this.getNamesForUids(uids);
24800            // massage results so they can be parsed by the native binder
24801            for (int i = results.length - 1; i >= 0; --i) {
24802                if (results[i] == null) {
24803                    results[i] = "";
24804                }
24805            }
24806            return results;
24807        }
24808    }
24809
24810    private class PackageManagerInternalImpl extends PackageManagerInternal {
24811        @Override
24812        public void setLocationPackagesProvider(PackagesProvider provider) {
24813            synchronized (mPackages) {
24814                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24815            }
24816        }
24817
24818        @Override
24819        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24820            synchronized (mPackages) {
24821                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24822            }
24823        }
24824
24825        @Override
24826        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24827            synchronized (mPackages) {
24828                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24829            }
24830        }
24831
24832        @Override
24833        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24834            synchronized (mPackages) {
24835                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24836            }
24837        }
24838
24839        @Override
24840        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24841            synchronized (mPackages) {
24842                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24843            }
24844        }
24845
24846        @Override
24847        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24848            synchronized (mPackages) {
24849                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24850            }
24851        }
24852
24853        @Override
24854        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24855            synchronized (mPackages) {
24856                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24857                        packageName, userId);
24858            }
24859        }
24860
24861        @Override
24862        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24863            synchronized (mPackages) {
24864                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24865                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24866                        packageName, userId);
24867            }
24868        }
24869
24870        @Override
24871        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24872            synchronized (mPackages) {
24873                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24874                        packageName, userId);
24875            }
24876        }
24877
24878        @Override
24879        public void setKeepUninstalledPackages(final List<String> packageList) {
24880            Preconditions.checkNotNull(packageList);
24881            List<String> removedFromList = null;
24882            synchronized (mPackages) {
24883                if (mKeepUninstalledPackages != null) {
24884                    final int packagesCount = mKeepUninstalledPackages.size();
24885                    for (int i = 0; i < packagesCount; i++) {
24886                        String oldPackage = mKeepUninstalledPackages.get(i);
24887                        if (packageList != null && packageList.contains(oldPackage)) {
24888                            continue;
24889                        }
24890                        if (removedFromList == null) {
24891                            removedFromList = new ArrayList<>();
24892                        }
24893                        removedFromList.add(oldPackage);
24894                    }
24895                }
24896                mKeepUninstalledPackages = new ArrayList<>(packageList);
24897                if (removedFromList != null) {
24898                    final int removedCount = removedFromList.size();
24899                    for (int i = 0; i < removedCount; i++) {
24900                        deletePackageIfUnusedLPr(removedFromList.get(i));
24901                    }
24902                }
24903            }
24904        }
24905
24906        @Override
24907        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24908            synchronized (mPackages) {
24909                // If we do not support permission review, done.
24910                if (!mPermissionReviewRequired) {
24911                    return false;
24912                }
24913
24914                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24915                if (packageSetting == null) {
24916                    return false;
24917                }
24918
24919                // Permission review applies only to apps not supporting the new permission model.
24920                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24921                    return false;
24922                }
24923
24924                // Legacy apps have the permission and get user consent on launch.
24925                PermissionsState permissionsState = packageSetting.getPermissionsState();
24926                return permissionsState.isPermissionReviewRequired(userId);
24927            }
24928        }
24929
24930        @Override
24931        public PackageInfo getPackageInfo(
24932                String packageName, int flags, int filterCallingUid, int userId) {
24933            return PackageManagerService.this
24934                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24935                            flags, filterCallingUid, userId);
24936        }
24937
24938        @Override
24939        public ApplicationInfo getApplicationInfo(
24940                String packageName, int flags, int filterCallingUid, int userId) {
24941            return PackageManagerService.this
24942                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24943        }
24944
24945        @Override
24946        public ActivityInfo getActivityInfo(
24947                ComponentName component, int flags, int filterCallingUid, int userId) {
24948            return PackageManagerService.this
24949                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24950        }
24951
24952        @Override
24953        public List<ResolveInfo> queryIntentActivities(
24954                Intent intent, int flags, int filterCallingUid, int userId) {
24955            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24956            return PackageManagerService.this
24957                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24958                            userId, false /*resolveForStart*/);
24959        }
24960
24961        @Override
24962        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24963                int userId) {
24964            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24965        }
24966
24967        @Override
24968        public void setDeviceAndProfileOwnerPackages(
24969                int deviceOwnerUserId, String deviceOwnerPackage,
24970                SparseArray<String> profileOwnerPackages) {
24971            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24972                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24973        }
24974
24975        @Override
24976        public boolean isPackageDataProtected(int userId, String packageName) {
24977            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24978        }
24979
24980        @Override
24981        public boolean isPackageEphemeral(int userId, String packageName) {
24982            synchronized (mPackages) {
24983                final PackageSetting ps = mSettings.mPackages.get(packageName);
24984                return ps != null ? ps.getInstantApp(userId) : false;
24985            }
24986        }
24987
24988        @Override
24989        public boolean wasPackageEverLaunched(String packageName, int userId) {
24990            synchronized (mPackages) {
24991                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24992            }
24993        }
24994
24995        @Override
24996        public void grantRuntimePermission(String packageName, String name, int userId,
24997                boolean overridePolicy) {
24998            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24999                    overridePolicy);
25000        }
25001
25002        @Override
25003        public void revokeRuntimePermission(String packageName, String name, int userId,
25004                boolean overridePolicy) {
25005            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25006                    overridePolicy);
25007        }
25008
25009        @Override
25010        public String getNameForUid(int uid) {
25011            return PackageManagerService.this.getNameForUid(uid);
25012        }
25013
25014        @Override
25015        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25016                Intent origIntent, String resolvedType, String callingPackage,
25017                Bundle verificationBundle, int userId) {
25018            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25019                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25020                    userId);
25021        }
25022
25023        @Override
25024        public void grantEphemeralAccess(int userId, Intent intent,
25025                int targetAppId, int ephemeralAppId) {
25026            synchronized (mPackages) {
25027                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25028                        targetAppId, ephemeralAppId);
25029            }
25030        }
25031
25032        @Override
25033        public boolean isInstantAppInstallerComponent(ComponentName component) {
25034            synchronized (mPackages) {
25035                return mInstantAppInstallerActivity != null
25036                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25037            }
25038        }
25039
25040        @Override
25041        public void pruneInstantApps() {
25042            mInstantAppRegistry.pruneInstantApps();
25043        }
25044
25045        @Override
25046        public String getSetupWizardPackageName() {
25047            return mSetupWizardPackage;
25048        }
25049
25050        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25051            if (policy != null) {
25052                mExternalSourcesPolicy = policy;
25053            }
25054        }
25055
25056        @Override
25057        public boolean isPackagePersistent(String packageName) {
25058            synchronized (mPackages) {
25059                PackageParser.Package pkg = mPackages.get(packageName);
25060                return pkg != null
25061                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25062                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25063                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25064                        : false;
25065            }
25066        }
25067
25068        @Override
25069        public List<PackageInfo> getOverlayPackages(int userId) {
25070            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25071            synchronized (mPackages) {
25072                for (PackageParser.Package p : mPackages.values()) {
25073                    if (p.mOverlayTarget != null) {
25074                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25075                        if (pkg != null) {
25076                            overlayPackages.add(pkg);
25077                        }
25078                    }
25079                }
25080            }
25081            return overlayPackages;
25082        }
25083
25084        @Override
25085        public List<String> getTargetPackageNames(int userId) {
25086            List<String> targetPackages = new ArrayList<>();
25087            synchronized (mPackages) {
25088                for (PackageParser.Package p : mPackages.values()) {
25089                    if (p.mOverlayTarget == null) {
25090                        targetPackages.add(p.packageName);
25091                    }
25092                }
25093            }
25094            return targetPackages;
25095        }
25096
25097        @Override
25098        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25099                @Nullable List<String> overlayPackageNames) {
25100            synchronized (mPackages) {
25101                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25102                    Slog.e(TAG, "failed to find package " + targetPackageName);
25103                    return false;
25104                }
25105                ArrayList<String> overlayPaths = null;
25106                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25107                    final int N = overlayPackageNames.size();
25108                    overlayPaths = new ArrayList<>(N);
25109                    for (int i = 0; i < N; i++) {
25110                        final String packageName = overlayPackageNames.get(i);
25111                        final PackageParser.Package pkg = mPackages.get(packageName);
25112                        if (pkg == null) {
25113                            Slog.e(TAG, "failed to find package " + packageName);
25114                            return false;
25115                        }
25116                        overlayPaths.add(pkg.baseCodePath);
25117                    }
25118                }
25119
25120                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25121                ps.setOverlayPaths(overlayPaths, userId);
25122                return true;
25123            }
25124        }
25125
25126        @Override
25127        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25128                int flags, int userId) {
25129            return resolveIntentInternal(
25130                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25131        }
25132
25133        @Override
25134        public ResolveInfo resolveService(Intent intent, String resolvedType,
25135                int flags, int userId, int callingUid) {
25136            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25137        }
25138
25139        @Override
25140        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25141            synchronized (mPackages) {
25142                mIsolatedOwners.put(isolatedUid, ownerUid);
25143            }
25144        }
25145
25146        @Override
25147        public void removeIsolatedUid(int isolatedUid) {
25148            synchronized (mPackages) {
25149                mIsolatedOwners.delete(isolatedUid);
25150            }
25151        }
25152
25153        @Override
25154        public int getUidTargetSdkVersion(int uid) {
25155            synchronized (mPackages) {
25156                return getUidTargetSdkVersionLockedLPr(uid);
25157            }
25158        }
25159
25160        @Override
25161        public boolean canAccessInstantApps(int callingUid, int userId) {
25162            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25163        }
25164    }
25165
25166    @Override
25167    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25168        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25169        synchronized (mPackages) {
25170            final long identity = Binder.clearCallingIdentity();
25171            try {
25172                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25173                        packageNames, userId);
25174            } finally {
25175                Binder.restoreCallingIdentity(identity);
25176            }
25177        }
25178    }
25179
25180    @Override
25181    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25182        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25183        synchronized (mPackages) {
25184            final long identity = Binder.clearCallingIdentity();
25185            try {
25186                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25187                        packageNames, userId);
25188            } finally {
25189                Binder.restoreCallingIdentity(identity);
25190            }
25191        }
25192    }
25193
25194    private static void enforceSystemOrPhoneCaller(String tag) {
25195        int callingUid = Binder.getCallingUid();
25196        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25197            throw new SecurityException(
25198                    "Cannot call " + tag + " from UID " + callingUid);
25199        }
25200    }
25201
25202    boolean isHistoricalPackageUsageAvailable() {
25203        return mPackageUsage.isHistoricalPackageUsageAvailable();
25204    }
25205
25206    /**
25207     * Return a <b>copy</b> of the collection of packages known to the package manager.
25208     * @return A copy of the values of mPackages.
25209     */
25210    Collection<PackageParser.Package> getPackages() {
25211        synchronized (mPackages) {
25212            return new ArrayList<>(mPackages.values());
25213        }
25214    }
25215
25216    /**
25217     * Logs process start information (including base APK hash) to the security log.
25218     * @hide
25219     */
25220    @Override
25221    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25222            String apkFile, int pid) {
25223        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25224            return;
25225        }
25226        if (!SecurityLog.isLoggingEnabled()) {
25227            return;
25228        }
25229        Bundle data = new Bundle();
25230        data.putLong("startTimestamp", System.currentTimeMillis());
25231        data.putString("processName", processName);
25232        data.putInt("uid", uid);
25233        data.putString("seinfo", seinfo);
25234        data.putString("apkFile", apkFile);
25235        data.putInt("pid", pid);
25236        Message msg = mProcessLoggingHandler.obtainMessage(
25237                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25238        msg.setData(data);
25239        mProcessLoggingHandler.sendMessage(msg);
25240    }
25241
25242    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25243        return mCompilerStats.getPackageStats(pkgName);
25244    }
25245
25246    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25247        return getOrCreateCompilerPackageStats(pkg.packageName);
25248    }
25249
25250    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25251        return mCompilerStats.getOrCreatePackageStats(pkgName);
25252    }
25253
25254    public void deleteCompilerPackageStats(String pkgName) {
25255        mCompilerStats.deletePackageStats(pkgName);
25256    }
25257
25258    @Override
25259    public int getInstallReason(String packageName, int userId) {
25260        final int callingUid = Binder.getCallingUid();
25261        enforceCrossUserPermission(callingUid, userId,
25262                true /* requireFullPermission */, false /* checkShell */,
25263                "get install reason");
25264        synchronized (mPackages) {
25265            final PackageSetting ps = mSettings.mPackages.get(packageName);
25266            if (filterAppAccessLPr(ps, callingUid, userId)) {
25267                return PackageManager.INSTALL_REASON_UNKNOWN;
25268            }
25269            if (ps != null) {
25270                return ps.getInstallReason(userId);
25271            }
25272        }
25273        return PackageManager.INSTALL_REASON_UNKNOWN;
25274    }
25275
25276    @Override
25277    public boolean canRequestPackageInstalls(String packageName, int userId) {
25278        return canRequestPackageInstallsInternal(packageName, 0, userId,
25279                true /* throwIfPermNotDeclared*/);
25280    }
25281
25282    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25283            boolean throwIfPermNotDeclared) {
25284        int callingUid = Binder.getCallingUid();
25285        int uid = getPackageUid(packageName, 0, userId);
25286        if (callingUid != uid && callingUid != Process.ROOT_UID
25287                && callingUid != Process.SYSTEM_UID) {
25288            throw new SecurityException(
25289                    "Caller uid " + callingUid + " does not own package " + packageName);
25290        }
25291        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25292        if (info == null) {
25293            return false;
25294        }
25295        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25296            return false;
25297        }
25298        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25299        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25300        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25301            if (throwIfPermNotDeclared) {
25302                throw new SecurityException("Need to declare " + appOpPermission
25303                        + " to call this api");
25304            } else {
25305                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25306                return false;
25307            }
25308        }
25309        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25310            return false;
25311        }
25312        if (mExternalSourcesPolicy != null) {
25313            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25314            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25315                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25316            }
25317        }
25318        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25319    }
25320
25321    @Override
25322    public ComponentName getInstantAppResolverSettingsComponent() {
25323        return mInstantAppResolverSettingsComponent;
25324    }
25325
25326    @Override
25327    public ComponentName getInstantAppInstallerComponent() {
25328        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25329            return null;
25330        }
25331        return mInstantAppInstallerActivity == null
25332                ? null : mInstantAppInstallerActivity.getComponentName();
25333    }
25334
25335    @Override
25336    public String getInstantAppAndroidId(String packageName, int userId) {
25337        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25338                "getInstantAppAndroidId");
25339        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25340                true /* requireFullPermission */, false /* checkShell */,
25341                "getInstantAppAndroidId");
25342        // Make sure the target is an Instant App.
25343        if (!isInstantApp(packageName, userId)) {
25344            return null;
25345        }
25346        synchronized (mPackages) {
25347            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25348        }
25349    }
25350
25351    boolean canHaveOatDir(String packageName) {
25352        synchronized (mPackages) {
25353            PackageParser.Package p = mPackages.get(packageName);
25354            if (p == null) {
25355                return false;
25356            }
25357            return p.canHaveOatDir();
25358        }
25359    }
25360
25361    private String getOatDir(PackageParser.Package pkg) {
25362        if (!pkg.canHaveOatDir()) {
25363            return null;
25364        }
25365        File codePath = new File(pkg.codePath);
25366        if (codePath.isDirectory()) {
25367            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25368        }
25369        return null;
25370    }
25371
25372    void deleteOatArtifactsOfPackage(String packageName) {
25373        final String[] instructionSets;
25374        final List<String> codePaths;
25375        final String oatDir;
25376        final PackageParser.Package pkg;
25377        synchronized (mPackages) {
25378            pkg = mPackages.get(packageName);
25379        }
25380        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25381        codePaths = pkg.getAllCodePaths();
25382        oatDir = getOatDir(pkg);
25383
25384        for (String codePath : codePaths) {
25385            for (String isa : instructionSets) {
25386                try {
25387                    mInstaller.deleteOdex(codePath, isa, oatDir);
25388                } catch (InstallerException e) {
25389                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25390                }
25391            }
25392        }
25393    }
25394
25395    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25396        Set<String> unusedPackages = new HashSet<>();
25397        long currentTimeInMillis = System.currentTimeMillis();
25398        synchronized (mPackages) {
25399            for (PackageParser.Package pkg : mPackages.values()) {
25400                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25401                if (ps == null) {
25402                    continue;
25403                }
25404                PackageDexUsage.PackageUseInfo packageUseInfo = getDexManager().getPackageUseInfo(
25405                        pkg.packageName);
25406                if (PackageManagerServiceUtils
25407                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25408                                downgradeTimeThresholdMillis, packageUseInfo,
25409                                pkg.getLatestPackageUseTimeInMills(),
25410                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25411                    unusedPackages.add(pkg.packageName);
25412                }
25413            }
25414        }
25415        return unusedPackages;
25416    }
25417}
25418
25419interface PackageSender {
25420    void sendPackageBroadcast(final String action, final String pkg,
25421        final Bundle extras, final int flags, final String targetPkg,
25422        final IIntentReceiver finishedReceiver, final int[] userIds);
25423    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25424        boolean includeStopped, int appId, int... userIds);
25425}
25426