PackageManagerService.java revision 9da8b8a7fc8c68c17e1bf8cce24e2f73abe5138e
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
106
107import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
108
109import android.Manifest;
110import android.annotation.IntDef;
111import android.annotation.NonNull;
112import android.annotation.Nullable;
113import android.app.ActivityManager;
114import android.app.AppOpsManager;
115import android.app.IActivityManager;
116import android.app.ResourcesManager;
117import android.app.admin.IDevicePolicyManager;
118import android.app.admin.SecurityLog;
119import android.app.backup.IBackupManager;
120import android.content.BroadcastReceiver;
121import android.content.ComponentName;
122import android.content.ContentResolver;
123import android.content.Context;
124import android.content.IIntentReceiver;
125import android.content.Intent;
126import android.content.IntentFilter;
127import android.content.IntentSender;
128import android.content.IntentSender.SendIntentException;
129import android.content.ServiceConnection;
130import android.content.pm.ActivityInfo;
131import android.content.pm.ApplicationInfo;
132import android.content.pm.AppsQueryHelper;
133import android.content.pm.AuxiliaryResolveInfo;
134import android.content.pm.ChangedPackages;
135import android.content.pm.ComponentInfo;
136import android.content.pm.FallbackCategoryProvider;
137import android.content.pm.FeatureInfo;
138import android.content.pm.IDexModuleRegisterCallback;
139import android.content.pm.IOnPermissionsChangeListener;
140import android.content.pm.IPackageDataObserver;
141import android.content.pm.IPackageDeleteObserver;
142import android.content.pm.IPackageDeleteObserver2;
143import android.content.pm.IPackageInstallObserver2;
144import android.content.pm.IPackageInstaller;
145import android.content.pm.IPackageManager;
146import android.content.pm.IPackageMoveObserver;
147import android.content.pm.IPackageStatsObserver;
148import android.content.pm.InstantAppInfo;
149import android.content.pm.InstantAppRequest;
150import android.content.pm.InstantAppResolveInfo;
151import android.content.pm.InstrumentationInfo;
152import android.content.pm.IntentFilterVerificationInfo;
153import android.content.pm.KeySet;
154import android.content.pm.PackageCleanItem;
155import android.content.pm.PackageInfo;
156import android.content.pm.PackageInfoLite;
157import android.content.pm.PackageInstaller;
158import android.content.pm.PackageManager;
159import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
160import android.content.pm.PackageManagerInternal;
161import android.content.pm.PackageParser;
162import android.content.pm.PackageParser.ActivityIntentInfo;
163import android.content.pm.PackageParser.PackageLite;
164import android.content.pm.PackageParser.PackageParserException;
165import android.content.pm.PackageStats;
166import android.content.pm.PackageUserState;
167import android.content.pm.ParceledListSlice;
168import android.content.pm.PermissionGroupInfo;
169import android.content.pm.PermissionInfo;
170import android.content.pm.ProviderInfo;
171import android.content.pm.ResolveInfo;
172import android.content.pm.ServiceInfo;
173import android.content.pm.SharedLibraryInfo;
174import android.content.pm.Signature;
175import android.content.pm.UserInfo;
176import android.content.pm.VerifierDeviceIdentity;
177import android.content.pm.VerifierInfo;
178import android.content.pm.VersionedPackage;
179import android.content.res.Resources;
180import android.database.ContentObserver;
181import android.graphics.Bitmap;
182import android.hardware.display.DisplayManager;
183import android.net.Uri;
184import android.os.Binder;
185import android.os.Build;
186import android.os.Bundle;
187import android.os.Debug;
188import android.os.Environment;
189import android.os.Environment.UserEnvironment;
190import android.os.FileUtils;
191import android.os.Handler;
192import android.os.IBinder;
193import android.os.Looper;
194import android.os.Message;
195import android.os.Parcel;
196import android.os.ParcelFileDescriptor;
197import android.os.PatternMatcher;
198import android.os.Process;
199import android.os.RemoteCallbackList;
200import android.os.RemoteException;
201import android.os.ResultReceiver;
202import android.os.SELinux;
203import android.os.ServiceManager;
204import android.os.ShellCallback;
205import android.os.SystemClock;
206import android.os.SystemProperties;
207import android.os.Trace;
208import android.os.UserHandle;
209import android.os.UserManager;
210import android.os.UserManagerInternal;
211import android.os.storage.IStorageManager;
212import android.os.storage.StorageEventListener;
213import android.os.storage.StorageManager;
214import android.os.storage.StorageManagerInternal;
215import android.os.storage.VolumeInfo;
216import android.os.storage.VolumeRecord;
217import android.provider.Settings.Global;
218import android.provider.Settings.Secure;
219import android.security.KeyStore;
220import android.security.SystemKeyStore;
221import android.service.pm.PackageServiceDumpProto;
222import android.system.ErrnoException;
223import android.system.Os;
224import android.text.TextUtils;
225import android.text.format.DateUtils;
226import android.util.ArrayMap;
227import android.util.ArraySet;
228import android.util.Base64;
229import android.util.BootTimingsTraceLog;
230import android.util.DisplayMetrics;
231import android.util.EventLog;
232import android.util.ExceptionUtils;
233import android.util.Log;
234import android.util.LogPrinter;
235import android.util.MathUtils;
236import android.util.PackageUtils;
237import android.util.Pair;
238import android.util.PrintStreamPrinter;
239import android.util.Slog;
240import android.util.SparseArray;
241import android.util.SparseBooleanArray;
242import android.util.SparseIntArray;
243import android.util.Xml;
244import android.util.jar.StrictJarFile;
245import android.util.proto.ProtoOutputStream;
246import android.view.Display;
247
248import com.android.internal.R;
249import com.android.internal.annotations.GuardedBy;
250import com.android.internal.app.IMediaContainerService;
251import com.android.internal.app.ResolverActivity;
252import com.android.internal.content.NativeLibraryHelper;
253import com.android.internal.content.PackageHelper;
254import com.android.internal.logging.MetricsLogger;
255import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
256import com.android.internal.os.IParcelFileDescriptorFactory;
257import com.android.internal.os.RoSystemProperties;
258import com.android.internal.os.SomeArgs;
259import com.android.internal.os.Zygote;
260import com.android.internal.telephony.CarrierAppUtils;
261import com.android.internal.util.ArrayUtils;
262import com.android.internal.util.ConcurrentUtils;
263import com.android.internal.util.DumpUtils;
264import com.android.internal.util.FastPrintWriter;
265import com.android.internal.util.FastXmlSerializer;
266import com.android.internal.util.IndentingPrintWriter;
267import com.android.internal.util.Preconditions;
268import com.android.internal.util.XmlUtils;
269import com.android.server.AttributeCache;
270import com.android.server.DeviceIdleController;
271import com.android.server.EventLogTags;
272import com.android.server.FgThread;
273import com.android.server.IntentResolver;
274import com.android.server.LocalServices;
275import com.android.server.LockGuard;
276import com.android.server.ServiceThread;
277import com.android.server.SystemConfig;
278import com.android.server.SystemServerInitThreadPool;
279import com.android.server.Watchdog;
280import com.android.server.net.NetworkPolicyManagerInternal;
281import com.android.server.pm.Installer.InstallerException;
282import com.android.server.pm.PermissionsState.PermissionState;
283import com.android.server.pm.Settings.DatabaseVersion;
284import com.android.server.pm.Settings.VersionInfo;
285import com.android.server.pm.dex.DexManager;
286import com.android.server.pm.dex.DexoptOptions;
287import com.android.server.pm.dex.PackageDexUsage;
288import com.android.server.storage.DeviceStorageMonitorInternal;
289
290import dalvik.system.CloseGuard;
291import dalvik.system.DexFile;
292import dalvik.system.VMRuntime;
293
294import libcore.io.IoUtils;
295import libcore.io.Streams;
296import libcore.util.EmptyArray;
297
298import org.xmlpull.v1.XmlPullParser;
299import org.xmlpull.v1.XmlPullParserException;
300import org.xmlpull.v1.XmlSerializer;
301
302import java.io.BufferedOutputStream;
303import java.io.BufferedReader;
304import java.io.ByteArrayInputStream;
305import java.io.ByteArrayOutputStream;
306import java.io.File;
307import java.io.FileDescriptor;
308import java.io.FileInputStream;
309import java.io.FileOutputStream;
310import java.io.FileReader;
311import java.io.FilenameFilter;
312import java.io.IOException;
313import java.io.InputStream;
314import java.io.OutputStream;
315import java.io.PrintWriter;
316import java.lang.annotation.Retention;
317import java.lang.annotation.RetentionPolicy;
318import java.nio.charset.StandardCharsets;
319import java.security.DigestInputStream;
320import java.security.MessageDigest;
321import java.security.NoSuchAlgorithmException;
322import java.security.PublicKey;
323import java.security.SecureRandom;
324import java.security.cert.Certificate;
325import java.security.cert.CertificateEncodingException;
326import java.security.cert.CertificateException;
327import java.text.SimpleDateFormat;
328import java.util.ArrayList;
329import java.util.Arrays;
330import java.util.Collection;
331import java.util.Collections;
332import java.util.Comparator;
333import java.util.Date;
334import java.util.HashMap;
335import java.util.HashSet;
336import java.util.Iterator;
337import java.util.List;
338import java.util.Map;
339import java.util.Objects;
340import java.util.Set;
341import java.util.concurrent.CountDownLatch;
342import java.util.concurrent.Future;
343import java.util.concurrent.TimeUnit;
344import java.util.concurrent.atomic.AtomicBoolean;
345import java.util.concurrent.atomic.AtomicInteger;
346import java.util.zip.GZIPInputStream;
347
348/**
349 * Keep track of all those APKs everywhere.
350 * <p>
351 * Internally there are two important locks:
352 * <ul>
353 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
354 * and other related state. It is a fine-grained lock that should only be held
355 * momentarily, as it's one of the most contended locks in the system.
356 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
357 * operations typically involve heavy lifting of application data on disk. Since
358 * {@code installd} is single-threaded, and it's operations can often be slow,
359 * this lock should never be acquired while already holding {@link #mPackages}.
360 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
361 * holding {@link #mInstallLock}.
362 * </ul>
363 * Many internal methods rely on the caller to hold the appropriate locks, and
364 * this contract is expressed through method name suffixes:
365 * <ul>
366 * <li>fooLI(): the caller must hold {@link #mInstallLock}
367 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
368 * being modified must be frozen
369 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
370 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
371 * </ul>
372 * <p>
373 * Because this class is very central to the platform's security; please run all
374 * CTS and unit tests whenever making modifications:
375 *
376 * <pre>
377 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
378 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
379 * </pre>
380 */
381public class PackageManagerService extends IPackageManager.Stub
382        implements PackageSender {
383    static final String TAG = "PackageManager";
384    static final boolean DEBUG_SETTINGS = false;
385    static final boolean DEBUG_PREFERRED = false;
386    static final boolean DEBUG_UPGRADE = false;
387    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
388    private static final boolean DEBUG_BACKUP = false;
389    private static final boolean DEBUG_INSTALL = false;
390    private static final boolean DEBUG_REMOVE = false;
391    private static final boolean DEBUG_BROADCASTS = false;
392    private static final boolean DEBUG_SHOW_INFO = false;
393    private static final boolean DEBUG_PACKAGE_INFO = false;
394    private static final boolean DEBUG_INTENT_MATCHING = false;
395    private static final boolean DEBUG_PACKAGE_SCANNING = false;
396    private static final boolean DEBUG_VERIFY = false;
397    private static final boolean DEBUG_FILTERS = false;
398    private static final boolean DEBUG_PERMISSIONS = false;
399    private static final boolean DEBUG_SHARED_LIBRARIES = false;
400    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
401
402    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
403    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
404    // user, but by default initialize to this.
405    public static final boolean DEBUG_DEXOPT = false;
406
407    private static final boolean DEBUG_ABI_SELECTION = false;
408    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
409    private static final boolean DEBUG_TRIAGED_MISSING = false;
410    private static final boolean DEBUG_APP_DATA = false;
411
412    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
413    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
414
415    private static final boolean HIDE_EPHEMERAL_APIS = false;
416
417    private static final boolean ENABLE_FREE_CACHE_V2 =
418            SystemProperties.getBoolean("fw.free_cache_v2", true);
419
420    private static final int RADIO_UID = Process.PHONE_UID;
421    private static final int LOG_UID = Process.LOG_UID;
422    private static final int NFC_UID = Process.NFC_UID;
423    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
424    private static final int SHELL_UID = Process.SHELL_UID;
425
426    // Cap the size of permission trees that 3rd party apps can define
427    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
428
429    // Suffix used during package installation when copying/moving
430    // package apks to install directory.
431    private static final String INSTALL_PACKAGE_SUFFIX = "-";
432
433    static final int SCAN_NO_DEX = 1<<1;
434    static final int SCAN_FORCE_DEX = 1<<2;
435    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
436    static final int SCAN_NEW_INSTALL = 1<<4;
437    static final int SCAN_UPDATE_TIME = 1<<5;
438    static final int SCAN_BOOTING = 1<<6;
439    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
440    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
441    static final int SCAN_REPLACING = 1<<9;
442    static final int SCAN_REQUIRE_KNOWN = 1<<10;
443    static final int SCAN_MOVE = 1<<11;
444    static final int SCAN_INITIAL = 1<<12;
445    static final int SCAN_CHECK_ONLY = 1<<13;
446    static final int SCAN_DONT_KILL_APP = 1<<14;
447    static final int SCAN_IGNORE_FROZEN = 1<<15;
448    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
449    static final int SCAN_AS_INSTANT_APP = 1<<17;
450    static final int SCAN_AS_FULL_APP = 1<<18;
451    /** Should not be with the scan flags */
452    static final int FLAGS_REMOVE_CHATTY = 1<<31;
453
454    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
455    /** Extension of the compressed packages */
456    private final static String COMPRESSED_EXTENSION = ".gz";
457
458    private static final int[] EMPTY_INT_ARRAY = new int[0];
459
460    private static final int TYPE_UNKNOWN = 0;
461    private static final int TYPE_ACTIVITY = 1;
462    private static final int TYPE_RECEIVER = 2;
463    private static final int TYPE_SERVICE = 3;
464    private static final int TYPE_PROVIDER = 4;
465    @IntDef(prefix = { "TYPE_" }, value = {
466            TYPE_UNKNOWN,
467            TYPE_ACTIVITY,
468            TYPE_RECEIVER,
469            TYPE_SERVICE,
470            TYPE_PROVIDER,
471    })
472    @Retention(RetentionPolicy.SOURCE)
473    public @interface ComponentType {}
474
475    /**
476     * Timeout (in milliseconds) after which the watchdog should declare that
477     * our handler thread is wedged.  The usual default for such things is one
478     * minute but we sometimes do very lengthy I/O operations on this thread,
479     * such as installing multi-gigabyte applications, so ours needs to be longer.
480     */
481    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
482
483    /**
484     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
485     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
486     * settings entry if available, otherwise we use the hardcoded default.  If it's been
487     * more than this long since the last fstrim, we force one during the boot sequence.
488     *
489     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
490     * one gets run at the next available charging+idle time.  This final mandatory
491     * no-fstrim check kicks in only of the other scheduling criteria is never met.
492     */
493    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
494
495    /**
496     * Whether verification is enabled by default.
497     */
498    private static final boolean DEFAULT_VERIFY_ENABLE = true;
499
500    /**
501     * The default maximum time to wait for the verification agent to return in
502     * milliseconds.
503     */
504    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
505
506    /**
507     * The default response for package verification timeout.
508     *
509     * This can be either PackageManager.VERIFICATION_ALLOW or
510     * PackageManager.VERIFICATION_REJECT.
511     */
512    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
513
514    static final String PLATFORM_PACKAGE_NAME = "android";
515
516    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
517
518    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
519            DEFAULT_CONTAINER_PACKAGE,
520            "com.android.defcontainer.DefaultContainerService");
521
522    private static final String KILL_APP_REASON_GIDS_CHANGED =
523            "permission grant or revoke changed gids";
524
525    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
526            "permissions revoked";
527
528    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
529
530    private static final String PACKAGE_SCHEME = "package";
531
532    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
533
534    /** Permission grant: not grant the permission. */
535    private static final int GRANT_DENIED = 1;
536
537    /** Permission grant: grant the permission as an install permission. */
538    private static final int GRANT_INSTALL = 2;
539
540    /** Permission grant: grant the permission as a runtime one. */
541    private static final int GRANT_RUNTIME = 3;
542
543    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
544    private static final int GRANT_UPGRADE = 4;
545
546    /** Canonical intent used to identify what counts as a "web browser" app */
547    private static final Intent sBrowserIntent;
548    static {
549        sBrowserIntent = new Intent();
550        sBrowserIntent.setAction(Intent.ACTION_VIEW);
551        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
552        sBrowserIntent.setData(Uri.parse("http:"));
553    }
554
555    /**
556     * The set of all protected actions [i.e. those actions for which a high priority
557     * intent filter is disallowed].
558     */
559    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
560    static {
561        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
562        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
563        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
564        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
565    }
566
567    // Compilation reasons.
568    public static final int REASON_FIRST_BOOT = 0;
569    public static final int REASON_BOOT = 1;
570    public static final int REASON_INSTALL = 2;
571    public static final int REASON_BACKGROUND_DEXOPT = 3;
572    public static final int REASON_AB_OTA = 4;
573    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
574
575    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
576
577    /** All dangerous permission names in the same order as the events in MetricsEvent */
578    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
579            Manifest.permission.READ_CALENDAR,
580            Manifest.permission.WRITE_CALENDAR,
581            Manifest.permission.CAMERA,
582            Manifest.permission.READ_CONTACTS,
583            Manifest.permission.WRITE_CONTACTS,
584            Manifest.permission.GET_ACCOUNTS,
585            Manifest.permission.ACCESS_FINE_LOCATION,
586            Manifest.permission.ACCESS_COARSE_LOCATION,
587            Manifest.permission.RECORD_AUDIO,
588            Manifest.permission.READ_PHONE_STATE,
589            Manifest.permission.CALL_PHONE,
590            Manifest.permission.READ_CALL_LOG,
591            Manifest.permission.WRITE_CALL_LOG,
592            Manifest.permission.ADD_VOICEMAIL,
593            Manifest.permission.USE_SIP,
594            Manifest.permission.PROCESS_OUTGOING_CALLS,
595            Manifest.permission.READ_CELL_BROADCASTS,
596            Manifest.permission.BODY_SENSORS,
597            Manifest.permission.SEND_SMS,
598            Manifest.permission.RECEIVE_SMS,
599            Manifest.permission.READ_SMS,
600            Manifest.permission.RECEIVE_WAP_PUSH,
601            Manifest.permission.RECEIVE_MMS,
602            Manifest.permission.READ_EXTERNAL_STORAGE,
603            Manifest.permission.WRITE_EXTERNAL_STORAGE,
604            Manifest.permission.READ_PHONE_NUMBERS,
605            Manifest.permission.ANSWER_PHONE_CALLS);
606
607
608    /**
609     * Version number for the package parser cache. Increment this whenever the format or
610     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
611     */
612    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
613
614    /**
615     * Whether the package parser cache is enabled.
616     */
617    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
618
619    final ServiceThread mHandlerThread;
620
621    final PackageHandler mHandler;
622
623    private final ProcessLoggingHandler mProcessLoggingHandler;
624
625    /**
626     * Messages for {@link #mHandler} that need to wait for system ready before
627     * being dispatched.
628     */
629    private ArrayList<Message> mPostSystemReadyMessages;
630
631    final int mSdkVersion = Build.VERSION.SDK_INT;
632
633    final Context mContext;
634    final boolean mFactoryTest;
635    final boolean mOnlyCore;
636    final DisplayMetrics mMetrics;
637    final int mDefParseFlags;
638    final String[] mSeparateProcesses;
639    final boolean mIsUpgrade;
640    final boolean mIsPreNUpgrade;
641    final boolean mIsPreNMR1Upgrade;
642
643    // Have we told the Activity Manager to whitelist the default container service by uid yet?
644    @GuardedBy("mPackages")
645    boolean mDefaultContainerWhitelisted = false;
646
647    @GuardedBy("mPackages")
648    private boolean mDexOptDialogShown;
649
650    /** The location for ASEC container files on internal storage. */
651    final String mAsecInternalPath;
652
653    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
654    // LOCK HELD.  Can be called with mInstallLock held.
655    @GuardedBy("mInstallLock")
656    final Installer mInstaller;
657
658    /** Directory where installed third-party apps stored */
659    final File mAppInstallDir;
660
661    /**
662     * Directory to which applications installed internally have their
663     * 32 bit native libraries copied.
664     */
665    private File mAppLib32InstallDir;
666
667    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
668    // apps.
669    final File mDrmAppPrivateInstallDir;
670
671    // ----------------------------------------------------------------
672
673    // Lock for state used when installing and doing other long running
674    // operations.  Methods that must be called with this lock held have
675    // the suffix "LI".
676    final Object mInstallLock = new Object();
677
678    // ----------------------------------------------------------------
679
680    // Keys are String (package name), values are Package.  This also serves
681    // as the lock for the global state.  Methods that must be called with
682    // this lock held have the prefix "LP".
683    @GuardedBy("mPackages")
684    final ArrayMap<String, PackageParser.Package> mPackages =
685            new ArrayMap<String, PackageParser.Package>();
686
687    final ArrayMap<String, Set<String>> mKnownCodebase =
688            new ArrayMap<String, Set<String>>();
689
690    // Keys are isolated uids and values are the uid of the application
691    // that created the isolated proccess.
692    @GuardedBy("mPackages")
693    final SparseIntArray mIsolatedOwners = new SparseIntArray();
694
695    /**
696     * Tracks new system packages [received in an OTA] that we expect to
697     * find updated user-installed versions. Keys are package name, values
698     * are package location.
699     */
700    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
701    /**
702     * Tracks high priority intent filters for protected actions. During boot, certain
703     * filter actions are protected and should never be allowed to have a high priority
704     * intent filter for them. However, there is one, and only one exception -- the
705     * setup wizard. It must be able to define a high priority intent filter for these
706     * actions to ensure there are no escapes from the wizard. We need to delay processing
707     * of these during boot as we need to look at all of the system packages in order
708     * to know which component is the setup wizard.
709     */
710    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
711    /**
712     * Whether or not processing protected filters should be deferred.
713     */
714    private boolean mDeferProtectedFilters = true;
715
716    /**
717     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
718     */
719    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
720    /**
721     * Whether or not system app permissions should be promoted from install to runtime.
722     */
723    boolean mPromoteSystemApps;
724
725    @GuardedBy("mPackages")
726    final Settings mSettings;
727
728    /**
729     * Set of package names that are currently "frozen", which means active
730     * surgery is being done on the code/data for that package. The platform
731     * will refuse to launch frozen packages to avoid race conditions.
732     *
733     * @see PackageFreezer
734     */
735    @GuardedBy("mPackages")
736    final ArraySet<String> mFrozenPackages = new ArraySet<>();
737
738    final ProtectedPackages mProtectedPackages;
739
740    @GuardedBy("mLoadedVolumes")
741    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
742
743    boolean mFirstBoot;
744
745    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
746
747    // System configuration read by SystemConfig.
748    final int[] mGlobalGids;
749    final SparseArray<ArraySet<String>> mSystemPermissions;
750    @GuardedBy("mAvailableFeatures")
751    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
752
753    // If mac_permissions.xml was found for seinfo labeling.
754    boolean mFoundPolicyFile;
755
756    private final InstantAppRegistry mInstantAppRegistry;
757
758    @GuardedBy("mPackages")
759    int mChangedPackagesSequenceNumber;
760    /**
761     * List of changed [installed, removed or updated] packages.
762     * mapping from user id -> sequence number -> package name
763     */
764    @GuardedBy("mPackages")
765    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
766    /**
767     * The sequence number of the last change to a package.
768     * mapping from user id -> package name -> sequence number
769     */
770    @GuardedBy("mPackages")
771    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
772
773    class PackageParserCallback implements PackageParser.Callback {
774        @Override public final boolean hasFeature(String feature) {
775            return PackageManagerService.this.hasSystemFeature(feature, 0);
776        }
777
778        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
779                Collection<PackageParser.Package> allPackages, String targetPackageName) {
780            List<PackageParser.Package> overlayPackages = null;
781            for (PackageParser.Package p : allPackages) {
782                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
783                    if (overlayPackages == null) {
784                        overlayPackages = new ArrayList<PackageParser.Package>();
785                    }
786                    overlayPackages.add(p);
787                }
788            }
789            if (overlayPackages != null) {
790                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
791                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
792                        return p1.mOverlayPriority - p2.mOverlayPriority;
793                    }
794                };
795                Collections.sort(overlayPackages, cmp);
796            }
797            return overlayPackages;
798        }
799
800        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
801                String targetPackageName, String targetPath) {
802            if ("android".equals(targetPackageName)) {
803                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
804                // native AssetManager.
805                return null;
806            }
807            List<PackageParser.Package> overlayPackages =
808                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
809            if (overlayPackages == null || overlayPackages.isEmpty()) {
810                return null;
811            }
812            List<String> overlayPathList = null;
813            for (PackageParser.Package overlayPackage : overlayPackages) {
814                if (targetPath == null) {
815                    if (overlayPathList == null) {
816                        overlayPathList = new ArrayList<String>();
817                    }
818                    overlayPathList.add(overlayPackage.baseCodePath);
819                    continue;
820                }
821
822                try {
823                    // Creates idmaps for system to parse correctly the Android manifest of the
824                    // target package.
825                    //
826                    // OverlayManagerService will update each of them with a correct gid from its
827                    // target package app id.
828                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
829                            UserHandle.getSharedAppGid(
830                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
831                    if (overlayPathList == null) {
832                        overlayPathList = new ArrayList<String>();
833                    }
834                    overlayPathList.add(overlayPackage.baseCodePath);
835                } catch (InstallerException e) {
836                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
837                            overlayPackage.baseCodePath);
838                }
839            }
840            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
841        }
842
843        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
844            synchronized (mPackages) {
845                return getStaticOverlayPathsLocked(
846                        mPackages.values(), targetPackageName, targetPath);
847            }
848        }
849
850        @Override public final String[] getOverlayApks(String targetPackageName) {
851            return getStaticOverlayPaths(targetPackageName, null);
852        }
853
854        @Override public final String[] getOverlayPaths(String targetPackageName,
855                String targetPath) {
856            return getStaticOverlayPaths(targetPackageName, targetPath);
857        }
858    };
859
860    class ParallelPackageParserCallback extends PackageParserCallback {
861        List<PackageParser.Package> mOverlayPackages = null;
862
863        void findStaticOverlayPackages() {
864            synchronized (mPackages) {
865                for (PackageParser.Package p : mPackages.values()) {
866                    if (p.mIsStaticOverlay) {
867                        if (mOverlayPackages == null) {
868                            mOverlayPackages = new ArrayList<PackageParser.Package>();
869                        }
870                        mOverlayPackages.add(p);
871                    }
872                }
873            }
874        }
875
876        @Override
877        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
878            // We can trust mOverlayPackages without holding mPackages because package uninstall
879            // can't happen while running parallel parsing.
880            // Moreover holding mPackages on each parsing thread causes dead-lock.
881            return mOverlayPackages == null ? null :
882                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
883        }
884    }
885
886    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
887    final ParallelPackageParserCallback mParallelPackageParserCallback =
888            new ParallelPackageParserCallback();
889
890    public static final class SharedLibraryEntry {
891        public final @Nullable String path;
892        public final @Nullable String apk;
893        public final @NonNull SharedLibraryInfo info;
894
895        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
896                String declaringPackageName, int declaringPackageVersionCode) {
897            path = _path;
898            apk = _apk;
899            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
900                    declaringPackageName, declaringPackageVersionCode), null);
901        }
902    }
903
904    // Currently known shared libraries.
905    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
906    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
907            new ArrayMap<>();
908
909    // All available activities, for your resolving pleasure.
910    final ActivityIntentResolver mActivities =
911            new ActivityIntentResolver();
912
913    // All available receivers, for your resolving pleasure.
914    final ActivityIntentResolver mReceivers =
915            new ActivityIntentResolver();
916
917    // All available services, for your resolving pleasure.
918    final ServiceIntentResolver mServices = new ServiceIntentResolver();
919
920    // All available providers, for your resolving pleasure.
921    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
922
923    // Mapping from provider base names (first directory in content URI codePath)
924    // to the provider information.
925    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
926            new ArrayMap<String, PackageParser.Provider>();
927
928    // Mapping from instrumentation class names to info about them.
929    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
930            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
931
932    // Mapping from permission names to info about them.
933    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
934            new ArrayMap<String, PackageParser.PermissionGroup>();
935
936    // Packages whose data we have transfered into another package, thus
937    // should no longer exist.
938    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
939
940    // Broadcast actions that are only available to the system.
941    @GuardedBy("mProtectedBroadcasts")
942    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
943
944    /** List of packages waiting for verification. */
945    final SparseArray<PackageVerificationState> mPendingVerification
946            = new SparseArray<PackageVerificationState>();
947
948    /** Set of packages associated with each app op permission. */
949    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
950
951    final PackageInstallerService mInstallerService;
952
953    private final PackageDexOptimizer mPackageDexOptimizer;
954    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
955    // is used by other apps).
956    private final DexManager mDexManager;
957
958    private AtomicInteger mNextMoveId = new AtomicInteger();
959    private final MoveCallbacks mMoveCallbacks;
960
961    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
962
963    // Cache of users who need badging.
964    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
965
966    /** Token for keys in mPendingVerification. */
967    private int mPendingVerificationToken = 0;
968
969    volatile boolean mSystemReady;
970    volatile boolean mSafeMode;
971    volatile boolean mHasSystemUidErrors;
972    private volatile boolean mEphemeralAppsDisabled;
973
974    ApplicationInfo mAndroidApplication;
975    final ActivityInfo mResolveActivity = new ActivityInfo();
976    final ResolveInfo mResolveInfo = new ResolveInfo();
977    ComponentName mResolveComponentName;
978    PackageParser.Package mPlatformPackage;
979    ComponentName mCustomResolverComponentName;
980
981    boolean mResolverReplaced = false;
982
983    private final @Nullable ComponentName mIntentFilterVerifierComponent;
984    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
985
986    private int mIntentFilterVerificationToken = 0;
987
988    /** The service connection to the ephemeral resolver */
989    final EphemeralResolverConnection mInstantAppResolverConnection;
990    /** Component used to show resolver settings for Instant Apps */
991    final ComponentName mInstantAppResolverSettingsComponent;
992
993    /** Activity used to install instant applications */
994    ActivityInfo mInstantAppInstallerActivity;
995    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
996
997    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
998            = new SparseArray<IntentFilterVerificationState>();
999
1000    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1001
1002    // List of packages names to keep cached, even if they are uninstalled for all users
1003    private List<String> mKeepUninstalledPackages;
1004
1005    private UserManagerInternal mUserManagerInternal;
1006
1007    private DeviceIdleController.LocalService mDeviceIdleController;
1008
1009    private File mCacheDir;
1010
1011    private ArraySet<String> mPrivappPermissionsViolations;
1012
1013    private Future<?> mPrepareAppDataFuture;
1014
1015    private static class IFVerificationParams {
1016        PackageParser.Package pkg;
1017        boolean replacing;
1018        int userId;
1019        int verifierUid;
1020
1021        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1022                int _userId, int _verifierUid) {
1023            pkg = _pkg;
1024            replacing = _replacing;
1025            userId = _userId;
1026            replacing = _replacing;
1027            verifierUid = _verifierUid;
1028        }
1029    }
1030
1031    private interface IntentFilterVerifier<T extends IntentFilter> {
1032        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1033                                               T filter, String packageName);
1034        void startVerifications(int userId);
1035        void receiveVerificationResponse(int verificationId);
1036    }
1037
1038    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1039        private Context mContext;
1040        private ComponentName mIntentFilterVerifierComponent;
1041        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1042
1043        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1044            mContext = context;
1045            mIntentFilterVerifierComponent = verifierComponent;
1046        }
1047
1048        private String getDefaultScheme() {
1049            return IntentFilter.SCHEME_HTTPS;
1050        }
1051
1052        @Override
1053        public void startVerifications(int userId) {
1054            // Launch verifications requests
1055            int count = mCurrentIntentFilterVerifications.size();
1056            for (int n=0; n<count; n++) {
1057                int verificationId = mCurrentIntentFilterVerifications.get(n);
1058                final IntentFilterVerificationState ivs =
1059                        mIntentFilterVerificationStates.get(verificationId);
1060
1061                String packageName = ivs.getPackageName();
1062
1063                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1064                final int filterCount = filters.size();
1065                ArraySet<String> domainsSet = new ArraySet<>();
1066                for (int m=0; m<filterCount; m++) {
1067                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1068                    domainsSet.addAll(filter.getHostsList());
1069                }
1070                synchronized (mPackages) {
1071                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1072                            packageName, domainsSet) != null) {
1073                        scheduleWriteSettingsLocked();
1074                    }
1075                }
1076                sendVerificationRequest(verificationId, ivs);
1077            }
1078            mCurrentIntentFilterVerifications.clear();
1079        }
1080
1081        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1082            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1083            verificationIntent.putExtra(
1084                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1085                    verificationId);
1086            verificationIntent.putExtra(
1087                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1088                    getDefaultScheme());
1089            verificationIntent.putExtra(
1090                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1091                    ivs.getHostsString());
1092            verificationIntent.putExtra(
1093                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1094                    ivs.getPackageName());
1095            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1096            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1097
1098            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1099            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1100                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1101                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1102
1103            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1104            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1105                    "Sending IntentFilter verification broadcast");
1106        }
1107
1108        public void receiveVerificationResponse(int verificationId) {
1109            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1110
1111            final boolean verified = ivs.isVerified();
1112
1113            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1114            final int count = filters.size();
1115            if (DEBUG_DOMAIN_VERIFICATION) {
1116                Slog.i(TAG, "Received verification response " + verificationId
1117                        + " for " + count + " filters, verified=" + verified);
1118            }
1119            for (int n=0; n<count; n++) {
1120                PackageParser.ActivityIntentInfo filter = filters.get(n);
1121                filter.setVerified(verified);
1122
1123                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1124                        + " verified with result:" + verified + " and hosts:"
1125                        + ivs.getHostsString());
1126            }
1127
1128            mIntentFilterVerificationStates.remove(verificationId);
1129
1130            final String packageName = ivs.getPackageName();
1131            IntentFilterVerificationInfo ivi = null;
1132
1133            synchronized (mPackages) {
1134                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1135            }
1136            if (ivi == null) {
1137                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1138                        + verificationId + " packageName:" + packageName);
1139                return;
1140            }
1141            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1142                    "Updating IntentFilterVerificationInfo for package " + packageName
1143                            +" verificationId:" + verificationId);
1144
1145            synchronized (mPackages) {
1146                if (verified) {
1147                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1148                } else {
1149                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1150                }
1151                scheduleWriteSettingsLocked();
1152
1153                final int userId = ivs.getUserId();
1154                if (userId != UserHandle.USER_ALL) {
1155                    final int userStatus =
1156                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1157
1158                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1159                    boolean needUpdate = false;
1160
1161                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1162                    // already been set by the User thru the Disambiguation dialog
1163                    switch (userStatus) {
1164                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1165                            if (verified) {
1166                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1167                            } else {
1168                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1169                            }
1170                            needUpdate = true;
1171                            break;
1172
1173                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1174                            if (verified) {
1175                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1176                                needUpdate = true;
1177                            }
1178                            break;
1179
1180                        default:
1181                            // Nothing to do
1182                    }
1183
1184                    if (needUpdate) {
1185                        mSettings.updateIntentFilterVerificationStatusLPw(
1186                                packageName, updatedStatus, userId);
1187                        scheduleWritePackageRestrictionsLocked(userId);
1188                    }
1189                }
1190            }
1191        }
1192
1193        @Override
1194        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1195                    ActivityIntentInfo filter, String packageName) {
1196            if (!hasValidDomains(filter)) {
1197                return false;
1198            }
1199            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1200            if (ivs == null) {
1201                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1202                        packageName);
1203            }
1204            if (DEBUG_DOMAIN_VERIFICATION) {
1205                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1206            }
1207            ivs.addFilter(filter);
1208            return true;
1209        }
1210
1211        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1212                int userId, int verificationId, String packageName) {
1213            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1214                    verifierUid, userId, packageName);
1215            ivs.setPendingState();
1216            synchronized (mPackages) {
1217                mIntentFilterVerificationStates.append(verificationId, ivs);
1218                mCurrentIntentFilterVerifications.add(verificationId);
1219            }
1220            return ivs;
1221        }
1222    }
1223
1224    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1225        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1226                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1227                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1228    }
1229
1230    // Set of pending broadcasts for aggregating enable/disable of components.
1231    static class PendingPackageBroadcasts {
1232        // for each user id, a map of <package name -> components within that package>
1233        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1234
1235        public PendingPackageBroadcasts() {
1236            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1237        }
1238
1239        public ArrayList<String> get(int userId, String packageName) {
1240            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1241            return packages.get(packageName);
1242        }
1243
1244        public void put(int userId, String packageName, ArrayList<String> components) {
1245            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1246            packages.put(packageName, components);
1247        }
1248
1249        public void remove(int userId, String packageName) {
1250            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1251            if (packages != null) {
1252                packages.remove(packageName);
1253            }
1254        }
1255
1256        public void remove(int userId) {
1257            mUidMap.remove(userId);
1258        }
1259
1260        public int userIdCount() {
1261            return mUidMap.size();
1262        }
1263
1264        public int userIdAt(int n) {
1265            return mUidMap.keyAt(n);
1266        }
1267
1268        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1269            return mUidMap.get(userId);
1270        }
1271
1272        public int size() {
1273            // total number of pending broadcast entries across all userIds
1274            int num = 0;
1275            for (int i = 0; i< mUidMap.size(); i++) {
1276                num += mUidMap.valueAt(i).size();
1277            }
1278            return num;
1279        }
1280
1281        public void clear() {
1282            mUidMap.clear();
1283        }
1284
1285        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1286            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1287            if (map == null) {
1288                map = new ArrayMap<String, ArrayList<String>>();
1289                mUidMap.put(userId, map);
1290            }
1291            return map;
1292        }
1293    }
1294    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1295
1296    // Service Connection to remote media container service to copy
1297    // package uri's from external media onto secure containers
1298    // or internal storage.
1299    private IMediaContainerService mContainerService = null;
1300
1301    static final int SEND_PENDING_BROADCAST = 1;
1302    static final int MCS_BOUND = 3;
1303    static final int END_COPY = 4;
1304    static final int INIT_COPY = 5;
1305    static final int MCS_UNBIND = 6;
1306    static final int START_CLEANING_PACKAGE = 7;
1307    static final int FIND_INSTALL_LOC = 8;
1308    static final int POST_INSTALL = 9;
1309    static final int MCS_RECONNECT = 10;
1310    static final int MCS_GIVE_UP = 11;
1311    static final int UPDATED_MEDIA_STATUS = 12;
1312    static final int WRITE_SETTINGS = 13;
1313    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1314    static final int PACKAGE_VERIFIED = 15;
1315    static final int CHECK_PENDING_VERIFICATION = 16;
1316    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1317    static final int INTENT_FILTER_VERIFIED = 18;
1318    static final int WRITE_PACKAGE_LIST = 19;
1319    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1320
1321    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1322
1323    // Delay time in millisecs
1324    static final int BROADCAST_DELAY = 10 * 1000;
1325
1326    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1327            2 * 60 * 60 * 1000L; /* two hours */
1328
1329    static UserManagerService sUserManager;
1330
1331    // Stores a list of users whose package restrictions file needs to be updated
1332    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1333
1334    final private DefaultContainerConnection mDefContainerConn =
1335            new DefaultContainerConnection();
1336    class DefaultContainerConnection implements ServiceConnection {
1337        public void onServiceConnected(ComponentName name, IBinder service) {
1338            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1339            final IMediaContainerService imcs = IMediaContainerService.Stub
1340                    .asInterface(Binder.allowBlocking(service));
1341            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1342        }
1343
1344        public void onServiceDisconnected(ComponentName name) {
1345            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1346        }
1347    }
1348
1349    // Recordkeeping of restore-after-install operations that are currently in flight
1350    // between the Package Manager and the Backup Manager
1351    static class PostInstallData {
1352        public InstallArgs args;
1353        public PackageInstalledInfo res;
1354
1355        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1356            args = _a;
1357            res = _r;
1358        }
1359    }
1360
1361    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1362    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1363
1364    // XML tags for backup/restore of various bits of state
1365    private static final String TAG_PREFERRED_BACKUP = "pa";
1366    private static final String TAG_DEFAULT_APPS = "da";
1367    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1368
1369    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1370    private static final String TAG_ALL_GRANTS = "rt-grants";
1371    private static final String TAG_GRANT = "grant";
1372    private static final String ATTR_PACKAGE_NAME = "pkg";
1373
1374    private static final String TAG_PERMISSION = "perm";
1375    private static final String ATTR_PERMISSION_NAME = "name";
1376    private static final String ATTR_IS_GRANTED = "g";
1377    private static final String ATTR_USER_SET = "set";
1378    private static final String ATTR_USER_FIXED = "fixed";
1379    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1380
1381    // System/policy permission grants are not backed up
1382    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1383            FLAG_PERMISSION_POLICY_FIXED
1384            | FLAG_PERMISSION_SYSTEM_FIXED
1385            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1386
1387    // And we back up these user-adjusted states
1388    private static final int USER_RUNTIME_GRANT_MASK =
1389            FLAG_PERMISSION_USER_SET
1390            | FLAG_PERMISSION_USER_FIXED
1391            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1392
1393    final @Nullable String mRequiredVerifierPackage;
1394    final @NonNull String mRequiredInstallerPackage;
1395    final @NonNull String mRequiredUninstallerPackage;
1396    final @Nullable String mSetupWizardPackage;
1397    final @Nullable String mStorageManagerPackage;
1398    final @NonNull String mServicesSystemSharedLibraryPackageName;
1399    final @NonNull String mSharedSystemSharedLibraryPackageName;
1400
1401    final boolean mPermissionReviewRequired;
1402
1403    private final PackageUsage mPackageUsage = new PackageUsage();
1404    private final CompilerStats mCompilerStats = new CompilerStats();
1405
1406    class PackageHandler extends Handler {
1407        private boolean mBound = false;
1408        final ArrayList<HandlerParams> mPendingInstalls =
1409            new ArrayList<HandlerParams>();
1410
1411        private boolean connectToService() {
1412            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1413                    " DefaultContainerService");
1414            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1415            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1416            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1417                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1418                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1419                mBound = true;
1420                return true;
1421            }
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1423            return false;
1424        }
1425
1426        private void disconnectService() {
1427            mContainerService = null;
1428            mBound = false;
1429            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1430            mContext.unbindService(mDefContainerConn);
1431            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1432        }
1433
1434        PackageHandler(Looper looper) {
1435            super(looper);
1436        }
1437
1438        public void handleMessage(Message msg) {
1439            try {
1440                doHandleMessage(msg);
1441            } finally {
1442                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1443            }
1444        }
1445
1446        void doHandleMessage(Message msg) {
1447            switch (msg.what) {
1448                case INIT_COPY: {
1449                    HandlerParams params = (HandlerParams) msg.obj;
1450                    int idx = mPendingInstalls.size();
1451                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1452                    // If a bind was already initiated we dont really
1453                    // need to do anything. The pending install
1454                    // will be processed later on.
1455                    if (!mBound) {
1456                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1457                                System.identityHashCode(mHandler));
1458                        // If this is the only one pending we might
1459                        // have to bind to the service again.
1460                        if (!connectToService()) {
1461                            Slog.e(TAG, "Failed to bind to media container service");
1462                            params.serviceError();
1463                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1464                                    System.identityHashCode(mHandler));
1465                            if (params.traceMethod != null) {
1466                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1467                                        params.traceCookie);
1468                            }
1469                            return;
1470                        } else {
1471                            // Once we bind to the service, the first
1472                            // pending request will be processed.
1473                            mPendingInstalls.add(idx, params);
1474                        }
1475                    } else {
1476                        mPendingInstalls.add(idx, params);
1477                        // Already bound to the service. Just make
1478                        // sure we trigger off processing the first request.
1479                        if (idx == 0) {
1480                            mHandler.sendEmptyMessage(MCS_BOUND);
1481                        }
1482                    }
1483                    break;
1484                }
1485                case MCS_BOUND: {
1486                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1487                    if (msg.obj != null) {
1488                        mContainerService = (IMediaContainerService) msg.obj;
1489                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1490                                System.identityHashCode(mHandler));
1491                    }
1492                    if (mContainerService == null) {
1493                        if (!mBound) {
1494                            // Something seriously wrong since we are not bound and we are not
1495                            // waiting for connection. Bail out.
1496                            Slog.e(TAG, "Cannot bind to media container service");
1497                            for (HandlerParams params : mPendingInstalls) {
1498                                // Indicate service bind error
1499                                params.serviceError();
1500                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1501                                        System.identityHashCode(params));
1502                                if (params.traceMethod != null) {
1503                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1504                                            params.traceMethod, params.traceCookie);
1505                                }
1506                                return;
1507                            }
1508                            mPendingInstalls.clear();
1509                        } else {
1510                            Slog.w(TAG, "Waiting to connect to media container service");
1511                        }
1512                    } else if (mPendingInstalls.size() > 0) {
1513                        HandlerParams params = mPendingInstalls.get(0);
1514                        if (params != null) {
1515                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1516                                    System.identityHashCode(params));
1517                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1518                            if (params.startCopy()) {
1519                                // We are done...  look for more work or to
1520                                // go idle.
1521                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1522                                        "Checking for more work or unbind...");
1523                                // Delete pending install
1524                                if (mPendingInstalls.size() > 0) {
1525                                    mPendingInstalls.remove(0);
1526                                }
1527                                if (mPendingInstalls.size() == 0) {
1528                                    if (mBound) {
1529                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1530                                                "Posting delayed MCS_UNBIND");
1531                                        removeMessages(MCS_UNBIND);
1532                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1533                                        // Unbind after a little delay, to avoid
1534                                        // continual thrashing.
1535                                        sendMessageDelayed(ubmsg, 10000);
1536                                    }
1537                                } else {
1538                                    // There are more pending requests in queue.
1539                                    // Just post MCS_BOUND message to trigger processing
1540                                    // of next pending install.
1541                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1542                                            "Posting MCS_BOUND for next work");
1543                                    mHandler.sendEmptyMessage(MCS_BOUND);
1544                                }
1545                            }
1546                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1547                        }
1548                    } else {
1549                        // Should never happen ideally.
1550                        Slog.w(TAG, "Empty queue");
1551                    }
1552                    break;
1553                }
1554                case MCS_RECONNECT: {
1555                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1556                    if (mPendingInstalls.size() > 0) {
1557                        if (mBound) {
1558                            disconnectService();
1559                        }
1560                        if (!connectToService()) {
1561                            Slog.e(TAG, "Failed to bind to media container service");
1562                            for (HandlerParams params : mPendingInstalls) {
1563                                // Indicate service bind error
1564                                params.serviceError();
1565                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1566                                        System.identityHashCode(params));
1567                            }
1568                            mPendingInstalls.clear();
1569                        }
1570                    }
1571                    break;
1572                }
1573                case MCS_UNBIND: {
1574                    // If there is no actual work left, then time to unbind.
1575                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1576
1577                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1578                        if (mBound) {
1579                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1580
1581                            disconnectService();
1582                        }
1583                    } else if (mPendingInstalls.size() > 0) {
1584                        // There are more pending requests in queue.
1585                        // Just post MCS_BOUND message to trigger processing
1586                        // of next pending install.
1587                        mHandler.sendEmptyMessage(MCS_BOUND);
1588                    }
1589
1590                    break;
1591                }
1592                case MCS_GIVE_UP: {
1593                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1594                    HandlerParams params = mPendingInstalls.remove(0);
1595                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1596                            System.identityHashCode(params));
1597                    break;
1598                }
1599                case SEND_PENDING_BROADCAST: {
1600                    String packages[];
1601                    ArrayList<String> components[];
1602                    int size = 0;
1603                    int uids[];
1604                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1605                    synchronized (mPackages) {
1606                        if (mPendingBroadcasts == null) {
1607                            return;
1608                        }
1609                        size = mPendingBroadcasts.size();
1610                        if (size <= 0) {
1611                            // Nothing to be done. Just return
1612                            return;
1613                        }
1614                        packages = new String[size];
1615                        components = new ArrayList[size];
1616                        uids = new int[size];
1617                        int i = 0;  // filling out the above arrays
1618
1619                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1620                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1621                            Iterator<Map.Entry<String, ArrayList<String>>> it
1622                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1623                                            .entrySet().iterator();
1624                            while (it.hasNext() && i < size) {
1625                                Map.Entry<String, ArrayList<String>> ent = it.next();
1626                                packages[i] = ent.getKey();
1627                                components[i] = ent.getValue();
1628                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1629                                uids[i] = (ps != null)
1630                                        ? UserHandle.getUid(packageUserId, ps.appId)
1631                                        : -1;
1632                                i++;
1633                            }
1634                        }
1635                        size = i;
1636                        mPendingBroadcasts.clear();
1637                    }
1638                    // Send broadcasts
1639                    for (int i = 0; i < size; i++) {
1640                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1641                    }
1642                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1643                    break;
1644                }
1645                case START_CLEANING_PACKAGE: {
1646                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1647                    final String packageName = (String)msg.obj;
1648                    final int userId = msg.arg1;
1649                    final boolean andCode = msg.arg2 != 0;
1650                    synchronized (mPackages) {
1651                        if (userId == UserHandle.USER_ALL) {
1652                            int[] users = sUserManager.getUserIds();
1653                            for (int user : users) {
1654                                mSettings.addPackageToCleanLPw(
1655                                        new PackageCleanItem(user, packageName, andCode));
1656                            }
1657                        } else {
1658                            mSettings.addPackageToCleanLPw(
1659                                    new PackageCleanItem(userId, packageName, andCode));
1660                        }
1661                    }
1662                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1663                    startCleaningPackages();
1664                } break;
1665                case POST_INSTALL: {
1666                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1667
1668                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1669                    final boolean didRestore = (msg.arg2 != 0);
1670                    mRunningInstalls.delete(msg.arg1);
1671
1672                    if (data != null) {
1673                        InstallArgs args = data.args;
1674                        PackageInstalledInfo parentRes = data.res;
1675
1676                        final boolean grantPermissions = (args.installFlags
1677                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1678                        final boolean killApp = (args.installFlags
1679                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1680                        final boolean virtualPreload = ((args.installFlags
1681                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1682                        final String[] grantedPermissions = args.installGrantPermissions;
1683
1684                        // Handle the parent package
1685                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1686                                virtualPreload, grantedPermissions, didRestore,
1687                                args.installerPackageName, args.observer);
1688
1689                        // Handle the child packages
1690                        final int childCount = (parentRes.addedChildPackages != null)
1691                                ? parentRes.addedChildPackages.size() : 0;
1692                        for (int i = 0; i < childCount; i++) {
1693                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1694                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1695                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1696                                    args.installerPackageName, args.observer);
1697                        }
1698
1699                        // Log tracing if needed
1700                        if (args.traceMethod != null) {
1701                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1702                                    args.traceCookie);
1703                        }
1704                    } else {
1705                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1706                    }
1707
1708                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1709                } break;
1710                case UPDATED_MEDIA_STATUS: {
1711                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1712                    boolean reportStatus = msg.arg1 == 1;
1713                    boolean doGc = msg.arg2 == 1;
1714                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1715                    if (doGc) {
1716                        // Force a gc to clear up stale containers.
1717                        Runtime.getRuntime().gc();
1718                    }
1719                    if (msg.obj != null) {
1720                        @SuppressWarnings("unchecked")
1721                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1722                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1723                        // Unload containers
1724                        unloadAllContainers(args);
1725                    }
1726                    if (reportStatus) {
1727                        try {
1728                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1729                                    "Invoking StorageManagerService call back");
1730                            PackageHelper.getStorageManager().finishMediaUpdate();
1731                        } catch (RemoteException e) {
1732                            Log.e(TAG, "StorageManagerService not running?");
1733                        }
1734                    }
1735                } break;
1736                case WRITE_SETTINGS: {
1737                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1738                    synchronized (mPackages) {
1739                        removeMessages(WRITE_SETTINGS);
1740                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1741                        mSettings.writeLPr();
1742                        mDirtyUsers.clear();
1743                    }
1744                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1745                } break;
1746                case WRITE_PACKAGE_RESTRICTIONS: {
1747                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1748                    synchronized (mPackages) {
1749                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1750                        for (int userId : mDirtyUsers) {
1751                            mSettings.writePackageRestrictionsLPr(userId);
1752                        }
1753                        mDirtyUsers.clear();
1754                    }
1755                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1756                } break;
1757                case WRITE_PACKAGE_LIST: {
1758                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1759                    synchronized (mPackages) {
1760                        removeMessages(WRITE_PACKAGE_LIST);
1761                        mSettings.writePackageListLPr(msg.arg1);
1762                    }
1763                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1764                } break;
1765                case CHECK_PENDING_VERIFICATION: {
1766                    final int verificationId = msg.arg1;
1767                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1768
1769                    if ((state != null) && !state.timeoutExtended()) {
1770                        final InstallArgs args = state.getInstallArgs();
1771                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1772
1773                        Slog.i(TAG, "Verification timed out for " + originUri);
1774                        mPendingVerification.remove(verificationId);
1775
1776                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1777
1778                        final UserHandle user = args.getUser();
1779                        if (getDefaultVerificationResponse(user)
1780                                == PackageManager.VERIFICATION_ALLOW) {
1781                            Slog.i(TAG, "Continuing with installation of " + originUri);
1782                            state.setVerifierResponse(Binder.getCallingUid(),
1783                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1784                            broadcastPackageVerified(verificationId, originUri,
1785                                    PackageManager.VERIFICATION_ALLOW, user);
1786                            try {
1787                                ret = args.copyApk(mContainerService, true);
1788                            } catch (RemoteException e) {
1789                                Slog.e(TAG, "Could not contact the ContainerService");
1790                            }
1791                        } else {
1792                            broadcastPackageVerified(verificationId, originUri,
1793                                    PackageManager.VERIFICATION_REJECT, user);
1794                        }
1795
1796                        Trace.asyncTraceEnd(
1797                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1798
1799                        processPendingInstall(args, ret);
1800                        mHandler.sendEmptyMessage(MCS_UNBIND);
1801                    }
1802                    break;
1803                }
1804                case PACKAGE_VERIFIED: {
1805                    final int verificationId = msg.arg1;
1806
1807                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1808                    if (state == null) {
1809                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1810                        break;
1811                    }
1812
1813                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1814
1815                    state.setVerifierResponse(response.callerUid, response.code);
1816
1817                    if (state.isVerificationComplete()) {
1818                        mPendingVerification.remove(verificationId);
1819
1820                        final InstallArgs args = state.getInstallArgs();
1821                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1822
1823                        int ret;
1824                        if (state.isInstallAllowed()) {
1825                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1826                            broadcastPackageVerified(verificationId, originUri,
1827                                    response.code, state.getInstallArgs().getUser());
1828                            try {
1829                                ret = args.copyApk(mContainerService, true);
1830                            } catch (RemoteException e) {
1831                                Slog.e(TAG, "Could not contact the ContainerService");
1832                            }
1833                        } else {
1834                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1835                        }
1836
1837                        Trace.asyncTraceEnd(
1838                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1839
1840                        processPendingInstall(args, ret);
1841                        mHandler.sendEmptyMessage(MCS_UNBIND);
1842                    }
1843
1844                    break;
1845                }
1846                case START_INTENT_FILTER_VERIFICATIONS: {
1847                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1848                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1849                            params.replacing, params.pkg);
1850                    break;
1851                }
1852                case INTENT_FILTER_VERIFIED: {
1853                    final int verificationId = msg.arg1;
1854
1855                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1856                            verificationId);
1857                    if (state == null) {
1858                        Slog.w(TAG, "Invalid IntentFilter verification token "
1859                                + verificationId + " received");
1860                        break;
1861                    }
1862
1863                    final int userId = state.getUserId();
1864
1865                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1866                            "Processing IntentFilter verification with token:"
1867                            + verificationId + " and userId:" + userId);
1868
1869                    final IntentFilterVerificationResponse response =
1870                            (IntentFilterVerificationResponse) msg.obj;
1871
1872                    state.setVerifierResponse(response.callerUid, response.code);
1873
1874                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1875                            "IntentFilter verification with token:" + verificationId
1876                            + " and userId:" + userId
1877                            + " is settings verifier response with response code:"
1878                            + response.code);
1879
1880                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1881                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1882                                + response.getFailedDomainsString());
1883                    }
1884
1885                    if (state.isVerificationComplete()) {
1886                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1887                    } else {
1888                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1889                                "IntentFilter verification with token:" + verificationId
1890                                + " was not said to be complete");
1891                    }
1892
1893                    break;
1894                }
1895                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1896                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1897                            mInstantAppResolverConnection,
1898                            (InstantAppRequest) msg.obj,
1899                            mInstantAppInstallerActivity,
1900                            mHandler);
1901                }
1902            }
1903        }
1904    }
1905
1906    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1907            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1908            boolean launchedForRestore, String installerPackage,
1909            IPackageInstallObserver2 installObserver) {
1910        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1911            // Send the removed broadcasts
1912            if (res.removedInfo != null) {
1913                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1914            }
1915
1916            // Now that we successfully installed the package, grant runtime
1917            // permissions if requested before broadcasting the install. Also
1918            // for legacy apps in permission review mode we clear the permission
1919            // review flag which is used to emulate runtime permissions for
1920            // legacy apps.
1921            if (grantPermissions) {
1922                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1923            }
1924
1925            final boolean update = res.removedInfo != null
1926                    && res.removedInfo.removedPackage != null;
1927            final String origInstallerPackageName = res.removedInfo != null
1928                    ? res.removedInfo.installerPackageName : null;
1929
1930            // If this is the first time we have child packages for a disabled privileged
1931            // app that had no children, we grant requested runtime permissions to the new
1932            // children if the parent on the system image had them already granted.
1933            if (res.pkg.parentPackage != null) {
1934                synchronized (mPackages) {
1935                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1936                }
1937            }
1938
1939            synchronized (mPackages) {
1940                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1941            }
1942
1943            final String packageName = res.pkg.applicationInfo.packageName;
1944
1945            // Determine the set of users who are adding this package for
1946            // the first time vs. those who are seeing an update.
1947            int[] firstUsers = EMPTY_INT_ARRAY;
1948            int[] updateUsers = EMPTY_INT_ARRAY;
1949            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1950            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1951            for (int newUser : res.newUsers) {
1952                if (ps.getInstantApp(newUser)) {
1953                    continue;
1954                }
1955                if (allNewUsers) {
1956                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1957                    continue;
1958                }
1959                boolean isNew = true;
1960                for (int origUser : res.origUsers) {
1961                    if (origUser == newUser) {
1962                        isNew = false;
1963                        break;
1964                    }
1965                }
1966                if (isNew) {
1967                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1968                } else {
1969                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1970                }
1971            }
1972
1973            // Send installed broadcasts if the package is not a static shared lib.
1974            if (res.pkg.staticSharedLibName == null) {
1975                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1976
1977                // Send added for users that see the package for the first time
1978                // sendPackageAddedForNewUsers also deals with system apps
1979                int appId = UserHandle.getAppId(res.uid);
1980                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1981                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1982                        virtualPreload /*startReceiver*/, appId, firstUsers);
1983
1984                // Send added for users that don't see the package for the first time
1985                Bundle extras = new Bundle(1);
1986                extras.putInt(Intent.EXTRA_UID, res.uid);
1987                if (update) {
1988                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1989                }
1990                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1991                        extras, 0 /*flags*/,
1992                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1993                if (origInstallerPackageName != null) {
1994                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1995                            extras, 0 /*flags*/,
1996                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1997                }
1998
1999                // Send replaced for users that don't see the package for the first time
2000                if (update) {
2001                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2002                            packageName, extras, 0 /*flags*/,
2003                            null /*targetPackage*/, null /*finishedReceiver*/,
2004                            updateUsers);
2005                    if (origInstallerPackageName != null) {
2006                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2007                                extras, 0 /*flags*/,
2008                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
2009                    }
2010                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2011                            null /*package*/, null /*extras*/, 0 /*flags*/,
2012                            packageName /*targetPackage*/,
2013                            null /*finishedReceiver*/, updateUsers);
2014                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2015                    // First-install and we did a restore, so we're responsible for the
2016                    // first-launch broadcast.
2017                    if (DEBUG_BACKUP) {
2018                        Slog.i(TAG, "Post-restore of " + packageName
2019                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2020                    }
2021                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2022                }
2023
2024                // Send broadcast package appeared if forward locked/external for all users
2025                // treat asec-hosted packages like removable media on upgrade
2026                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2027                    if (DEBUG_INSTALL) {
2028                        Slog.i(TAG, "upgrading pkg " + res.pkg
2029                                + " is ASEC-hosted -> AVAILABLE");
2030                    }
2031                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2032                    ArrayList<String> pkgList = new ArrayList<>(1);
2033                    pkgList.add(packageName);
2034                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2035                }
2036            }
2037
2038            // Work that needs to happen on first install within each user
2039            if (firstUsers != null && firstUsers.length > 0) {
2040                synchronized (mPackages) {
2041                    for (int userId : firstUsers) {
2042                        // If this app is a browser and it's newly-installed for some
2043                        // users, clear any default-browser state in those users. The
2044                        // app's nature doesn't depend on the user, so we can just check
2045                        // its browser nature in any user and generalize.
2046                        if (packageIsBrowser(packageName, userId)) {
2047                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2048                        }
2049
2050                        // We may also need to apply pending (restored) runtime
2051                        // permission grants within these users.
2052                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2053                    }
2054                }
2055            }
2056
2057            // Log current value of "unknown sources" setting
2058            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2059                    getUnknownSourcesSettings());
2060
2061            // Remove the replaced package's older resources safely now
2062            // We delete after a gc for applications  on sdcard.
2063            if (res.removedInfo != null && res.removedInfo.args != null) {
2064                Runtime.getRuntime().gc();
2065                synchronized (mInstallLock) {
2066                    res.removedInfo.args.doPostDeleteLI(true);
2067                }
2068            } else {
2069                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2070                // and not block here.
2071                VMRuntime.getRuntime().requestConcurrentGC();
2072            }
2073
2074            // Notify DexManager that the package was installed for new users.
2075            // The updated users should already be indexed and the package code paths
2076            // should not change.
2077            // Don't notify the manager for ephemeral apps as they are not expected to
2078            // survive long enough to benefit of background optimizations.
2079            for (int userId : firstUsers) {
2080                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2081                // There's a race currently where some install events may interleave with an uninstall.
2082                // This can lead to package info being null (b/36642664).
2083                if (info != null) {
2084                    mDexManager.notifyPackageInstalled(info, userId);
2085                }
2086            }
2087        }
2088
2089        // If someone is watching installs - notify them
2090        if (installObserver != null) {
2091            try {
2092                Bundle extras = extrasForInstallResult(res);
2093                installObserver.onPackageInstalled(res.name, res.returnCode,
2094                        res.returnMsg, extras);
2095            } catch (RemoteException e) {
2096                Slog.i(TAG, "Observer no longer exists.");
2097            }
2098        }
2099    }
2100
2101    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2102            PackageParser.Package pkg) {
2103        if (pkg.parentPackage == null) {
2104            return;
2105        }
2106        if (pkg.requestedPermissions == null) {
2107            return;
2108        }
2109        final PackageSetting disabledSysParentPs = mSettings
2110                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2111        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2112                || !disabledSysParentPs.isPrivileged()
2113                || (disabledSysParentPs.childPackageNames != null
2114                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2115            return;
2116        }
2117        final int[] allUserIds = sUserManager.getUserIds();
2118        final int permCount = pkg.requestedPermissions.size();
2119        for (int i = 0; i < permCount; i++) {
2120            String permission = pkg.requestedPermissions.get(i);
2121            BasePermission bp = mSettings.mPermissions.get(permission);
2122            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2123                continue;
2124            }
2125            for (int userId : allUserIds) {
2126                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2127                        permission, userId)) {
2128                    grantRuntimePermission(pkg.packageName, permission, userId);
2129                }
2130            }
2131        }
2132    }
2133
2134    private StorageEventListener mStorageListener = new StorageEventListener() {
2135        @Override
2136        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2137            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2138                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2139                    final String volumeUuid = vol.getFsUuid();
2140
2141                    // Clean up any users or apps that were removed or recreated
2142                    // while this volume was missing
2143                    sUserManager.reconcileUsers(volumeUuid);
2144                    reconcileApps(volumeUuid);
2145
2146                    // Clean up any install sessions that expired or were
2147                    // cancelled while this volume was missing
2148                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2149
2150                    loadPrivatePackages(vol);
2151
2152                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2153                    unloadPrivatePackages(vol);
2154                }
2155            }
2156
2157            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2158                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2159                    updateExternalMediaStatus(true, false);
2160                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2161                    updateExternalMediaStatus(false, false);
2162                }
2163            }
2164        }
2165
2166        @Override
2167        public void onVolumeForgotten(String fsUuid) {
2168            if (TextUtils.isEmpty(fsUuid)) {
2169                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2170                return;
2171            }
2172
2173            // Remove any apps installed on the forgotten volume
2174            synchronized (mPackages) {
2175                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2176                for (PackageSetting ps : packages) {
2177                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2178                    deletePackageVersioned(new VersionedPackage(ps.name,
2179                            PackageManager.VERSION_CODE_HIGHEST),
2180                            new LegacyPackageDeleteObserver(null).getBinder(),
2181                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2182                    // Try very hard to release any references to this package
2183                    // so we don't risk the system server being killed due to
2184                    // open FDs
2185                    AttributeCache.instance().removePackage(ps.name);
2186                }
2187
2188                mSettings.onVolumeForgotten(fsUuid);
2189                mSettings.writeLPr();
2190            }
2191        }
2192    };
2193
2194    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2195            String[] grantedPermissions) {
2196        for (int userId : userIds) {
2197            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2198        }
2199    }
2200
2201    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2202            String[] grantedPermissions) {
2203        PackageSetting ps = (PackageSetting) pkg.mExtras;
2204        if (ps == null) {
2205            return;
2206        }
2207
2208        PermissionsState permissionsState = ps.getPermissionsState();
2209
2210        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2211                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2212
2213        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2214                >= Build.VERSION_CODES.M;
2215
2216        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2217
2218        for (String permission : pkg.requestedPermissions) {
2219            final BasePermission bp;
2220            synchronized (mPackages) {
2221                bp = mSettings.mPermissions.get(permission);
2222            }
2223            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2224                    && (!instantApp || bp.isInstant())
2225                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2226                    && (grantedPermissions == null
2227                           || ArrayUtils.contains(grantedPermissions, permission))) {
2228                final int flags = permissionsState.getPermissionFlags(permission, userId);
2229                if (supportsRuntimePermissions) {
2230                    // Installer cannot change immutable permissions.
2231                    if ((flags & immutableFlags) == 0) {
2232                        grantRuntimePermission(pkg.packageName, permission, userId);
2233                    }
2234                } else if (mPermissionReviewRequired) {
2235                    // In permission review mode we clear the review flag when we
2236                    // are asked to install the app with all permissions granted.
2237                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2238                        updatePermissionFlags(permission, pkg.packageName,
2239                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2240                    }
2241                }
2242            }
2243        }
2244    }
2245
2246    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2247        Bundle extras = null;
2248        switch (res.returnCode) {
2249            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2250                extras = new Bundle();
2251                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2252                        res.origPermission);
2253                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2254                        res.origPackage);
2255                break;
2256            }
2257            case PackageManager.INSTALL_SUCCEEDED: {
2258                extras = new Bundle();
2259                extras.putBoolean(Intent.EXTRA_REPLACING,
2260                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2261                break;
2262            }
2263        }
2264        return extras;
2265    }
2266
2267    void scheduleWriteSettingsLocked() {
2268        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2269            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2270        }
2271    }
2272
2273    void scheduleWritePackageListLocked(int userId) {
2274        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2275            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2276            msg.arg1 = userId;
2277            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2278        }
2279    }
2280
2281    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2282        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2283        scheduleWritePackageRestrictionsLocked(userId);
2284    }
2285
2286    void scheduleWritePackageRestrictionsLocked(int userId) {
2287        final int[] userIds = (userId == UserHandle.USER_ALL)
2288                ? sUserManager.getUserIds() : new int[]{userId};
2289        for (int nextUserId : userIds) {
2290            if (!sUserManager.exists(nextUserId)) return;
2291            mDirtyUsers.add(nextUserId);
2292            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2293                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2294            }
2295        }
2296    }
2297
2298    public static PackageManagerService main(Context context, Installer installer,
2299            boolean factoryTest, boolean onlyCore) {
2300        // Self-check for initial settings.
2301        PackageManagerServiceCompilerMapping.checkProperties();
2302
2303        PackageManagerService m = new PackageManagerService(context, installer,
2304                factoryTest, onlyCore);
2305        m.enableSystemUserPackages();
2306        ServiceManager.addService("package", m);
2307        return m;
2308    }
2309
2310    private void enableSystemUserPackages() {
2311        if (!UserManager.isSplitSystemUser()) {
2312            return;
2313        }
2314        // For system user, enable apps based on the following conditions:
2315        // - app is whitelisted or belong to one of these groups:
2316        //   -- system app which has no launcher icons
2317        //   -- system app which has INTERACT_ACROSS_USERS permission
2318        //   -- system IME app
2319        // - app is not in the blacklist
2320        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2321        Set<String> enableApps = new ArraySet<>();
2322        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2323                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2324                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2325        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2326        enableApps.addAll(wlApps);
2327        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2328                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2329        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2330        enableApps.removeAll(blApps);
2331        Log.i(TAG, "Applications installed for system user: " + enableApps);
2332        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2333                UserHandle.SYSTEM);
2334        final int allAppsSize = allAps.size();
2335        synchronized (mPackages) {
2336            for (int i = 0; i < allAppsSize; i++) {
2337                String pName = allAps.get(i);
2338                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2339                // Should not happen, but we shouldn't be failing if it does
2340                if (pkgSetting == null) {
2341                    continue;
2342                }
2343                boolean install = enableApps.contains(pName);
2344                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2345                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2346                            + " for system user");
2347                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2348                }
2349            }
2350            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2351        }
2352    }
2353
2354    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2355        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2356                Context.DISPLAY_SERVICE);
2357        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2358    }
2359
2360    /**
2361     * Requests that files preopted on a secondary system partition be copied to the data partition
2362     * if possible.  Note that the actual copying of the files is accomplished by init for security
2363     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2364     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2365     */
2366    private static void requestCopyPreoptedFiles() {
2367        final int WAIT_TIME_MS = 100;
2368        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2369        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2370            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2371            // We will wait for up to 100 seconds.
2372            final long timeStart = SystemClock.uptimeMillis();
2373            final long timeEnd = timeStart + 100 * 1000;
2374            long timeNow = timeStart;
2375            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2376                try {
2377                    Thread.sleep(WAIT_TIME_MS);
2378                } catch (InterruptedException e) {
2379                    // Do nothing
2380                }
2381                timeNow = SystemClock.uptimeMillis();
2382                if (timeNow > timeEnd) {
2383                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2384                    Slog.wtf(TAG, "cppreopt did not finish!");
2385                    break;
2386                }
2387            }
2388
2389            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2390        }
2391    }
2392
2393    public PackageManagerService(Context context, Installer installer,
2394            boolean factoryTest, boolean onlyCore) {
2395        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2396        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2397        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2398                SystemClock.uptimeMillis());
2399
2400        if (mSdkVersion <= 0) {
2401            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2402        }
2403
2404        mContext = context;
2405
2406        mPermissionReviewRequired = context.getResources().getBoolean(
2407                R.bool.config_permissionReviewRequired);
2408
2409        mFactoryTest = factoryTest;
2410        mOnlyCore = onlyCore;
2411        mMetrics = new DisplayMetrics();
2412        mSettings = new Settings(mPackages);
2413        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2414                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2415        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2416                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2417        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2418                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2419        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2420                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2421        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2422                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2423        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2424                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2425
2426        String separateProcesses = SystemProperties.get("debug.separate_processes");
2427        if (separateProcesses != null && separateProcesses.length() > 0) {
2428            if ("*".equals(separateProcesses)) {
2429                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2430                mSeparateProcesses = null;
2431                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2432            } else {
2433                mDefParseFlags = 0;
2434                mSeparateProcesses = separateProcesses.split(",");
2435                Slog.w(TAG, "Running with debug.separate_processes: "
2436                        + separateProcesses);
2437            }
2438        } else {
2439            mDefParseFlags = 0;
2440            mSeparateProcesses = null;
2441        }
2442
2443        mInstaller = installer;
2444        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2445                "*dexopt*");
2446        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2447        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2448
2449        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2450                FgThread.get().getLooper());
2451
2452        getDefaultDisplayMetrics(context, mMetrics);
2453
2454        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2455        SystemConfig systemConfig = SystemConfig.getInstance();
2456        mGlobalGids = systemConfig.getGlobalGids();
2457        mSystemPermissions = systemConfig.getSystemPermissions();
2458        mAvailableFeatures = systemConfig.getAvailableFeatures();
2459        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2460
2461        mProtectedPackages = new ProtectedPackages(mContext);
2462
2463        synchronized (mInstallLock) {
2464        // writer
2465        synchronized (mPackages) {
2466            mHandlerThread = new ServiceThread(TAG,
2467                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2468            mHandlerThread.start();
2469            mHandler = new PackageHandler(mHandlerThread.getLooper());
2470            mProcessLoggingHandler = new ProcessLoggingHandler();
2471            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2472
2473            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2474            mInstantAppRegistry = new InstantAppRegistry(this);
2475
2476            File dataDir = Environment.getDataDirectory();
2477            mAppInstallDir = new File(dataDir, "app");
2478            mAppLib32InstallDir = new File(dataDir, "app-lib");
2479            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2480            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2481            sUserManager = new UserManagerService(context, this,
2482                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2483
2484            // Propagate permission configuration in to package manager.
2485            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2486                    = systemConfig.getPermissions();
2487            for (int i=0; i<permConfig.size(); i++) {
2488                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2489                BasePermission bp = mSettings.mPermissions.get(perm.name);
2490                if (bp == null) {
2491                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2492                    mSettings.mPermissions.put(perm.name, bp);
2493                }
2494                if (perm.gids != null) {
2495                    bp.setGids(perm.gids, perm.perUser);
2496                }
2497            }
2498
2499            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2500            final int builtInLibCount = libConfig.size();
2501            for (int i = 0; i < builtInLibCount; i++) {
2502                String name = libConfig.keyAt(i);
2503                String path = libConfig.valueAt(i);
2504                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2505                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2506            }
2507
2508            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2509
2510            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2511            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2512            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2513
2514            // Clean up orphaned packages for which the code path doesn't exist
2515            // and they are an update to a system app - caused by bug/32321269
2516            final int packageSettingCount = mSettings.mPackages.size();
2517            for (int i = packageSettingCount - 1; i >= 0; i--) {
2518                PackageSetting ps = mSettings.mPackages.valueAt(i);
2519                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2520                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2521                    mSettings.mPackages.removeAt(i);
2522                    mSettings.enableSystemPackageLPw(ps.name);
2523                }
2524            }
2525
2526            if (mFirstBoot) {
2527                requestCopyPreoptedFiles();
2528            }
2529
2530            String customResolverActivity = Resources.getSystem().getString(
2531                    R.string.config_customResolverActivity);
2532            if (TextUtils.isEmpty(customResolverActivity)) {
2533                customResolverActivity = null;
2534            } else {
2535                mCustomResolverComponentName = ComponentName.unflattenFromString(
2536                        customResolverActivity);
2537            }
2538
2539            long startTime = SystemClock.uptimeMillis();
2540
2541            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2542                    startTime);
2543
2544            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2545            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2546
2547            if (bootClassPath == null) {
2548                Slog.w(TAG, "No BOOTCLASSPATH found!");
2549            }
2550
2551            if (systemServerClassPath == null) {
2552                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2553            }
2554
2555            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2556
2557            final VersionInfo ver = mSettings.getInternalVersion();
2558            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2559            if (mIsUpgrade) {
2560                logCriticalInfo(Log.INFO,
2561                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2562            }
2563
2564            // when upgrading from pre-M, promote system app permissions from install to runtime
2565            mPromoteSystemApps =
2566                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2567
2568            // When upgrading from pre-N, we need to handle package extraction like first boot,
2569            // as there is no profiling data available.
2570            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2571
2572            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2573
2574            // save off the names of pre-existing system packages prior to scanning; we don't
2575            // want to automatically grant runtime permissions for new system apps
2576            if (mPromoteSystemApps) {
2577                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2578                while (pkgSettingIter.hasNext()) {
2579                    PackageSetting ps = pkgSettingIter.next();
2580                    if (isSystemApp(ps)) {
2581                        mExistingSystemPackages.add(ps.name);
2582                    }
2583                }
2584            }
2585
2586            mCacheDir = preparePackageParserCache(mIsUpgrade);
2587
2588            // Set flag to monitor and not change apk file paths when
2589            // scanning install directories.
2590            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2591
2592            if (mIsUpgrade || mFirstBoot) {
2593                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2594            }
2595
2596            // Collect vendor overlay packages. (Do this before scanning any apps.)
2597            // For security and version matching reason, only consider
2598            // overlay packages if they reside in the right directory.
2599            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2600                    | PackageParser.PARSE_IS_SYSTEM
2601                    | PackageParser.PARSE_IS_SYSTEM_DIR
2602                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2603
2604            mParallelPackageParserCallback.findStaticOverlayPackages();
2605
2606            // Find base frameworks (resource packages without code).
2607            scanDirTracedLI(frameworkDir, mDefParseFlags
2608                    | PackageParser.PARSE_IS_SYSTEM
2609                    | PackageParser.PARSE_IS_SYSTEM_DIR
2610                    | PackageParser.PARSE_IS_PRIVILEGED,
2611                    scanFlags | SCAN_NO_DEX, 0);
2612
2613            // Collected privileged system packages.
2614            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2615            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2616                    | PackageParser.PARSE_IS_SYSTEM
2617                    | PackageParser.PARSE_IS_SYSTEM_DIR
2618                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2619
2620            // Collect ordinary system packages.
2621            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2622            scanDirTracedLI(systemAppDir, mDefParseFlags
2623                    | PackageParser.PARSE_IS_SYSTEM
2624                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2625
2626            // Collect all vendor packages.
2627            File vendorAppDir = new File("/vendor/app");
2628            try {
2629                vendorAppDir = vendorAppDir.getCanonicalFile();
2630            } catch (IOException e) {
2631                // failed to look up canonical path, continue with original one
2632            }
2633            scanDirTracedLI(vendorAppDir, mDefParseFlags
2634                    | PackageParser.PARSE_IS_SYSTEM
2635                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2636
2637            // Collect all OEM packages.
2638            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2639            scanDirTracedLI(oemAppDir, mDefParseFlags
2640                    | PackageParser.PARSE_IS_SYSTEM
2641                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2642
2643            // Prune any system packages that no longer exist.
2644            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2645            // Stub packages must either be replaced with full versions in the /data
2646            // partition or be disabled.
2647            final List<String> stubSystemApps = new ArrayList<>();
2648            if (!mOnlyCore) {
2649                // do this first before mucking with mPackages for the "expecting better" case
2650                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2651                while (pkgIterator.hasNext()) {
2652                    final PackageParser.Package pkg = pkgIterator.next();
2653                    if (pkg.isStub) {
2654                        stubSystemApps.add(pkg.packageName);
2655                    }
2656                }
2657
2658                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2659                while (psit.hasNext()) {
2660                    PackageSetting ps = psit.next();
2661
2662                    /*
2663                     * If this is not a system app, it can't be a
2664                     * disable system app.
2665                     */
2666                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2667                        continue;
2668                    }
2669
2670                    /*
2671                     * If the package is scanned, it's not erased.
2672                     */
2673                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2674                    if (scannedPkg != null) {
2675                        /*
2676                         * If the system app is both scanned and in the
2677                         * disabled packages list, then it must have been
2678                         * added via OTA. Remove it from the currently
2679                         * scanned package so the previously user-installed
2680                         * application can be scanned.
2681                         */
2682                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2683                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2684                                    + ps.name + "; removing system app.  Last known codePath="
2685                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2686                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2687                                    + scannedPkg.mVersionCode);
2688                            removePackageLI(scannedPkg, true);
2689                            mExpectingBetter.put(ps.name, ps.codePath);
2690                        }
2691
2692                        continue;
2693                    }
2694
2695                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2696                        psit.remove();
2697                        logCriticalInfo(Log.WARN, "System package " + ps.name
2698                                + " no longer exists; it's data will be wiped");
2699                        // Actual deletion of code and data will be handled by later
2700                        // reconciliation step
2701                    } else {
2702                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2703                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2704                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2705                        }
2706                    }
2707                }
2708            }
2709
2710            //look for any incomplete package installations
2711            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2712            for (int i = 0; i < deletePkgsList.size(); i++) {
2713                // Actual deletion of code and data will be handled by later
2714                // reconciliation step
2715                final String packageName = deletePkgsList.get(i).name;
2716                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2717                synchronized (mPackages) {
2718                    mSettings.removePackageLPw(packageName);
2719                }
2720            }
2721
2722            //delete tmp files
2723            deleteTempPackageFiles();
2724
2725            // Remove any shared userIDs that have no associated packages
2726            mSettings.pruneSharedUsersLPw();
2727            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2728            final int systemPackagesCount = mPackages.size();
2729            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2730                    + " ms, packageCount: " + systemPackagesCount
2731                    + " ms, timePerPackage: "
2732                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount));
2733            if (mIsUpgrade && systemPackagesCount > 0) {
2734                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2735                        ((int) systemScanTime) / systemPackagesCount);
2736            }
2737            if (!mOnlyCore) {
2738                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2739                        SystemClock.uptimeMillis());
2740                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2741
2742                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2743                        | PackageParser.PARSE_FORWARD_LOCK,
2744                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2745
2746                // Remove disable package settings for updated system apps that were
2747                // removed via an OTA. If the update is no longer present, remove the
2748                // app completely. Otherwise, revoke their system privileges.
2749                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2750                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2751                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2752
2753                    final String msg;
2754                    if (deletedPkg == null) {
2755                        // should have found an update, but, we didn't; remove everything
2756                        msg = "Updated system package " + deletedAppName
2757                                + " no longer exists; removing its data";
2758                        // Actual deletion of code and data will be handled by later
2759                        // reconciliation step
2760                    } else {
2761                        // found an update; revoke system privileges
2762                        msg = "Updated system package + " + deletedAppName
2763                                + " no longer exists; revoking system privileges";
2764
2765                        // Don't do anything if a stub is removed from the system image. If
2766                        // we were to remove the uncompressed version from the /data partition,
2767                        // this is where it'd be done.
2768
2769                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2770                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2771                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2772                    }
2773                    logCriticalInfo(Log.WARN, msg);
2774                }
2775
2776                /*
2777                 * Make sure all system apps that we expected to appear on
2778                 * the userdata partition actually showed up. If they never
2779                 * appeared, crawl back and revive the system version.
2780                 */
2781                for (int i = 0; i < mExpectingBetter.size(); i++) {
2782                    final String packageName = mExpectingBetter.keyAt(i);
2783                    if (!mPackages.containsKey(packageName)) {
2784                        final File scanFile = mExpectingBetter.valueAt(i);
2785
2786                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2787                                + " but never showed up; reverting to system");
2788
2789                        int reparseFlags = mDefParseFlags;
2790                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2791                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2792                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2793                                    | PackageParser.PARSE_IS_PRIVILEGED;
2794                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2795                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2796                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2797                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2798                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2799                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2800                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2801                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2802                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2803                        } else {
2804                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2805                            continue;
2806                        }
2807
2808                        mSettings.enableSystemPackageLPw(packageName);
2809
2810                        try {
2811                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2812                        } catch (PackageManagerException e) {
2813                            Slog.e(TAG, "Failed to parse original system package: "
2814                                    + e.getMessage());
2815                        }
2816                    }
2817                }
2818
2819                // Uncompress and install any stubbed system applications.
2820                // This must be done last to ensure all stubs are replaced or disabled.
2821                decompressSystemApplications(stubSystemApps, scanFlags);
2822
2823                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2824                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2825                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2826                        + " ms, packageCount: " + dataPackagesCount
2827                        + " ms, timePerPackage: "
2828                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount));
2829                if (mIsUpgrade && dataPackagesCount > 0) {
2830                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2831                            ((int) dataScanTime) / dataPackagesCount);
2832                }
2833            }
2834            mExpectingBetter.clear();
2835
2836            // Resolve the storage manager.
2837            mStorageManagerPackage = getStorageManagerPackageName();
2838
2839            // Resolve protected action filters. Only the setup wizard is allowed to
2840            // have a high priority filter for these actions.
2841            mSetupWizardPackage = getSetupWizardPackageName();
2842            if (mProtectedFilters.size() > 0) {
2843                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2844                    Slog.i(TAG, "No setup wizard;"
2845                        + " All protected intents capped to priority 0");
2846                }
2847                for (ActivityIntentInfo filter : mProtectedFilters) {
2848                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2849                        if (DEBUG_FILTERS) {
2850                            Slog.i(TAG, "Found setup wizard;"
2851                                + " allow priority " + filter.getPriority() + ";"
2852                                + " package: " + filter.activity.info.packageName
2853                                + " activity: " + filter.activity.className
2854                                + " priority: " + filter.getPriority());
2855                        }
2856                        // skip setup wizard; allow it to keep the high priority filter
2857                        continue;
2858                    }
2859                    if (DEBUG_FILTERS) {
2860                        Slog.i(TAG, "Protected action; cap priority to 0;"
2861                                + " package: " + filter.activity.info.packageName
2862                                + " activity: " + filter.activity.className
2863                                + " origPrio: " + filter.getPriority());
2864                    }
2865                    filter.setPriority(0);
2866                }
2867            }
2868            mDeferProtectedFilters = false;
2869            mProtectedFilters.clear();
2870
2871            // Now that we know all of the shared libraries, update all clients to have
2872            // the correct library paths.
2873            updateAllSharedLibrariesLPw(null);
2874
2875            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2876                // NOTE: We ignore potential failures here during a system scan (like
2877                // the rest of the commands above) because there's precious little we
2878                // can do about it. A settings error is reported, though.
2879                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2880            }
2881
2882            // Now that we know all the packages we are keeping,
2883            // read and update their last usage times.
2884            mPackageUsage.read(mPackages);
2885            mCompilerStats.read();
2886
2887            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2888                    SystemClock.uptimeMillis());
2889            Slog.i(TAG, "Time to scan packages: "
2890                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2891                    + " seconds");
2892
2893            // If the platform SDK has changed since the last time we booted,
2894            // we need to re-grant app permission to catch any new ones that
2895            // appear.  This is really a hack, and means that apps can in some
2896            // cases get permissions that the user didn't initially explicitly
2897            // allow...  it would be nice to have some better way to handle
2898            // this situation.
2899            int updateFlags = UPDATE_PERMISSIONS_ALL;
2900            if (ver.sdkVersion != mSdkVersion) {
2901                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2902                        + mSdkVersion + "; regranting permissions for internal storage");
2903                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2904            }
2905            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2906            ver.sdkVersion = mSdkVersion;
2907
2908            // If this is the first boot or an update from pre-M, and it is a normal
2909            // boot, then we need to initialize the default preferred apps across
2910            // all defined users.
2911            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2912                for (UserInfo user : sUserManager.getUsers(true)) {
2913                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2914                    applyFactoryDefaultBrowserLPw(user.id);
2915                    primeDomainVerificationsLPw(user.id);
2916                }
2917            }
2918
2919            // Prepare storage for system user really early during boot,
2920            // since core system apps like SettingsProvider and SystemUI
2921            // can't wait for user to start
2922            final int storageFlags;
2923            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2924                storageFlags = StorageManager.FLAG_STORAGE_DE;
2925            } else {
2926                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2927            }
2928            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2929                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2930                    true /* onlyCoreApps */);
2931            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2932                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2933                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2934                traceLog.traceBegin("AppDataFixup");
2935                try {
2936                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2937                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2938                } catch (InstallerException e) {
2939                    Slog.w(TAG, "Trouble fixing GIDs", e);
2940                }
2941                traceLog.traceEnd();
2942
2943                traceLog.traceBegin("AppDataPrepare");
2944                if (deferPackages == null || deferPackages.isEmpty()) {
2945                    return;
2946                }
2947                int count = 0;
2948                for (String pkgName : deferPackages) {
2949                    PackageParser.Package pkg = null;
2950                    synchronized (mPackages) {
2951                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2952                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2953                            pkg = ps.pkg;
2954                        }
2955                    }
2956                    if (pkg != null) {
2957                        synchronized (mInstallLock) {
2958                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2959                                    true /* maybeMigrateAppData */);
2960                        }
2961                        count++;
2962                    }
2963                }
2964                traceLog.traceEnd();
2965                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2966            }, "prepareAppData");
2967
2968            // If this is first boot after an OTA, and a normal boot, then
2969            // we need to clear code cache directories.
2970            // Note that we do *not* clear the application profiles. These remain valid
2971            // across OTAs and are used to drive profile verification (post OTA) and
2972            // profile compilation (without waiting to collect a fresh set of profiles).
2973            if (mIsUpgrade && !onlyCore) {
2974                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2975                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2976                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2977                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2978                        // No apps are running this early, so no need to freeze
2979                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2980                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2981                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2982                    }
2983                }
2984                ver.fingerprint = Build.FINGERPRINT;
2985            }
2986
2987            checkDefaultBrowser();
2988
2989            // clear only after permissions and other defaults have been updated
2990            mExistingSystemPackages.clear();
2991            mPromoteSystemApps = false;
2992
2993            // All the changes are done during package scanning.
2994            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2995
2996            // can downgrade to reader
2997            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2998            mSettings.writeLPr();
2999            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3000            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3001                    SystemClock.uptimeMillis());
3002
3003            if (!mOnlyCore) {
3004                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3005                mRequiredInstallerPackage = getRequiredInstallerLPr();
3006                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3007                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3008                if (mIntentFilterVerifierComponent != null) {
3009                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3010                            mIntentFilterVerifierComponent);
3011                } else {
3012                    mIntentFilterVerifier = null;
3013                }
3014                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3015                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3016                        SharedLibraryInfo.VERSION_UNDEFINED);
3017                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3018                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3019                        SharedLibraryInfo.VERSION_UNDEFINED);
3020            } else {
3021                mRequiredVerifierPackage = null;
3022                mRequiredInstallerPackage = null;
3023                mRequiredUninstallerPackage = null;
3024                mIntentFilterVerifierComponent = null;
3025                mIntentFilterVerifier = null;
3026                mServicesSystemSharedLibraryPackageName = null;
3027                mSharedSystemSharedLibraryPackageName = null;
3028            }
3029
3030            mInstallerService = new PackageInstallerService(context, this);
3031            final Pair<ComponentName, String> instantAppResolverComponent =
3032                    getInstantAppResolverLPr();
3033            if (instantAppResolverComponent != null) {
3034                if (DEBUG_EPHEMERAL) {
3035                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3036                }
3037                mInstantAppResolverConnection = new EphemeralResolverConnection(
3038                        mContext, instantAppResolverComponent.first,
3039                        instantAppResolverComponent.second);
3040                mInstantAppResolverSettingsComponent =
3041                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3042            } else {
3043                mInstantAppResolverConnection = null;
3044                mInstantAppResolverSettingsComponent = null;
3045            }
3046            updateInstantAppInstallerLocked(null);
3047
3048            // Read and update the usage of dex files.
3049            // Do this at the end of PM init so that all the packages have their
3050            // data directory reconciled.
3051            // At this point we know the code paths of the packages, so we can validate
3052            // the disk file and build the internal cache.
3053            // The usage file is expected to be small so loading and verifying it
3054            // should take a fairly small time compare to the other activities (e.g. package
3055            // scanning).
3056            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3057            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3058            for (int userId : currentUserIds) {
3059                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3060            }
3061            mDexManager.load(userPackages);
3062            if (mIsUpgrade) {
3063                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3064                        (int) (SystemClock.uptimeMillis() - startTime));
3065            }
3066        } // synchronized (mPackages)
3067        } // synchronized (mInstallLock)
3068
3069        // Now after opening every single application zip, make sure they
3070        // are all flushed.  Not really needed, but keeps things nice and
3071        // tidy.
3072        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3073        Runtime.getRuntime().gc();
3074        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3075
3076        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3077        FallbackCategoryProvider.loadFallbacks();
3078        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3079
3080        // The initial scanning above does many calls into installd while
3081        // holding the mPackages lock, but we're mostly interested in yelling
3082        // once we have a booted system.
3083        mInstaller.setWarnIfHeld(mPackages);
3084
3085        // Expose private service for system components to use.
3086        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3087        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3088    }
3089
3090    /**
3091     * Uncompress and install stub applications.
3092     * <p>In order to save space on the system partition, some applications are shipped in a
3093     * compressed form. In addition the compressed bits for the full application, the
3094     * system image contains a tiny stub comprised of only the Android manifest.
3095     * <p>During the first boot, attempt to uncompress and install the full application. If
3096     * the application can't be installed for any reason, disable the stub and prevent
3097     * uncompressing the full application during future boots.
3098     * <p>In order to forcefully attempt an installation of a full application, go to app
3099     * settings and enable the application.
3100     */
3101    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3102        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3103            final String pkgName = stubSystemApps.get(i);
3104            // skip if the system package is already disabled
3105            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3106                stubSystemApps.remove(i);
3107                continue;
3108            }
3109            // skip if the package isn't installed (?!); this should never happen
3110            final PackageParser.Package pkg = mPackages.get(pkgName);
3111            if (pkg == null) {
3112                stubSystemApps.remove(i);
3113                continue;
3114            }
3115            // skip if the package has been disabled by the user
3116            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3117            if (ps != null) {
3118                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3119                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3120                    stubSystemApps.remove(i);
3121                    continue;
3122                }
3123            }
3124
3125            if (DEBUG_COMPRESSION) {
3126                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3127            }
3128
3129            // uncompress the binary to its eventual destination on /data
3130            final File scanFile = decompressPackage(pkg);
3131            if (scanFile == null) {
3132                continue;
3133            }
3134
3135            // install the package to replace the stub on /system
3136            try {
3137                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3138                removePackageLI(pkg, true /*chatty*/);
3139                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3140                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3141                        UserHandle.USER_SYSTEM, "android");
3142                stubSystemApps.remove(i);
3143                continue;
3144            } catch (PackageManagerException e) {
3145                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3146            }
3147
3148            // any failed attempt to install the package will be cleaned up later
3149        }
3150
3151        // disable any stub still left; these failed to install the full application
3152        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3153            final String pkgName = stubSystemApps.get(i);
3154            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3155            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3156                    UserHandle.USER_SYSTEM, "android");
3157            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3158        }
3159    }
3160
3161    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3162        if (DEBUG_COMPRESSION) {
3163            Slog.i(TAG, "Decompress file"
3164                    + "; src: " + srcFile.getAbsolutePath()
3165                    + ", dst: " + dstFile.getAbsolutePath());
3166        }
3167        try (
3168                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3169                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3170        ) {
3171            Streams.copy(fileIn, fileOut);
3172            Os.chmod(dstFile.getAbsolutePath(), 0644);
3173            return PackageManager.INSTALL_SUCCEEDED;
3174        } catch (IOException e) {
3175            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3176                    + "; src: " + srcFile.getAbsolutePath()
3177                    + ", dst: " + dstFile.getAbsolutePath());
3178        }
3179        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3180    }
3181
3182    private File[] getCompressedFiles(String codePath) {
3183        return new File(codePath).listFiles(new FilenameFilter() {
3184            @Override
3185            public boolean accept(File dir, String name) {
3186                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3187            }
3188        });
3189    }
3190
3191    private boolean compressedFileExists(String codePath) {
3192        final File[] compressedFiles = getCompressedFiles(codePath);
3193        return compressedFiles != null && compressedFiles.length > 0;
3194    }
3195
3196    /**
3197     * Decompresses the given package on the system image onto
3198     * the /data partition.
3199     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3200     */
3201    private File decompressPackage(PackageParser.Package pkg) {
3202        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3203        if (compressedFiles == null || compressedFiles.length == 0) {
3204            if (DEBUG_COMPRESSION) {
3205                Slog.i(TAG, "No files to decompress");
3206            }
3207            return null;
3208        }
3209        final File dstCodePath =
3210                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3211        int ret = PackageManager.INSTALL_SUCCEEDED;
3212        try {
3213            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3214            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3215            for (File srcFile : compressedFiles) {
3216                final String srcFileName = srcFile.getName();
3217                final String dstFileName = srcFileName.substring(
3218                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3219                final File dstFile = new File(dstCodePath, dstFileName);
3220                ret = decompressFile(srcFile, dstFile);
3221                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3222                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3223                            + "; pkg: " + pkg.packageName
3224                            + ", file: " + dstFileName);
3225                    break;
3226                }
3227            }
3228        } catch (ErrnoException e) {
3229            logCriticalInfo(Log.ERROR, "Failed to decompress"
3230                    + "; pkg: " + pkg.packageName
3231                    + ", err: " + e.errno);
3232        }
3233        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3234            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3235            NativeLibraryHelper.Handle handle = null;
3236            try {
3237                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3238                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3239                        null /*abiOverride*/);
3240            } catch (IOException e) {
3241                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3242                        + "; pkg: " + pkg.packageName);
3243                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3244            } finally {
3245                IoUtils.closeQuietly(handle);
3246            }
3247        }
3248        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3249            if (dstCodePath == null || !dstCodePath.exists()) {
3250                return null;
3251            }
3252            removeCodePathLI(dstCodePath);
3253            return null;
3254        }
3255        return dstCodePath;
3256    }
3257
3258    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3259        // we're only interested in updating the installer appliction when 1) it's not
3260        // already set or 2) the modified package is the installer
3261        if (mInstantAppInstallerActivity != null
3262                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3263                        .equals(modifiedPackage)) {
3264            return;
3265        }
3266        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3267    }
3268
3269    private static File preparePackageParserCache(boolean isUpgrade) {
3270        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3271            return null;
3272        }
3273
3274        // Disable package parsing on eng builds to allow for faster incremental development.
3275        if (Build.IS_ENG) {
3276            return null;
3277        }
3278
3279        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3280            Slog.i(TAG, "Disabling package parser cache due to system property.");
3281            return null;
3282        }
3283
3284        // The base directory for the package parser cache lives under /data/system/.
3285        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3286                "package_cache");
3287        if (cacheBaseDir == null) {
3288            return null;
3289        }
3290
3291        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3292        // This also serves to "GC" unused entries when the package cache version changes (which
3293        // can only happen during upgrades).
3294        if (isUpgrade) {
3295            FileUtils.deleteContents(cacheBaseDir);
3296        }
3297
3298
3299        // Return the versioned package cache directory. This is something like
3300        // "/data/system/package_cache/1"
3301        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3302
3303        // The following is a workaround to aid development on non-numbered userdebug
3304        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3305        // the system partition is newer.
3306        //
3307        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3308        // that starts with "eng." to signify that this is an engineering build and not
3309        // destined for release.
3310        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3311            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3312
3313            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3314            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3315            // in general and should not be used for production changes. In this specific case,
3316            // we know that they will work.
3317            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3318            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3319                FileUtils.deleteContents(cacheBaseDir);
3320                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3321            }
3322        }
3323
3324        return cacheDir;
3325    }
3326
3327    @Override
3328    public boolean isFirstBoot() {
3329        // allow instant applications
3330        return mFirstBoot;
3331    }
3332
3333    @Override
3334    public boolean isOnlyCoreApps() {
3335        // allow instant applications
3336        return mOnlyCore;
3337    }
3338
3339    @Override
3340    public boolean isUpgrade() {
3341        // allow instant applications
3342        return mIsUpgrade;
3343    }
3344
3345    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3346        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3347
3348        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3349                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3350                UserHandle.USER_SYSTEM);
3351        if (matches.size() == 1) {
3352            return matches.get(0).getComponentInfo().packageName;
3353        } else if (matches.size() == 0) {
3354            Log.e(TAG, "There should probably be a verifier, but, none were found");
3355            return null;
3356        }
3357        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3358    }
3359
3360    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3361        synchronized (mPackages) {
3362            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3363            if (libraryEntry == null) {
3364                throw new IllegalStateException("Missing required shared library:" + name);
3365            }
3366            return libraryEntry.apk;
3367        }
3368    }
3369
3370    private @NonNull String getRequiredInstallerLPr() {
3371        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3372        intent.addCategory(Intent.CATEGORY_DEFAULT);
3373        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3374
3375        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3376                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3377                UserHandle.USER_SYSTEM);
3378        if (matches.size() == 1) {
3379            ResolveInfo resolveInfo = matches.get(0);
3380            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3381                throw new RuntimeException("The installer must be a privileged app");
3382            }
3383            return matches.get(0).getComponentInfo().packageName;
3384        } else {
3385            throw new RuntimeException("There must be exactly one installer; found " + matches);
3386        }
3387    }
3388
3389    private @NonNull String getRequiredUninstallerLPr() {
3390        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3391        intent.addCategory(Intent.CATEGORY_DEFAULT);
3392        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3393
3394        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3395                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3396                UserHandle.USER_SYSTEM);
3397        if (resolveInfo == null ||
3398                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3399            throw new RuntimeException("There must be exactly one uninstaller; found "
3400                    + resolveInfo);
3401        }
3402        return resolveInfo.getComponentInfo().packageName;
3403    }
3404
3405    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3406        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3407
3408        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3409                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3410                UserHandle.USER_SYSTEM);
3411        ResolveInfo best = null;
3412        final int N = matches.size();
3413        for (int i = 0; i < N; i++) {
3414            final ResolveInfo cur = matches.get(i);
3415            final String packageName = cur.getComponentInfo().packageName;
3416            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3417                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3418                continue;
3419            }
3420
3421            if (best == null || cur.priority > best.priority) {
3422                best = cur;
3423            }
3424        }
3425
3426        if (best != null) {
3427            return best.getComponentInfo().getComponentName();
3428        }
3429        Slog.w(TAG, "Intent filter verifier not found");
3430        return null;
3431    }
3432
3433    @Override
3434    public @Nullable ComponentName getInstantAppResolverComponent() {
3435        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3436            return null;
3437        }
3438        synchronized (mPackages) {
3439            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3440            if (instantAppResolver == null) {
3441                return null;
3442            }
3443            return instantAppResolver.first;
3444        }
3445    }
3446
3447    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3448        final String[] packageArray =
3449                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3450        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3451            if (DEBUG_EPHEMERAL) {
3452                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3453            }
3454            return null;
3455        }
3456
3457        final int callingUid = Binder.getCallingUid();
3458        final int resolveFlags =
3459                MATCH_DIRECT_BOOT_AWARE
3460                | MATCH_DIRECT_BOOT_UNAWARE
3461                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3462        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3463        final Intent resolverIntent = new Intent(actionName);
3464        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3465                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3466        // temporarily look for the old action
3467        if (resolvers.size() == 0) {
3468            if (DEBUG_EPHEMERAL) {
3469                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3470            }
3471            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3472            resolverIntent.setAction(actionName);
3473            resolvers = queryIntentServicesInternal(resolverIntent, null,
3474                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3475        }
3476        final int N = resolvers.size();
3477        if (N == 0) {
3478            if (DEBUG_EPHEMERAL) {
3479                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3480            }
3481            return null;
3482        }
3483
3484        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3485        for (int i = 0; i < N; i++) {
3486            final ResolveInfo info = resolvers.get(i);
3487
3488            if (info.serviceInfo == null) {
3489                continue;
3490            }
3491
3492            final String packageName = info.serviceInfo.packageName;
3493            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3494                if (DEBUG_EPHEMERAL) {
3495                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3496                            + " pkg: " + packageName + ", info:" + info);
3497                }
3498                continue;
3499            }
3500
3501            if (DEBUG_EPHEMERAL) {
3502                Slog.v(TAG, "Ephemeral resolver found;"
3503                        + " pkg: " + packageName + ", info:" + info);
3504            }
3505            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3506        }
3507        if (DEBUG_EPHEMERAL) {
3508            Slog.v(TAG, "Ephemeral resolver NOT found");
3509        }
3510        return null;
3511    }
3512
3513    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3514        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3515        intent.addCategory(Intent.CATEGORY_DEFAULT);
3516        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3517
3518        final int resolveFlags =
3519                MATCH_DIRECT_BOOT_AWARE
3520                | MATCH_DIRECT_BOOT_UNAWARE
3521                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3522        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3523                resolveFlags, UserHandle.USER_SYSTEM);
3524        // temporarily look for the old action
3525        if (matches.isEmpty()) {
3526            if (DEBUG_EPHEMERAL) {
3527                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3528            }
3529            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3530            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3531                    resolveFlags, UserHandle.USER_SYSTEM);
3532        }
3533        Iterator<ResolveInfo> iter = matches.iterator();
3534        while (iter.hasNext()) {
3535            final ResolveInfo rInfo = iter.next();
3536            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3537            if (ps != null) {
3538                final PermissionsState permissionsState = ps.getPermissionsState();
3539                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3540                    continue;
3541                }
3542            }
3543            iter.remove();
3544        }
3545        if (matches.size() == 0) {
3546            return null;
3547        } else if (matches.size() == 1) {
3548            return (ActivityInfo) matches.get(0).getComponentInfo();
3549        } else {
3550            throw new RuntimeException(
3551                    "There must be at most one ephemeral installer; found " + matches);
3552        }
3553    }
3554
3555    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3556            @NonNull ComponentName resolver) {
3557        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3558                .addCategory(Intent.CATEGORY_DEFAULT)
3559                .setPackage(resolver.getPackageName());
3560        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3561        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3562                UserHandle.USER_SYSTEM);
3563        // temporarily look for the old action
3564        if (matches.isEmpty()) {
3565            if (DEBUG_EPHEMERAL) {
3566                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3567            }
3568            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3569            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3570                    UserHandle.USER_SYSTEM);
3571        }
3572        if (matches.isEmpty()) {
3573            return null;
3574        }
3575        return matches.get(0).getComponentInfo().getComponentName();
3576    }
3577
3578    private void primeDomainVerificationsLPw(int userId) {
3579        if (DEBUG_DOMAIN_VERIFICATION) {
3580            Slog.d(TAG, "Priming domain verifications in user " + userId);
3581        }
3582
3583        SystemConfig systemConfig = SystemConfig.getInstance();
3584        ArraySet<String> packages = systemConfig.getLinkedApps();
3585
3586        for (String packageName : packages) {
3587            PackageParser.Package pkg = mPackages.get(packageName);
3588            if (pkg != null) {
3589                if (!pkg.isSystemApp()) {
3590                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3591                    continue;
3592                }
3593
3594                ArraySet<String> domains = null;
3595                for (PackageParser.Activity a : pkg.activities) {
3596                    for (ActivityIntentInfo filter : a.intents) {
3597                        if (hasValidDomains(filter)) {
3598                            if (domains == null) {
3599                                domains = new ArraySet<String>();
3600                            }
3601                            domains.addAll(filter.getHostsList());
3602                        }
3603                    }
3604                }
3605
3606                if (domains != null && domains.size() > 0) {
3607                    if (DEBUG_DOMAIN_VERIFICATION) {
3608                        Slog.v(TAG, "      + " + packageName);
3609                    }
3610                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3611                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3612                    // and then 'always' in the per-user state actually used for intent resolution.
3613                    final IntentFilterVerificationInfo ivi;
3614                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3615                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3616                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3617                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3618                } else {
3619                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3620                            + "' does not handle web links");
3621                }
3622            } else {
3623                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3624            }
3625        }
3626
3627        scheduleWritePackageRestrictionsLocked(userId);
3628        scheduleWriteSettingsLocked();
3629    }
3630
3631    private void applyFactoryDefaultBrowserLPw(int userId) {
3632        // The default browser app's package name is stored in a string resource,
3633        // with a product-specific overlay used for vendor customization.
3634        String browserPkg = mContext.getResources().getString(
3635                com.android.internal.R.string.default_browser);
3636        if (!TextUtils.isEmpty(browserPkg)) {
3637            // non-empty string => required to be a known package
3638            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3639            if (ps == null) {
3640                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3641                browserPkg = null;
3642            } else {
3643                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3644            }
3645        }
3646
3647        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3648        // default.  If there's more than one, just leave everything alone.
3649        if (browserPkg == null) {
3650            calculateDefaultBrowserLPw(userId);
3651        }
3652    }
3653
3654    private void calculateDefaultBrowserLPw(int userId) {
3655        List<String> allBrowsers = resolveAllBrowserApps(userId);
3656        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3657        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3658    }
3659
3660    private List<String> resolveAllBrowserApps(int userId) {
3661        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3662        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3663                PackageManager.MATCH_ALL, userId);
3664
3665        final int count = list.size();
3666        List<String> result = new ArrayList<String>(count);
3667        for (int i=0; i<count; i++) {
3668            ResolveInfo info = list.get(i);
3669            if (info.activityInfo == null
3670                    || !info.handleAllWebDataURI
3671                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3672                    || result.contains(info.activityInfo.packageName)) {
3673                continue;
3674            }
3675            result.add(info.activityInfo.packageName);
3676        }
3677
3678        return result;
3679    }
3680
3681    private boolean packageIsBrowser(String packageName, int userId) {
3682        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3683                PackageManager.MATCH_ALL, userId);
3684        final int N = list.size();
3685        for (int i = 0; i < N; i++) {
3686            ResolveInfo info = list.get(i);
3687            if (packageName.equals(info.activityInfo.packageName)) {
3688                return true;
3689            }
3690        }
3691        return false;
3692    }
3693
3694    private void checkDefaultBrowser() {
3695        final int myUserId = UserHandle.myUserId();
3696        final String packageName = getDefaultBrowserPackageName(myUserId);
3697        if (packageName != null) {
3698            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3699            if (info == null) {
3700                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3701                synchronized (mPackages) {
3702                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3703                }
3704            }
3705        }
3706    }
3707
3708    @Override
3709    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3710            throws RemoteException {
3711        try {
3712            return super.onTransact(code, data, reply, flags);
3713        } catch (RuntimeException e) {
3714            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3715                Slog.wtf(TAG, "Package Manager Crash", e);
3716            }
3717            throw e;
3718        }
3719    }
3720
3721    static int[] appendInts(int[] cur, int[] add) {
3722        if (add == null) return cur;
3723        if (cur == null) return add;
3724        final int N = add.length;
3725        for (int i=0; i<N; i++) {
3726            cur = appendInt(cur, add[i]);
3727        }
3728        return cur;
3729    }
3730
3731    /**
3732     * Returns whether or not a full application can see an instant application.
3733     * <p>
3734     * Currently, there are three cases in which this can occur:
3735     * <ol>
3736     * <li>The calling application is a "special" process. The special
3737     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3738     *     and {@code 0}</li>
3739     * <li>The calling application has the permission
3740     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3741     * <li>The calling application is the default launcher on the
3742     *     system partition.</li>
3743     * </ol>
3744     */
3745    private boolean canViewInstantApps(int callingUid, int userId) {
3746        if (callingUid == Process.SYSTEM_UID
3747                || callingUid == Process.SHELL_UID
3748                || callingUid == Process.ROOT_UID) {
3749            return true;
3750        }
3751        if (mContext.checkCallingOrSelfPermission(
3752                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3753            return true;
3754        }
3755        if (mContext.checkCallingOrSelfPermission(
3756                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3757            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3758            if (homeComponent != null
3759                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3760                return true;
3761            }
3762        }
3763        return false;
3764    }
3765
3766    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3767        if (!sUserManager.exists(userId)) return null;
3768        if (ps == null) {
3769            return null;
3770        }
3771        PackageParser.Package p = ps.pkg;
3772        if (p == null) {
3773            return null;
3774        }
3775        final int callingUid = Binder.getCallingUid();
3776        // Filter out ephemeral app metadata:
3777        //   * The system/shell/root can see metadata for any app
3778        //   * An installed app can see metadata for 1) other installed apps
3779        //     and 2) ephemeral apps that have explicitly interacted with it
3780        //   * Ephemeral apps can only see their own data and exposed installed apps
3781        //   * Holding a signature permission allows seeing instant apps
3782        if (filterAppAccessLPr(ps, callingUid, userId)) {
3783            return null;
3784        }
3785
3786        final PermissionsState permissionsState = ps.getPermissionsState();
3787
3788        // Compute GIDs only if requested
3789        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3790                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3791        // Compute granted permissions only if package has requested permissions
3792        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3793                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3794        final PackageUserState state = ps.readUserState(userId);
3795
3796        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3797                && ps.isSystem()) {
3798            flags |= MATCH_ANY_USER;
3799        }
3800
3801        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3802                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3803
3804        if (packageInfo == null) {
3805            return null;
3806        }
3807
3808        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3809                resolveExternalPackageNameLPr(p);
3810
3811        return packageInfo;
3812    }
3813
3814    @Override
3815    public void checkPackageStartable(String packageName, int userId) {
3816        final int callingUid = Binder.getCallingUid();
3817        if (getInstantAppPackageName(callingUid) != null) {
3818            throw new SecurityException("Instant applications don't have access to this method");
3819        }
3820        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3821        synchronized (mPackages) {
3822            final PackageSetting ps = mSettings.mPackages.get(packageName);
3823            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3824                throw new SecurityException("Package " + packageName + " was not found!");
3825            }
3826
3827            if (!ps.getInstalled(userId)) {
3828                throw new SecurityException(
3829                        "Package " + packageName + " was not installed for user " + userId + "!");
3830            }
3831
3832            if (mSafeMode && !ps.isSystem()) {
3833                throw new SecurityException("Package " + packageName + " not a system app!");
3834            }
3835
3836            if (mFrozenPackages.contains(packageName)) {
3837                throw new SecurityException("Package " + packageName + " is currently frozen!");
3838            }
3839
3840            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3841                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3842                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3843            }
3844        }
3845    }
3846
3847    @Override
3848    public boolean isPackageAvailable(String packageName, int userId) {
3849        if (!sUserManager.exists(userId)) return false;
3850        final int callingUid = Binder.getCallingUid();
3851        enforceCrossUserPermission(callingUid, userId,
3852                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3853        synchronized (mPackages) {
3854            PackageParser.Package p = mPackages.get(packageName);
3855            if (p != null) {
3856                final PackageSetting ps = (PackageSetting) p.mExtras;
3857                if (filterAppAccessLPr(ps, callingUid, userId)) {
3858                    return false;
3859                }
3860                if (ps != null) {
3861                    final PackageUserState state = ps.readUserState(userId);
3862                    if (state != null) {
3863                        return PackageParser.isAvailable(state);
3864                    }
3865                }
3866            }
3867        }
3868        return false;
3869    }
3870
3871    @Override
3872    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3873        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3874                flags, Binder.getCallingUid(), userId);
3875    }
3876
3877    @Override
3878    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3879            int flags, int userId) {
3880        return getPackageInfoInternal(versionedPackage.getPackageName(),
3881                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3882    }
3883
3884    /**
3885     * Important: The provided filterCallingUid is used exclusively to filter out packages
3886     * that can be seen based on user state. It's typically the original caller uid prior
3887     * to clearing. Because it can only be provided by trusted code, it's value can be
3888     * trusted and will be used as-is; unlike userId which will be validated by this method.
3889     */
3890    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3891            int flags, int filterCallingUid, int userId) {
3892        if (!sUserManager.exists(userId)) return null;
3893        flags = updateFlagsForPackage(flags, userId, packageName);
3894        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3895                false /* requireFullPermission */, false /* checkShell */, "get package info");
3896
3897        // reader
3898        synchronized (mPackages) {
3899            // Normalize package name to handle renamed packages and static libs
3900            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3901
3902            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3903            if (matchFactoryOnly) {
3904                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3905                if (ps != null) {
3906                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3907                        return null;
3908                    }
3909                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3910                        return null;
3911                    }
3912                    return generatePackageInfo(ps, flags, userId);
3913                }
3914            }
3915
3916            PackageParser.Package p = mPackages.get(packageName);
3917            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3918                return null;
3919            }
3920            if (DEBUG_PACKAGE_INFO)
3921                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3922            if (p != null) {
3923                final PackageSetting ps = (PackageSetting) p.mExtras;
3924                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3925                    return null;
3926                }
3927                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3928                    return null;
3929                }
3930                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3931            }
3932            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3933                final PackageSetting ps = mSettings.mPackages.get(packageName);
3934                if (ps == null) return null;
3935                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3936                    return null;
3937                }
3938                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3939                    return null;
3940                }
3941                return generatePackageInfo(ps, flags, userId);
3942            }
3943        }
3944        return null;
3945    }
3946
3947    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3948        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3949            return true;
3950        }
3951        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3952            return true;
3953        }
3954        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3955            return true;
3956        }
3957        return false;
3958    }
3959
3960    private boolean isComponentVisibleToInstantApp(
3961            @Nullable ComponentName component, @ComponentType int type) {
3962        if (type == TYPE_ACTIVITY) {
3963            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3964            return activity != null
3965                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3966                    : false;
3967        } else if (type == TYPE_RECEIVER) {
3968            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3969            return activity != null
3970                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3971                    : false;
3972        } else if (type == TYPE_SERVICE) {
3973            final PackageParser.Service service = mServices.mServices.get(component);
3974            return service != null
3975                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3976                    : false;
3977        } else if (type == TYPE_PROVIDER) {
3978            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3979            return provider != null
3980                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3981                    : false;
3982        } else if (type == TYPE_UNKNOWN) {
3983            return isComponentVisibleToInstantApp(component);
3984        }
3985        return false;
3986    }
3987
3988    /**
3989     * Returns whether or not access to the application should be filtered.
3990     * <p>
3991     * Access may be limited based upon whether the calling or target applications
3992     * are instant applications.
3993     *
3994     * @see #canAccessInstantApps(int)
3995     */
3996    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3997            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3998        // if we're in an isolated process, get the real calling UID
3999        if (Process.isIsolated(callingUid)) {
4000            callingUid = mIsolatedOwners.get(callingUid);
4001        }
4002        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4003        final boolean callerIsInstantApp = instantAppPkgName != null;
4004        if (ps == null) {
4005            if (callerIsInstantApp) {
4006                // pretend the application exists, but, needs to be filtered
4007                return true;
4008            }
4009            return false;
4010        }
4011        // if the target and caller are the same application, don't filter
4012        if (isCallerSameApp(ps.name, callingUid)) {
4013            return false;
4014        }
4015        if (callerIsInstantApp) {
4016            // request for a specific component; if it hasn't been explicitly exposed, filter
4017            if (component != null) {
4018                return !isComponentVisibleToInstantApp(component, componentType);
4019            }
4020            // request for application; if no components have been explicitly exposed, filter
4021            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4022        }
4023        if (ps.getInstantApp(userId)) {
4024            // caller can see all components of all instant applications, don't filter
4025            if (canViewInstantApps(callingUid, userId)) {
4026                return false;
4027            }
4028            // request for a specific instant application component, filter
4029            if (component != null) {
4030                return true;
4031            }
4032            // request for an instant application; if the caller hasn't been granted access, filter
4033            return !mInstantAppRegistry.isInstantAccessGranted(
4034                    userId, UserHandle.getAppId(callingUid), ps.appId);
4035        }
4036        return false;
4037    }
4038
4039    /**
4040     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4041     */
4042    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4043        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4044    }
4045
4046    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4047            int flags) {
4048        // Callers can access only the libs they depend on, otherwise they need to explicitly
4049        // ask for the shared libraries given the caller is allowed to access all static libs.
4050        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4051            // System/shell/root get to see all static libs
4052            final int appId = UserHandle.getAppId(uid);
4053            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4054                    || appId == Process.ROOT_UID) {
4055                return false;
4056            }
4057        }
4058
4059        // No package means no static lib as it is always on internal storage
4060        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4061            return false;
4062        }
4063
4064        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4065                ps.pkg.staticSharedLibVersion);
4066        if (libEntry == null) {
4067            return false;
4068        }
4069
4070        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4071        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4072        if (uidPackageNames == null) {
4073            return true;
4074        }
4075
4076        for (String uidPackageName : uidPackageNames) {
4077            if (ps.name.equals(uidPackageName)) {
4078                return false;
4079            }
4080            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4081            if (uidPs != null) {
4082                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4083                        libEntry.info.getName());
4084                if (index < 0) {
4085                    continue;
4086                }
4087                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4088                    return false;
4089                }
4090            }
4091        }
4092        return true;
4093    }
4094
4095    @Override
4096    public String[] currentToCanonicalPackageNames(String[] names) {
4097        final int callingUid = Binder.getCallingUid();
4098        if (getInstantAppPackageName(callingUid) != null) {
4099            return names;
4100        }
4101        final String[] out = new String[names.length];
4102        // reader
4103        synchronized (mPackages) {
4104            final int callingUserId = UserHandle.getUserId(callingUid);
4105            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4106            for (int i=names.length-1; i>=0; i--) {
4107                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4108                boolean translateName = false;
4109                if (ps != null && ps.realName != null) {
4110                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4111                    translateName = !targetIsInstantApp
4112                            || canViewInstantApps
4113                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4114                                    UserHandle.getAppId(callingUid), ps.appId);
4115                }
4116                out[i] = translateName ? ps.realName : names[i];
4117            }
4118        }
4119        return out;
4120    }
4121
4122    @Override
4123    public String[] canonicalToCurrentPackageNames(String[] names) {
4124        final int callingUid = Binder.getCallingUid();
4125        if (getInstantAppPackageName(callingUid) != null) {
4126            return names;
4127        }
4128        final String[] out = new String[names.length];
4129        // reader
4130        synchronized (mPackages) {
4131            final int callingUserId = UserHandle.getUserId(callingUid);
4132            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4133            for (int i=names.length-1; i>=0; i--) {
4134                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4135                boolean translateName = false;
4136                if (cur != null) {
4137                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4138                    final boolean targetIsInstantApp =
4139                            ps != null && ps.getInstantApp(callingUserId);
4140                    translateName = !targetIsInstantApp
4141                            || canViewInstantApps
4142                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4143                                    UserHandle.getAppId(callingUid), ps.appId);
4144                }
4145                out[i] = translateName ? cur : names[i];
4146            }
4147        }
4148        return out;
4149    }
4150
4151    @Override
4152    public int getPackageUid(String packageName, int flags, int userId) {
4153        if (!sUserManager.exists(userId)) return -1;
4154        final int callingUid = Binder.getCallingUid();
4155        flags = updateFlagsForPackage(flags, userId, packageName);
4156        enforceCrossUserPermission(callingUid, userId,
4157                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4158
4159        // reader
4160        synchronized (mPackages) {
4161            final PackageParser.Package p = mPackages.get(packageName);
4162            if (p != null && p.isMatch(flags)) {
4163                PackageSetting ps = (PackageSetting) p.mExtras;
4164                if (filterAppAccessLPr(ps, callingUid, userId)) {
4165                    return -1;
4166                }
4167                return UserHandle.getUid(userId, p.applicationInfo.uid);
4168            }
4169            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4170                final PackageSetting ps = mSettings.mPackages.get(packageName);
4171                if (ps != null && ps.isMatch(flags)
4172                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4173                    return UserHandle.getUid(userId, ps.appId);
4174                }
4175            }
4176        }
4177
4178        return -1;
4179    }
4180
4181    @Override
4182    public int[] getPackageGids(String packageName, int flags, int userId) {
4183        if (!sUserManager.exists(userId)) return null;
4184        final int callingUid = Binder.getCallingUid();
4185        flags = updateFlagsForPackage(flags, userId, packageName);
4186        enforceCrossUserPermission(callingUid, userId,
4187                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4188
4189        // reader
4190        synchronized (mPackages) {
4191            final PackageParser.Package p = mPackages.get(packageName);
4192            if (p != null && p.isMatch(flags)) {
4193                PackageSetting ps = (PackageSetting) p.mExtras;
4194                if (filterAppAccessLPr(ps, callingUid, userId)) {
4195                    return null;
4196                }
4197                // TODO: Shouldn't this be checking for package installed state for userId and
4198                // return null?
4199                return ps.getPermissionsState().computeGids(userId);
4200            }
4201            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4202                final PackageSetting ps = mSettings.mPackages.get(packageName);
4203                if (ps != null && ps.isMatch(flags)
4204                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4205                    return ps.getPermissionsState().computeGids(userId);
4206                }
4207            }
4208        }
4209
4210        return null;
4211    }
4212
4213    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4214        if (bp.perm != null) {
4215            return PackageParser.generatePermissionInfo(bp.perm, flags);
4216        }
4217        PermissionInfo pi = new PermissionInfo();
4218        pi.name = bp.name;
4219        pi.packageName = bp.sourcePackage;
4220        pi.nonLocalizedLabel = bp.name;
4221        pi.protectionLevel = bp.protectionLevel;
4222        return pi;
4223    }
4224
4225    @Override
4226    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4227        final int callingUid = Binder.getCallingUid();
4228        if (getInstantAppPackageName(callingUid) != null) {
4229            return null;
4230        }
4231        // reader
4232        synchronized (mPackages) {
4233            final BasePermission p = mSettings.mPermissions.get(name);
4234            // If the caller is an app that targets pre 26 SDK drop protection flags.
4235            final PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4236            permissionInfo.protectionLevel = adjustPermissionProtectionFlagsLPr(
4237                    permissionInfo.protectionLevel, packageName, callingUid);
4238            return permissionInfo;
4239        }
4240    }
4241
4242    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4243            String packageName, int uid) {
4244        // Signature permission flags area always reported
4245        final int protectionLevelMasked = protectionLevel
4246                & (PermissionInfo.PROTECTION_NORMAL
4247                | PermissionInfo.PROTECTION_DANGEROUS
4248                | PermissionInfo.PROTECTION_SIGNATURE);
4249        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4250            return protectionLevel;
4251        }
4252
4253        // System sees all flags.
4254        final int appId = UserHandle.getAppId(uid);
4255        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4256                || appId == Process.SHELL_UID) {
4257            return protectionLevel;
4258        }
4259
4260        // Normalize package name to handle renamed packages and static libs
4261        packageName = resolveInternalPackageNameLPr(packageName,
4262                PackageManager.VERSION_CODE_HIGHEST);
4263
4264        // Apps that target O see flags for all protection levels.
4265        final PackageSetting ps = mSettings.mPackages.get(packageName);
4266        if (ps == null) {
4267            return protectionLevel;
4268        }
4269        if (ps.appId != appId) {
4270            return protectionLevel;
4271        }
4272
4273        final PackageParser.Package pkg = mPackages.get(packageName);
4274        if (pkg == null) {
4275            return protectionLevel;
4276        }
4277        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4278            return protectionLevelMasked;
4279        }
4280
4281        return protectionLevel;
4282    }
4283
4284    @Override
4285    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4286            int flags) {
4287        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4288            return null;
4289        }
4290        // reader
4291        synchronized (mPackages) {
4292            if (group != null && !mPermissionGroups.containsKey(group)) {
4293                // This is thrown as NameNotFoundException
4294                return null;
4295            }
4296
4297            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4298            for (BasePermission p : mSettings.mPermissions.values()) {
4299                if (group == null) {
4300                    if (p.perm == null || p.perm.info.group == null) {
4301                        out.add(generatePermissionInfo(p, flags));
4302                    }
4303                } else {
4304                    if (p.perm != null && group.equals(p.perm.info.group)) {
4305                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4306                    }
4307                }
4308            }
4309            return new ParceledListSlice<>(out);
4310        }
4311    }
4312
4313    @Override
4314    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4315        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4316            return null;
4317        }
4318        // reader
4319        synchronized (mPackages) {
4320            return PackageParser.generatePermissionGroupInfo(
4321                    mPermissionGroups.get(name), flags);
4322        }
4323    }
4324
4325    @Override
4326    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4327        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4328            return ParceledListSlice.emptyList();
4329        }
4330        // reader
4331        synchronized (mPackages) {
4332            final int N = mPermissionGroups.size();
4333            ArrayList<PermissionGroupInfo> out
4334                    = new ArrayList<PermissionGroupInfo>(N);
4335            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4336                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4337            }
4338            return new ParceledListSlice<>(out);
4339        }
4340    }
4341
4342    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4343            int filterCallingUid, int userId) {
4344        if (!sUserManager.exists(userId)) return null;
4345        PackageSetting ps = mSettings.mPackages.get(packageName);
4346        if (ps != null) {
4347            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4348                return null;
4349            }
4350            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4351                return null;
4352            }
4353            if (ps.pkg == null) {
4354                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4355                if (pInfo != null) {
4356                    return pInfo.applicationInfo;
4357                }
4358                return null;
4359            }
4360            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4361                    ps.readUserState(userId), userId);
4362            if (ai != null) {
4363                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4364            }
4365            return ai;
4366        }
4367        return null;
4368    }
4369
4370    @Override
4371    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4372        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4373    }
4374
4375    /**
4376     * Important: The provided filterCallingUid is used exclusively to filter out applications
4377     * that can be seen based on user state. It's typically the original caller uid prior
4378     * to clearing. Because it can only be provided by trusted code, it's value can be
4379     * trusted and will be used as-is; unlike userId which will be validated by this method.
4380     */
4381    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4382            int filterCallingUid, int userId) {
4383        if (!sUserManager.exists(userId)) return null;
4384        flags = updateFlagsForApplication(flags, userId, packageName);
4385        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4386                false /* requireFullPermission */, false /* checkShell */, "get application info");
4387
4388        // writer
4389        synchronized (mPackages) {
4390            // Normalize package name to handle renamed packages and static libs
4391            packageName = resolveInternalPackageNameLPr(packageName,
4392                    PackageManager.VERSION_CODE_HIGHEST);
4393
4394            PackageParser.Package p = mPackages.get(packageName);
4395            if (DEBUG_PACKAGE_INFO) Log.v(
4396                    TAG, "getApplicationInfo " + packageName
4397                    + ": " + p);
4398            if (p != null) {
4399                PackageSetting ps = mSettings.mPackages.get(packageName);
4400                if (ps == null) return null;
4401                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4402                    return null;
4403                }
4404                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4405                    return null;
4406                }
4407                // Note: isEnabledLP() does not apply here - always return info
4408                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4409                        p, flags, ps.readUserState(userId), userId);
4410                if (ai != null) {
4411                    ai.packageName = resolveExternalPackageNameLPr(p);
4412                }
4413                return ai;
4414            }
4415            if ("android".equals(packageName)||"system".equals(packageName)) {
4416                return mAndroidApplication;
4417            }
4418            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4419                // Already generates the external package name
4420                return generateApplicationInfoFromSettingsLPw(packageName,
4421                        flags, filterCallingUid, userId);
4422            }
4423        }
4424        return null;
4425    }
4426
4427    private String normalizePackageNameLPr(String packageName) {
4428        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4429        return normalizedPackageName != null ? normalizedPackageName : packageName;
4430    }
4431
4432    @Override
4433    public void deletePreloadsFileCache() {
4434        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4435            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4436        }
4437        File dir = Environment.getDataPreloadsFileCacheDirectory();
4438        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4439        FileUtils.deleteContents(dir);
4440    }
4441
4442    @Override
4443    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4444            final int storageFlags, final IPackageDataObserver observer) {
4445        mContext.enforceCallingOrSelfPermission(
4446                android.Manifest.permission.CLEAR_APP_CACHE, null);
4447        mHandler.post(() -> {
4448            boolean success = false;
4449            try {
4450                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4451                success = true;
4452            } catch (IOException e) {
4453                Slog.w(TAG, e);
4454            }
4455            if (observer != null) {
4456                try {
4457                    observer.onRemoveCompleted(null, success);
4458                } catch (RemoteException e) {
4459                    Slog.w(TAG, e);
4460                }
4461            }
4462        });
4463    }
4464
4465    @Override
4466    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4467            final int storageFlags, final IntentSender pi) {
4468        mContext.enforceCallingOrSelfPermission(
4469                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4470        mHandler.post(() -> {
4471            boolean success = false;
4472            try {
4473                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4474                success = true;
4475            } catch (IOException e) {
4476                Slog.w(TAG, e);
4477            }
4478            if (pi != null) {
4479                try {
4480                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4481                } catch (SendIntentException e) {
4482                    Slog.w(TAG, e);
4483                }
4484            }
4485        });
4486    }
4487
4488    /**
4489     * Blocking call to clear various types of cached data across the system
4490     * until the requested bytes are available.
4491     */
4492    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4493        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4494        final File file = storage.findPathForUuid(volumeUuid);
4495        if (file.getUsableSpace() >= bytes) return;
4496
4497        if (ENABLE_FREE_CACHE_V2) {
4498            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4499                    volumeUuid);
4500            final boolean aggressive = (storageFlags
4501                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4502            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4503
4504            // 1. Pre-flight to determine if we have any chance to succeed
4505            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4506            if (internalVolume && (aggressive || SystemProperties
4507                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4508                deletePreloadsFileCache();
4509                if (file.getUsableSpace() >= bytes) return;
4510            }
4511
4512            // 3. Consider parsed APK data (aggressive only)
4513            if (internalVolume && aggressive) {
4514                FileUtils.deleteContents(mCacheDir);
4515                if (file.getUsableSpace() >= bytes) return;
4516            }
4517
4518            // 4. Consider cached app data (above quotas)
4519            try {
4520                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4521                        Installer.FLAG_FREE_CACHE_V2);
4522            } catch (InstallerException ignored) {
4523            }
4524            if (file.getUsableSpace() >= bytes) return;
4525
4526            // 5. Consider shared libraries with refcount=0 and age>min cache period
4527            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4528                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4529                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4530                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4531                return;
4532            }
4533
4534            // 6. Consider dexopt output (aggressive only)
4535            // TODO: Implement
4536
4537            // 7. Consider installed instant apps unused longer than min cache period
4538            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4539                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4540                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4541                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4542                return;
4543            }
4544
4545            // 8. Consider cached app data (below quotas)
4546            try {
4547                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4548                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4549            } catch (InstallerException ignored) {
4550            }
4551            if (file.getUsableSpace() >= bytes) return;
4552
4553            // 9. Consider DropBox entries
4554            // TODO: Implement
4555
4556            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4557            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4558                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4559                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4560                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4561                return;
4562            }
4563        } else {
4564            try {
4565                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4566            } catch (InstallerException ignored) {
4567            }
4568            if (file.getUsableSpace() >= bytes) return;
4569        }
4570
4571        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4572    }
4573
4574    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4575            throws IOException {
4576        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4577        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4578
4579        List<VersionedPackage> packagesToDelete = null;
4580        final long now = System.currentTimeMillis();
4581
4582        synchronized (mPackages) {
4583            final int[] allUsers = sUserManager.getUserIds();
4584            final int libCount = mSharedLibraries.size();
4585            for (int i = 0; i < libCount; i++) {
4586                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4587                if (versionedLib == null) {
4588                    continue;
4589                }
4590                final int versionCount = versionedLib.size();
4591                for (int j = 0; j < versionCount; j++) {
4592                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4593                    // Skip packages that are not static shared libs.
4594                    if (!libInfo.isStatic()) {
4595                        break;
4596                    }
4597                    // Important: We skip static shared libs used for some user since
4598                    // in such a case we need to keep the APK on the device. The check for
4599                    // a lib being used for any user is performed by the uninstall call.
4600                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4601                    // Resolve the package name - we use synthetic package names internally
4602                    final String internalPackageName = resolveInternalPackageNameLPr(
4603                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4604                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4605                    // Skip unused static shared libs cached less than the min period
4606                    // to prevent pruning a lib needed by a subsequently installed package.
4607                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4608                        continue;
4609                    }
4610                    if (packagesToDelete == null) {
4611                        packagesToDelete = new ArrayList<>();
4612                    }
4613                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4614                            declaringPackage.getVersionCode()));
4615                }
4616            }
4617        }
4618
4619        if (packagesToDelete != null) {
4620            final int packageCount = packagesToDelete.size();
4621            for (int i = 0; i < packageCount; i++) {
4622                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4623                // Delete the package synchronously (will fail of the lib used for any user).
4624                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4625                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4626                                == PackageManager.DELETE_SUCCEEDED) {
4627                    if (volume.getUsableSpace() >= neededSpace) {
4628                        return true;
4629                    }
4630                }
4631            }
4632        }
4633
4634        return false;
4635    }
4636
4637    /**
4638     * Update given flags based on encryption status of current user.
4639     */
4640    private int updateFlags(int flags, int userId) {
4641        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4642                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4643            // Caller expressed an explicit opinion about what encryption
4644            // aware/unaware components they want to see, so fall through and
4645            // give them what they want
4646        } else {
4647            // Caller expressed no opinion, so match based on user state
4648            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4649                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4650            } else {
4651                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4652            }
4653        }
4654        return flags;
4655    }
4656
4657    private UserManagerInternal getUserManagerInternal() {
4658        if (mUserManagerInternal == null) {
4659            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4660        }
4661        return mUserManagerInternal;
4662    }
4663
4664    private DeviceIdleController.LocalService getDeviceIdleController() {
4665        if (mDeviceIdleController == null) {
4666            mDeviceIdleController =
4667                    LocalServices.getService(DeviceIdleController.LocalService.class);
4668        }
4669        return mDeviceIdleController;
4670    }
4671
4672    /**
4673     * Update given flags when being used to request {@link PackageInfo}.
4674     */
4675    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4676        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4677        boolean triaged = true;
4678        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4679                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4680            // Caller is asking for component details, so they'd better be
4681            // asking for specific encryption matching behavior, or be triaged
4682            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4683                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4684                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4685                triaged = false;
4686            }
4687        }
4688        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4689                | PackageManager.MATCH_SYSTEM_ONLY
4690                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4691            triaged = false;
4692        }
4693        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4694            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4695                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4696                    + Debug.getCallers(5));
4697        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4698                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4699            // If the caller wants all packages and has a restricted profile associated with it,
4700            // then match all users. This is to make sure that launchers that need to access work
4701            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4702            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4703            flags |= PackageManager.MATCH_ANY_USER;
4704        }
4705        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4706            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4707                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4708        }
4709        return updateFlags(flags, userId);
4710    }
4711
4712    /**
4713     * Update given flags when being used to request {@link ApplicationInfo}.
4714     */
4715    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4716        return updateFlagsForPackage(flags, userId, cookie);
4717    }
4718
4719    /**
4720     * Update given flags when being used to request {@link ComponentInfo}.
4721     */
4722    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4723        if (cookie instanceof Intent) {
4724            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4725                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4726            }
4727        }
4728
4729        boolean triaged = true;
4730        // Caller is asking for component details, so they'd better be
4731        // asking for specific encryption matching behavior, or be triaged
4732        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4733                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4734                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4735            triaged = false;
4736        }
4737        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4738            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4739                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4740        }
4741
4742        return updateFlags(flags, userId);
4743    }
4744
4745    /**
4746     * Update given intent when being used to request {@link ResolveInfo}.
4747     */
4748    private Intent updateIntentForResolve(Intent intent) {
4749        if (intent.getSelector() != null) {
4750            intent = intent.getSelector();
4751        }
4752        if (DEBUG_PREFERRED) {
4753            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4754        }
4755        return intent;
4756    }
4757
4758    /**
4759     * Update given flags when being used to request {@link ResolveInfo}.
4760     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4761     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4762     * flag set. However, this flag is only honoured in three circumstances:
4763     * <ul>
4764     * <li>when called from a system process</li>
4765     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4766     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4767     * action and a {@code android.intent.category.BROWSABLE} category</li>
4768     * </ul>
4769     */
4770    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4771        return updateFlagsForResolve(flags, userId, intent, callingUid,
4772                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4773    }
4774    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4775            boolean wantInstantApps) {
4776        return updateFlagsForResolve(flags, userId, intent, callingUid,
4777                wantInstantApps, false /*onlyExposedExplicitly*/);
4778    }
4779    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4780            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4781        // Safe mode means we shouldn't match any third-party components
4782        if (mSafeMode) {
4783            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4784        }
4785        if (getInstantAppPackageName(callingUid) != null) {
4786            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4787            if (onlyExposedExplicitly) {
4788                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4789            }
4790            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4791            flags |= PackageManager.MATCH_INSTANT;
4792        } else {
4793            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4794            final boolean allowMatchInstant =
4795                    (wantInstantApps
4796                            && Intent.ACTION_VIEW.equals(intent.getAction())
4797                            && hasWebURI(intent))
4798                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4799            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4800                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4801            if (!allowMatchInstant) {
4802                flags &= ~PackageManager.MATCH_INSTANT;
4803            }
4804        }
4805        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4806    }
4807
4808    @Override
4809    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4810        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4811    }
4812
4813    /**
4814     * Important: The provided filterCallingUid is used exclusively to filter out activities
4815     * that can be seen based on user state. It's typically the original caller uid prior
4816     * to clearing. Because it can only be provided by trusted code, it's value can be
4817     * trusted and will be used as-is; unlike userId which will be validated by this method.
4818     */
4819    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4820            int filterCallingUid, int userId) {
4821        if (!sUserManager.exists(userId)) return null;
4822        flags = updateFlagsForComponent(flags, userId, component);
4823        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4824                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4825        synchronized (mPackages) {
4826            PackageParser.Activity a = mActivities.mActivities.get(component);
4827
4828            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4829            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4830                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4831                if (ps == null) return null;
4832                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4833                    return null;
4834                }
4835                return PackageParser.generateActivityInfo(
4836                        a, flags, ps.readUserState(userId), userId);
4837            }
4838            if (mResolveComponentName.equals(component)) {
4839                return PackageParser.generateActivityInfo(
4840                        mResolveActivity, flags, new PackageUserState(), userId);
4841            }
4842        }
4843        return null;
4844    }
4845
4846    @Override
4847    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4848            String resolvedType) {
4849        synchronized (mPackages) {
4850            if (component.equals(mResolveComponentName)) {
4851                // The resolver supports EVERYTHING!
4852                return true;
4853            }
4854            final int callingUid = Binder.getCallingUid();
4855            final int callingUserId = UserHandle.getUserId(callingUid);
4856            PackageParser.Activity a = mActivities.mActivities.get(component);
4857            if (a == null) {
4858                return false;
4859            }
4860            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4861            if (ps == null) {
4862                return false;
4863            }
4864            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4865                return false;
4866            }
4867            for (int i=0; i<a.intents.size(); i++) {
4868                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4869                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4870                    return true;
4871                }
4872            }
4873            return false;
4874        }
4875    }
4876
4877    @Override
4878    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4879        if (!sUserManager.exists(userId)) return null;
4880        final int callingUid = Binder.getCallingUid();
4881        flags = updateFlagsForComponent(flags, userId, component);
4882        enforceCrossUserPermission(callingUid, userId,
4883                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4884        synchronized (mPackages) {
4885            PackageParser.Activity a = mReceivers.mActivities.get(component);
4886            if (DEBUG_PACKAGE_INFO) Log.v(
4887                TAG, "getReceiverInfo " + component + ": " + a);
4888            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4889                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4890                if (ps == null) return null;
4891                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4892                    return null;
4893                }
4894                return PackageParser.generateActivityInfo(
4895                        a, flags, ps.readUserState(userId), userId);
4896            }
4897        }
4898        return null;
4899    }
4900
4901    @Override
4902    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4903            int flags, int userId) {
4904        if (!sUserManager.exists(userId)) return null;
4905        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4906        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4907            return null;
4908        }
4909
4910        flags = updateFlagsForPackage(flags, userId, null);
4911
4912        final boolean canSeeStaticLibraries =
4913                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4914                        == PERMISSION_GRANTED
4915                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4916                        == PERMISSION_GRANTED
4917                || canRequestPackageInstallsInternal(packageName,
4918                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4919                        false  /* throwIfPermNotDeclared*/)
4920                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4921                        == PERMISSION_GRANTED;
4922
4923        synchronized (mPackages) {
4924            List<SharedLibraryInfo> result = null;
4925
4926            final int libCount = mSharedLibraries.size();
4927            for (int i = 0; i < libCount; i++) {
4928                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4929                if (versionedLib == null) {
4930                    continue;
4931                }
4932
4933                final int versionCount = versionedLib.size();
4934                for (int j = 0; j < versionCount; j++) {
4935                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4936                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4937                        break;
4938                    }
4939                    final long identity = Binder.clearCallingIdentity();
4940                    try {
4941                        PackageInfo packageInfo = getPackageInfoVersioned(
4942                                libInfo.getDeclaringPackage(), flags
4943                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4944                        if (packageInfo == null) {
4945                            continue;
4946                        }
4947                    } finally {
4948                        Binder.restoreCallingIdentity(identity);
4949                    }
4950
4951                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4952                            libInfo.getVersion(), libInfo.getType(),
4953                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4954                            flags, userId));
4955
4956                    if (result == null) {
4957                        result = new ArrayList<>();
4958                    }
4959                    result.add(resLibInfo);
4960                }
4961            }
4962
4963            return result != null ? new ParceledListSlice<>(result) : null;
4964        }
4965    }
4966
4967    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4968            SharedLibraryInfo libInfo, int flags, int userId) {
4969        List<VersionedPackage> versionedPackages = null;
4970        final int packageCount = mSettings.mPackages.size();
4971        for (int i = 0; i < packageCount; i++) {
4972            PackageSetting ps = mSettings.mPackages.valueAt(i);
4973
4974            if (ps == null) {
4975                continue;
4976            }
4977
4978            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4979                continue;
4980            }
4981
4982            final String libName = libInfo.getName();
4983            if (libInfo.isStatic()) {
4984                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4985                if (libIdx < 0) {
4986                    continue;
4987                }
4988                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4989                    continue;
4990                }
4991                if (versionedPackages == null) {
4992                    versionedPackages = new ArrayList<>();
4993                }
4994                // If the dependent is a static shared lib, use the public package name
4995                String dependentPackageName = ps.name;
4996                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4997                    dependentPackageName = ps.pkg.manifestPackageName;
4998                }
4999                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5000            } else if (ps.pkg != null) {
5001                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5002                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5003                    if (versionedPackages == null) {
5004                        versionedPackages = new ArrayList<>();
5005                    }
5006                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5007                }
5008            }
5009        }
5010
5011        return versionedPackages;
5012    }
5013
5014    @Override
5015    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5016        if (!sUserManager.exists(userId)) return null;
5017        final int callingUid = Binder.getCallingUid();
5018        flags = updateFlagsForComponent(flags, userId, component);
5019        enforceCrossUserPermission(callingUid, userId,
5020                false /* requireFullPermission */, false /* checkShell */, "get service info");
5021        synchronized (mPackages) {
5022            PackageParser.Service s = mServices.mServices.get(component);
5023            if (DEBUG_PACKAGE_INFO) Log.v(
5024                TAG, "getServiceInfo " + component + ": " + s);
5025            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5026                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5027                if (ps == null) return null;
5028                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5029                    return null;
5030                }
5031                return PackageParser.generateServiceInfo(
5032                        s, flags, ps.readUserState(userId), userId);
5033            }
5034        }
5035        return null;
5036    }
5037
5038    @Override
5039    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5040        if (!sUserManager.exists(userId)) return null;
5041        final int callingUid = Binder.getCallingUid();
5042        flags = updateFlagsForComponent(flags, userId, component);
5043        enforceCrossUserPermission(callingUid, userId,
5044                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5045        synchronized (mPackages) {
5046            PackageParser.Provider p = mProviders.mProviders.get(component);
5047            if (DEBUG_PACKAGE_INFO) Log.v(
5048                TAG, "getProviderInfo " + component + ": " + p);
5049            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5050                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5051                if (ps == null) return null;
5052                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5053                    return null;
5054                }
5055                return PackageParser.generateProviderInfo(
5056                        p, flags, ps.readUserState(userId), userId);
5057            }
5058        }
5059        return null;
5060    }
5061
5062    @Override
5063    public String[] getSystemSharedLibraryNames() {
5064        // allow instant applications
5065        synchronized (mPackages) {
5066            Set<String> libs = null;
5067            final int libCount = mSharedLibraries.size();
5068            for (int i = 0; i < libCount; i++) {
5069                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5070                if (versionedLib == null) {
5071                    continue;
5072                }
5073                final int versionCount = versionedLib.size();
5074                for (int j = 0; j < versionCount; j++) {
5075                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5076                    if (!libEntry.info.isStatic()) {
5077                        if (libs == null) {
5078                            libs = new ArraySet<>();
5079                        }
5080                        libs.add(libEntry.info.getName());
5081                        break;
5082                    }
5083                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5084                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5085                            UserHandle.getUserId(Binder.getCallingUid()),
5086                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5087                        if (libs == null) {
5088                            libs = new ArraySet<>();
5089                        }
5090                        libs.add(libEntry.info.getName());
5091                        break;
5092                    }
5093                }
5094            }
5095
5096            if (libs != null) {
5097                String[] libsArray = new String[libs.size()];
5098                libs.toArray(libsArray);
5099                return libsArray;
5100            }
5101
5102            return null;
5103        }
5104    }
5105
5106    @Override
5107    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5108        // allow instant applications
5109        synchronized (mPackages) {
5110            return mServicesSystemSharedLibraryPackageName;
5111        }
5112    }
5113
5114    @Override
5115    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5116        // allow instant applications
5117        synchronized (mPackages) {
5118            return mSharedSystemSharedLibraryPackageName;
5119        }
5120    }
5121
5122    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5123        for (int i = userList.length - 1; i >= 0; --i) {
5124            final int userId = userList[i];
5125            // don't add instant app to the list of updates
5126            if (pkgSetting.getInstantApp(userId)) {
5127                continue;
5128            }
5129            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5130            if (changedPackages == null) {
5131                changedPackages = new SparseArray<>();
5132                mChangedPackages.put(userId, changedPackages);
5133            }
5134            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5135            if (sequenceNumbers == null) {
5136                sequenceNumbers = new HashMap<>();
5137                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5138            }
5139            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5140            if (sequenceNumber != null) {
5141                changedPackages.remove(sequenceNumber);
5142            }
5143            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5144            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5145        }
5146        mChangedPackagesSequenceNumber++;
5147    }
5148
5149    @Override
5150    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5151        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5152            return null;
5153        }
5154        synchronized (mPackages) {
5155            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5156                return null;
5157            }
5158            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5159            if (changedPackages == null) {
5160                return null;
5161            }
5162            final List<String> packageNames =
5163                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5164            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5165                final String packageName = changedPackages.get(i);
5166                if (packageName != null) {
5167                    packageNames.add(packageName);
5168                }
5169            }
5170            return packageNames.isEmpty()
5171                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5172        }
5173    }
5174
5175    @Override
5176    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5177        // allow instant applications
5178        ArrayList<FeatureInfo> res;
5179        synchronized (mAvailableFeatures) {
5180            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5181            res.addAll(mAvailableFeatures.values());
5182        }
5183        final FeatureInfo fi = new FeatureInfo();
5184        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5185                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5186        res.add(fi);
5187
5188        return new ParceledListSlice<>(res);
5189    }
5190
5191    @Override
5192    public boolean hasSystemFeature(String name, int version) {
5193        // allow instant applications
5194        synchronized (mAvailableFeatures) {
5195            final FeatureInfo feat = mAvailableFeatures.get(name);
5196            if (feat == null) {
5197                return false;
5198            } else {
5199                return feat.version >= version;
5200            }
5201        }
5202    }
5203
5204    @Override
5205    public int checkPermission(String permName, String pkgName, int userId) {
5206        if (!sUserManager.exists(userId)) {
5207            return PackageManager.PERMISSION_DENIED;
5208        }
5209        final int callingUid = Binder.getCallingUid();
5210
5211        synchronized (mPackages) {
5212            final PackageParser.Package p = mPackages.get(pkgName);
5213            if (p != null && p.mExtras != null) {
5214                final PackageSetting ps = (PackageSetting) p.mExtras;
5215                if (filterAppAccessLPr(ps, callingUid, userId)) {
5216                    return PackageManager.PERMISSION_DENIED;
5217                }
5218                final boolean instantApp = ps.getInstantApp(userId);
5219                final PermissionsState permissionsState = ps.getPermissionsState();
5220                if (permissionsState.hasPermission(permName, userId)) {
5221                    if (instantApp) {
5222                        BasePermission bp = mSettings.mPermissions.get(permName);
5223                        if (bp != null && bp.isInstant()) {
5224                            return PackageManager.PERMISSION_GRANTED;
5225                        }
5226                    } else {
5227                        return PackageManager.PERMISSION_GRANTED;
5228                    }
5229                }
5230                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5231                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5232                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5233                    return PackageManager.PERMISSION_GRANTED;
5234                }
5235            }
5236        }
5237
5238        return PackageManager.PERMISSION_DENIED;
5239    }
5240
5241    @Override
5242    public int checkUidPermission(String permName, int uid) {
5243        final int callingUid = Binder.getCallingUid();
5244        final int callingUserId = UserHandle.getUserId(callingUid);
5245        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5246        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5247        final int userId = UserHandle.getUserId(uid);
5248        if (!sUserManager.exists(userId)) {
5249            return PackageManager.PERMISSION_DENIED;
5250        }
5251
5252        synchronized (mPackages) {
5253            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5254            if (obj != null) {
5255                if (obj instanceof SharedUserSetting) {
5256                    if (isCallerInstantApp) {
5257                        return PackageManager.PERMISSION_DENIED;
5258                    }
5259                } else if (obj instanceof PackageSetting) {
5260                    final PackageSetting ps = (PackageSetting) obj;
5261                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5262                        return PackageManager.PERMISSION_DENIED;
5263                    }
5264                }
5265                final SettingBase settingBase = (SettingBase) obj;
5266                final PermissionsState permissionsState = settingBase.getPermissionsState();
5267                if (permissionsState.hasPermission(permName, userId)) {
5268                    if (isUidInstantApp) {
5269                        BasePermission bp = mSettings.mPermissions.get(permName);
5270                        if (bp != null && bp.isInstant()) {
5271                            return PackageManager.PERMISSION_GRANTED;
5272                        }
5273                    } else {
5274                        return PackageManager.PERMISSION_GRANTED;
5275                    }
5276                }
5277                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5278                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5279                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5280                    return PackageManager.PERMISSION_GRANTED;
5281                }
5282            } else {
5283                ArraySet<String> perms = mSystemPermissions.get(uid);
5284                if (perms != null) {
5285                    if (perms.contains(permName)) {
5286                        return PackageManager.PERMISSION_GRANTED;
5287                    }
5288                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5289                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5290                        return PackageManager.PERMISSION_GRANTED;
5291                    }
5292                }
5293            }
5294        }
5295
5296        return PackageManager.PERMISSION_DENIED;
5297    }
5298
5299    @Override
5300    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5301        if (UserHandle.getCallingUserId() != userId) {
5302            mContext.enforceCallingPermission(
5303                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5304                    "isPermissionRevokedByPolicy for user " + userId);
5305        }
5306
5307        if (checkPermission(permission, packageName, userId)
5308                == PackageManager.PERMISSION_GRANTED) {
5309            return false;
5310        }
5311
5312        final int callingUid = Binder.getCallingUid();
5313        if (getInstantAppPackageName(callingUid) != null) {
5314            if (!isCallerSameApp(packageName, callingUid)) {
5315                return false;
5316            }
5317        } else {
5318            if (isInstantApp(packageName, userId)) {
5319                return false;
5320            }
5321        }
5322
5323        final long identity = Binder.clearCallingIdentity();
5324        try {
5325            final int flags = getPermissionFlags(permission, packageName, userId);
5326            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5327        } finally {
5328            Binder.restoreCallingIdentity(identity);
5329        }
5330    }
5331
5332    @Override
5333    public String getPermissionControllerPackageName() {
5334        synchronized (mPackages) {
5335            return mRequiredInstallerPackage;
5336        }
5337    }
5338
5339    /**
5340     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5341     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5342     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5343     * @param message the message to log on security exception
5344     */
5345    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5346            boolean checkShell, String message) {
5347        if (userId < 0) {
5348            throw new IllegalArgumentException("Invalid userId " + userId);
5349        }
5350        if (checkShell) {
5351            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5352        }
5353        if (userId == UserHandle.getUserId(callingUid)) return;
5354        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5355            if (requireFullPermission) {
5356                mContext.enforceCallingOrSelfPermission(
5357                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5358            } else {
5359                try {
5360                    mContext.enforceCallingOrSelfPermission(
5361                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5362                } catch (SecurityException se) {
5363                    mContext.enforceCallingOrSelfPermission(
5364                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5365                }
5366            }
5367        }
5368    }
5369
5370    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5371        if (callingUid == Process.SHELL_UID) {
5372            if (userHandle >= 0
5373                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5374                throw new SecurityException("Shell does not have permission to access user "
5375                        + userHandle);
5376            } else if (userHandle < 0) {
5377                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5378                        + Debug.getCallers(3));
5379            }
5380        }
5381    }
5382
5383    private BasePermission findPermissionTreeLP(String permName) {
5384        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5385            if (permName.startsWith(bp.name) &&
5386                    permName.length() > bp.name.length() &&
5387                    permName.charAt(bp.name.length()) == '.') {
5388                return bp;
5389            }
5390        }
5391        return null;
5392    }
5393
5394    private BasePermission checkPermissionTreeLP(String permName) {
5395        if (permName != null) {
5396            BasePermission bp = findPermissionTreeLP(permName);
5397            if (bp != null) {
5398                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5399                    return bp;
5400                }
5401                throw new SecurityException("Calling uid "
5402                        + Binder.getCallingUid()
5403                        + " is not allowed to add to permission tree "
5404                        + bp.name + " owned by uid " + bp.uid);
5405            }
5406        }
5407        throw new SecurityException("No permission tree found for " + permName);
5408    }
5409
5410    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5411        if (s1 == null) {
5412            return s2 == null;
5413        }
5414        if (s2 == null) {
5415            return false;
5416        }
5417        if (s1.getClass() != s2.getClass()) {
5418            return false;
5419        }
5420        return s1.equals(s2);
5421    }
5422
5423    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5424        if (pi1.icon != pi2.icon) return false;
5425        if (pi1.logo != pi2.logo) return false;
5426        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5427        if (!compareStrings(pi1.name, pi2.name)) return false;
5428        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5429        // We'll take care of setting this one.
5430        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5431        // These are not currently stored in settings.
5432        //if (!compareStrings(pi1.group, pi2.group)) return false;
5433        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5434        //if (pi1.labelRes != pi2.labelRes) return false;
5435        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5436        return true;
5437    }
5438
5439    int permissionInfoFootprint(PermissionInfo info) {
5440        int size = info.name.length();
5441        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5442        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5443        return size;
5444    }
5445
5446    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5447        int size = 0;
5448        for (BasePermission perm : mSettings.mPermissions.values()) {
5449            if (perm.uid == tree.uid) {
5450                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5451            }
5452        }
5453        return size;
5454    }
5455
5456    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5457        // We calculate the max size of permissions defined by this uid and throw
5458        // if that plus the size of 'info' would exceed our stated maximum.
5459        if (tree.uid != Process.SYSTEM_UID) {
5460            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5461            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5462                throw new SecurityException("Permission tree size cap exceeded");
5463            }
5464        }
5465    }
5466
5467    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5468        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5469            throw new SecurityException("Instant apps can't add permissions");
5470        }
5471        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5472            throw new SecurityException("Label must be specified in permission");
5473        }
5474        BasePermission tree = checkPermissionTreeLP(info.name);
5475        BasePermission bp = mSettings.mPermissions.get(info.name);
5476        boolean added = bp == null;
5477        boolean changed = true;
5478        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5479        if (added) {
5480            enforcePermissionCapLocked(info, tree);
5481            bp = new BasePermission(info.name, tree.sourcePackage,
5482                    BasePermission.TYPE_DYNAMIC);
5483        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5484            throw new SecurityException(
5485                    "Not allowed to modify non-dynamic permission "
5486                    + info.name);
5487        } else {
5488            if (bp.protectionLevel == fixedLevel
5489                    && bp.perm.owner.equals(tree.perm.owner)
5490                    && bp.uid == tree.uid
5491                    && comparePermissionInfos(bp.perm.info, info)) {
5492                changed = false;
5493            }
5494        }
5495        bp.protectionLevel = fixedLevel;
5496        info = new PermissionInfo(info);
5497        info.protectionLevel = fixedLevel;
5498        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5499        bp.perm.info.packageName = tree.perm.info.packageName;
5500        bp.uid = tree.uid;
5501        if (added) {
5502            mSettings.mPermissions.put(info.name, bp);
5503        }
5504        if (changed) {
5505            if (!async) {
5506                mSettings.writeLPr();
5507            } else {
5508                scheduleWriteSettingsLocked();
5509            }
5510        }
5511        return added;
5512    }
5513
5514    @Override
5515    public boolean addPermission(PermissionInfo info) {
5516        synchronized (mPackages) {
5517            return addPermissionLocked(info, false);
5518        }
5519    }
5520
5521    @Override
5522    public boolean addPermissionAsync(PermissionInfo info) {
5523        synchronized (mPackages) {
5524            return addPermissionLocked(info, true);
5525        }
5526    }
5527
5528    @Override
5529    public void removePermission(String name) {
5530        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5531            throw new SecurityException("Instant applications don't have access to this method");
5532        }
5533        synchronized (mPackages) {
5534            checkPermissionTreeLP(name);
5535            BasePermission bp = mSettings.mPermissions.get(name);
5536            if (bp != null) {
5537                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5538                    throw new SecurityException(
5539                            "Not allowed to modify non-dynamic permission "
5540                            + name);
5541                }
5542                mSettings.mPermissions.remove(name);
5543                mSettings.writeLPr();
5544            }
5545        }
5546    }
5547
5548    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5549            PackageParser.Package pkg, BasePermission bp) {
5550        int index = pkg.requestedPermissions.indexOf(bp.name);
5551        if (index == -1) {
5552            throw new SecurityException("Package " + pkg.packageName
5553                    + " has not requested permission " + bp.name);
5554        }
5555        if (!bp.isRuntime() && !bp.isDevelopment()) {
5556            throw new SecurityException("Permission " + bp.name
5557                    + " is not a changeable permission type");
5558        }
5559    }
5560
5561    @Override
5562    public void grantRuntimePermission(String packageName, String name, final int userId) {
5563        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5564    }
5565
5566    private void grantRuntimePermission(String packageName, String name, final int userId,
5567            boolean overridePolicy) {
5568        if (!sUserManager.exists(userId)) {
5569            Log.e(TAG, "No such user:" + userId);
5570            return;
5571        }
5572        final int callingUid = Binder.getCallingUid();
5573
5574        mContext.enforceCallingOrSelfPermission(
5575                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5576                "grantRuntimePermission");
5577
5578        enforceCrossUserPermission(callingUid, userId,
5579                true /* requireFullPermission */, true /* checkShell */,
5580                "grantRuntimePermission");
5581
5582        final int uid;
5583        final PackageSetting ps;
5584
5585        synchronized (mPackages) {
5586            final PackageParser.Package pkg = mPackages.get(packageName);
5587            if (pkg == null) {
5588                throw new IllegalArgumentException("Unknown package: " + packageName);
5589            }
5590            final BasePermission bp = mSettings.mPermissions.get(name);
5591            if (bp == null) {
5592                throw new IllegalArgumentException("Unknown permission: " + name);
5593            }
5594            ps = (PackageSetting) pkg.mExtras;
5595            if (ps == null
5596                    || filterAppAccessLPr(ps, callingUid, userId)) {
5597                throw new IllegalArgumentException("Unknown package: " + packageName);
5598            }
5599
5600            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5601
5602            // If a permission review is required for legacy apps we represent
5603            // their permissions as always granted runtime ones since we need
5604            // to keep the review required permission flag per user while an
5605            // install permission's state is shared across all users.
5606            if (mPermissionReviewRequired
5607                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5608                    && bp.isRuntime()) {
5609                return;
5610            }
5611
5612            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5613
5614            final PermissionsState permissionsState = ps.getPermissionsState();
5615
5616            final int flags = permissionsState.getPermissionFlags(name, userId);
5617            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5618                throw new SecurityException("Cannot grant system fixed permission "
5619                        + name + " for package " + packageName);
5620            }
5621            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5622                throw new SecurityException("Cannot grant policy fixed permission "
5623                        + name + " for package " + packageName);
5624            }
5625
5626            if (bp.isDevelopment()) {
5627                // Development permissions must be handled specially, since they are not
5628                // normal runtime permissions.  For now they apply to all users.
5629                if (permissionsState.grantInstallPermission(bp) !=
5630                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5631                    scheduleWriteSettingsLocked();
5632                }
5633                return;
5634            }
5635
5636            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5637                throw new SecurityException("Cannot grant non-ephemeral permission"
5638                        + name + " for package " + packageName);
5639            }
5640
5641            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5642                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5643                return;
5644            }
5645
5646            final int result = permissionsState.grantRuntimePermission(bp, userId);
5647            switch (result) {
5648                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5649                    return;
5650                }
5651
5652                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5653                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5654                    mHandler.post(new Runnable() {
5655                        @Override
5656                        public void run() {
5657                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5658                        }
5659                    });
5660                }
5661                break;
5662            }
5663
5664            if (bp.isRuntime()) {
5665                logPermissionGranted(mContext, name, packageName);
5666            }
5667
5668            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5669
5670            // Not critical if that is lost - app has to request again.
5671            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5672        }
5673
5674        // Only need to do this if user is initialized. Otherwise it's a new user
5675        // and there are no processes running as the user yet and there's no need
5676        // to make an expensive call to remount processes for the changed permissions.
5677        if (READ_EXTERNAL_STORAGE.equals(name)
5678                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5679            final long token = Binder.clearCallingIdentity();
5680            try {
5681                if (sUserManager.isInitialized(userId)) {
5682                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5683                            StorageManagerInternal.class);
5684                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5685                }
5686            } finally {
5687                Binder.restoreCallingIdentity(token);
5688            }
5689        }
5690    }
5691
5692    @Override
5693    public void revokeRuntimePermission(String packageName, String name, int userId) {
5694        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5695    }
5696
5697    private void revokeRuntimePermission(String packageName, String name, int userId,
5698            boolean overridePolicy) {
5699        if (!sUserManager.exists(userId)) {
5700            Log.e(TAG, "No such user:" + userId);
5701            return;
5702        }
5703
5704        mContext.enforceCallingOrSelfPermission(
5705                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5706                "revokeRuntimePermission");
5707
5708        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5709                true /* requireFullPermission */, true /* checkShell */,
5710                "revokeRuntimePermission");
5711
5712        final int appId;
5713
5714        synchronized (mPackages) {
5715            final PackageParser.Package pkg = mPackages.get(packageName);
5716            if (pkg == null) {
5717                throw new IllegalArgumentException("Unknown package: " + packageName);
5718            }
5719            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5720            if (ps == null
5721                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5722                throw new IllegalArgumentException("Unknown package: " + packageName);
5723            }
5724            final BasePermission bp = mSettings.mPermissions.get(name);
5725            if (bp == null) {
5726                throw new IllegalArgumentException("Unknown permission: " + name);
5727            }
5728
5729            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5730
5731            // If a permission review is required for legacy apps we represent
5732            // their permissions as always granted runtime ones since we need
5733            // to keep the review required permission flag per user while an
5734            // install permission's state is shared across all users.
5735            if (mPermissionReviewRequired
5736                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5737                    && bp.isRuntime()) {
5738                return;
5739            }
5740
5741            final PermissionsState permissionsState = ps.getPermissionsState();
5742
5743            final int flags = permissionsState.getPermissionFlags(name, userId);
5744            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5745                throw new SecurityException("Cannot revoke system fixed permission "
5746                        + name + " for package " + packageName);
5747            }
5748            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5749                throw new SecurityException("Cannot revoke policy fixed permission "
5750                        + name + " for package " + packageName);
5751            }
5752
5753            if (bp.isDevelopment()) {
5754                // Development permissions must be handled specially, since they are not
5755                // normal runtime permissions.  For now they apply to all users.
5756                if (permissionsState.revokeInstallPermission(bp) !=
5757                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5758                    scheduleWriteSettingsLocked();
5759                }
5760                return;
5761            }
5762
5763            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5764                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5765                return;
5766            }
5767
5768            if (bp.isRuntime()) {
5769                logPermissionRevoked(mContext, name, packageName);
5770            }
5771
5772            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5773
5774            // Critical, after this call app should never have the permission.
5775            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5776
5777            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5778        }
5779
5780        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5781    }
5782
5783    /**
5784     * Get the first event id for the permission.
5785     *
5786     * <p>There are four events for each permission: <ul>
5787     *     <li>Request permission: first id + 0</li>
5788     *     <li>Grant permission: first id + 1</li>
5789     *     <li>Request for permission denied: first id + 2</li>
5790     *     <li>Revoke permission: first id + 3</li>
5791     * </ul></p>
5792     *
5793     * @param name name of the permission
5794     *
5795     * @return The first event id for the permission
5796     */
5797    private static int getBaseEventId(@NonNull String name) {
5798        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5799
5800        if (eventIdIndex == -1) {
5801            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5802                    || Build.IS_USER) {
5803                Log.i(TAG, "Unknown permission " + name);
5804
5805                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5806            } else {
5807                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5808                //
5809                // Also update
5810                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5811                // - metrics_constants.proto
5812                throw new IllegalStateException("Unknown permission " + name);
5813            }
5814        }
5815
5816        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5817    }
5818
5819    /**
5820     * Log that a permission was revoked.
5821     *
5822     * @param context Context of the caller
5823     * @param name name of the permission
5824     * @param packageName package permission if for
5825     */
5826    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5827            @NonNull String packageName) {
5828        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5829    }
5830
5831    /**
5832     * Log that a permission request was granted.
5833     *
5834     * @param context Context of the caller
5835     * @param name name of the permission
5836     * @param packageName package permission if for
5837     */
5838    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5839            @NonNull String packageName) {
5840        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5841    }
5842
5843    @Override
5844    public void resetRuntimePermissions() {
5845        mContext.enforceCallingOrSelfPermission(
5846                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5847                "revokeRuntimePermission");
5848
5849        int callingUid = Binder.getCallingUid();
5850        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5851            mContext.enforceCallingOrSelfPermission(
5852                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5853                    "resetRuntimePermissions");
5854        }
5855
5856        synchronized (mPackages) {
5857            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5858            for (int userId : UserManagerService.getInstance().getUserIds()) {
5859                final int packageCount = mPackages.size();
5860                for (int i = 0; i < packageCount; i++) {
5861                    PackageParser.Package pkg = mPackages.valueAt(i);
5862                    if (!(pkg.mExtras instanceof PackageSetting)) {
5863                        continue;
5864                    }
5865                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5866                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5867                }
5868            }
5869        }
5870    }
5871
5872    @Override
5873    public int getPermissionFlags(String name, String packageName, int userId) {
5874        if (!sUserManager.exists(userId)) {
5875            return 0;
5876        }
5877
5878        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5879
5880        final int callingUid = Binder.getCallingUid();
5881        enforceCrossUserPermission(callingUid, userId,
5882                true /* requireFullPermission */, false /* checkShell */,
5883                "getPermissionFlags");
5884
5885        synchronized (mPackages) {
5886            final PackageParser.Package pkg = mPackages.get(packageName);
5887            if (pkg == null) {
5888                return 0;
5889            }
5890            final BasePermission bp = mSettings.mPermissions.get(name);
5891            if (bp == null) {
5892                return 0;
5893            }
5894            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5895            if (ps == null
5896                    || filterAppAccessLPr(ps, callingUid, userId)) {
5897                return 0;
5898            }
5899            PermissionsState permissionsState = ps.getPermissionsState();
5900            return permissionsState.getPermissionFlags(name, userId);
5901        }
5902    }
5903
5904    @Override
5905    public void updatePermissionFlags(String name, String packageName, int flagMask,
5906            int flagValues, int userId) {
5907        if (!sUserManager.exists(userId)) {
5908            return;
5909        }
5910
5911        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5912
5913        final int callingUid = Binder.getCallingUid();
5914        enforceCrossUserPermission(callingUid, userId,
5915                true /* requireFullPermission */, true /* checkShell */,
5916                "updatePermissionFlags");
5917
5918        // Only the system can change these flags and nothing else.
5919        if (getCallingUid() != Process.SYSTEM_UID) {
5920            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5921            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5922            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5923            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5924            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5925        }
5926
5927        synchronized (mPackages) {
5928            final PackageParser.Package pkg = mPackages.get(packageName);
5929            if (pkg == null) {
5930                throw new IllegalArgumentException("Unknown package: " + packageName);
5931            }
5932            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5933            if (ps == null
5934                    || filterAppAccessLPr(ps, callingUid, userId)) {
5935                throw new IllegalArgumentException("Unknown package: " + packageName);
5936            }
5937
5938            final BasePermission bp = mSettings.mPermissions.get(name);
5939            if (bp == null) {
5940                throw new IllegalArgumentException("Unknown permission: " + name);
5941            }
5942
5943            PermissionsState permissionsState = ps.getPermissionsState();
5944
5945            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5946
5947            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5948                // Install and runtime permissions are stored in different places,
5949                // so figure out what permission changed and persist the change.
5950                if (permissionsState.getInstallPermissionState(name) != null) {
5951                    scheduleWriteSettingsLocked();
5952                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5953                        || hadState) {
5954                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5955                }
5956            }
5957        }
5958    }
5959
5960    /**
5961     * Update the permission flags for all packages and runtime permissions of a user in order
5962     * to allow device or profile owner to remove POLICY_FIXED.
5963     */
5964    @Override
5965    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5966        if (!sUserManager.exists(userId)) {
5967            return;
5968        }
5969
5970        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5971
5972        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5973                true /* requireFullPermission */, true /* checkShell */,
5974                "updatePermissionFlagsForAllApps");
5975
5976        // Only the system can change system fixed flags.
5977        if (getCallingUid() != Process.SYSTEM_UID) {
5978            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5979            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5980        }
5981
5982        synchronized (mPackages) {
5983            boolean changed = false;
5984            final int packageCount = mPackages.size();
5985            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5986                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5987                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5988                if (ps == null) {
5989                    continue;
5990                }
5991                PermissionsState permissionsState = ps.getPermissionsState();
5992                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5993                        userId, flagMask, flagValues);
5994            }
5995            if (changed) {
5996                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5997            }
5998        }
5999    }
6000
6001    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6002        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6003                != PackageManager.PERMISSION_GRANTED
6004            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6005                != PackageManager.PERMISSION_GRANTED) {
6006            throw new SecurityException(message + " requires "
6007                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6008                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6009        }
6010    }
6011
6012    @Override
6013    public boolean shouldShowRequestPermissionRationale(String permissionName,
6014            String packageName, int userId) {
6015        if (UserHandle.getCallingUserId() != userId) {
6016            mContext.enforceCallingPermission(
6017                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6018                    "canShowRequestPermissionRationale for user " + userId);
6019        }
6020
6021        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6022        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6023            return false;
6024        }
6025
6026        if (checkPermission(permissionName, packageName, userId)
6027                == PackageManager.PERMISSION_GRANTED) {
6028            return false;
6029        }
6030
6031        final int flags;
6032
6033        final long identity = Binder.clearCallingIdentity();
6034        try {
6035            flags = getPermissionFlags(permissionName,
6036                    packageName, userId);
6037        } finally {
6038            Binder.restoreCallingIdentity(identity);
6039        }
6040
6041        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6042                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6043                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6044
6045        if ((flags & fixedFlags) != 0) {
6046            return false;
6047        }
6048
6049        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6050    }
6051
6052    @Override
6053    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6054        mContext.enforceCallingOrSelfPermission(
6055                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6056                "addOnPermissionsChangeListener");
6057
6058        synchronized (mPackages) {
6059            mOnPermissionChangeListeners.addListenerLocked(listener);
6060        }
6061    }
6062
6063    @Override
6064    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6065        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6066            throw new SecurityException("Instant applications don't have access to this method");
6067        }
6068        synchronized (mPackages) {
6069            mOnPermissionChangeListeners.removeListenerLocked(listener);
6070        }
6071    }
6072
6073    @Override
6074    public boolean isProtectedBroadcast(String actionName) {
6075        // allow instant applications
6076        synchronized (mProtectedBroadcasts) {
6077            if (mProtectedBroadcasts.contains(actionName)) {
6078                return true;
6079            } else if (actionName != null) {
6080                // TODO: remove these terrible hacks
6081                if (actionName.startsWith("android.net.netmon.lingerExpired")
6082                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6083                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6084                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6085                    return true;
6086                }
6087            }
6088        }
6089        return false;
6090    }
6091
6092    @Override
6093    public int checkSignatures(String pkg1, String pkg2) {
6094        synchronized (mPackages) {
6095            final PackageParser.Package p1 = mPackages.get(pkg1);
6096            final PackageParser.Package p2 = mPackages.get(pkg2);
6097            if (p1 == null || p1.mExtras == null
6098                    || p2 == null || p2.mExtras == null) {
6099                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6100            }
6101            final int callingUid = Binder.getCallingUid();
6102            final int callingUserId = UserHandle.getUserId(callingUid);
6103            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6104            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6105            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6106                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6107                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6108            }
6109            return compareSignatures(p1.mSignatures, p2.mSignatures);
6110        }
6111    }
6112
6113    @Override
6114    public int checkUidSignatures(int uid1, int uid2) {
6115        final int callingUid = Binder.getCallingUid();
6116        final int callingUserId = UserHandle.getUserId(callingUid);
6117        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6118        // Map to base uids.
6119        uid1 = UserHandle.getAppId(uid1);
6120        uid2 = UserHandle.getAppId(uid2);
6121        // reader
6122        synchronized (mPackages) {
6123            Signature[] s1;
6124            Signature[] s2;
6125            Object obj = mSettings.getUserIdLPr(uid1);
6126            if (obj != null) {
6127                if (obj instanceof SharedUserSetting) {
6128                    if (isCallerInstantApp) {
6129                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6130                    }
6131                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6132                } else if (obj instanceof PackageSetting) {
6133                    final PackageSetting ps = (PackageSetting) obj;
6134                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6135                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6136                    }
6137                    s1 = ps.signatures.mSignatures;
6138                } else {
6139                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6140                }
6141            } else {
6142                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6143            }
6144            obj = mSettings.getUserIdLPr(uid2);
6145            if (obj != null) {
6146                if (obj instanceof SharedUserSetting) {
6147                    if (isCallerInstantApp) {
6148                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6149                    }
6150                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6151                } else if (obj instanceof PackageSetting) {
6152                    final PackageSetting ps = (PackageSetting) obj;
6153                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6154                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6155                    }
6156                    s2 = ps.signatures.mSignatures;
6157                } else {
6158                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6159                }
6160            } else {
6161                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6162            }
6163            return compareSignatures(s1, s2);
6164        }
6165    }
6166
6167    /**
6168     * This method should typically only be used when granting or revoking
6169     * permissions, since the app may immediately restart after this call.
6170     * <p>
6171     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6172     * guard your work against the app being relaunched.
6173     */
6174    private void killUid(int appId, int userId, String reason) {
6175        final long identity = Binder.clearCallingIdentity();
6176        try {
6177            IActivityManager am = ActivityManager.getService();
6178            if (am != null) {
6179                try {
6180                    am.killUid(appId, userId, reason);
6181                } catch (RemoteException e) {
6182                    /* ignore - same process */
6183                }
6184            }
6185        } finally {
6186            Binder.restoreCallingIdentity(identity);
6187        }
6188    }
6189
6190    /**
6191     * Compares two sets of signatures. Returns:
6192     * <br />
6193     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6194     * <br />
6195     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6196     * <br />
6197     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6198     * <br />
6199     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6200     * <br />
6201     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6202     */
6203    static int compareSignatures(Signature[] s1, Signature[] s2) {
6204        if (s1 == null) {
6205            return s2 == null
6206                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6207                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6208        }
6209
6210        if (s2 == null) {
6211            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6212        }
6213
6214        if (s1.length != s2.length) {
6215            return PackageManager.SIGNATURE_NO_MATCH;
6216        }
6217
6218        // Since both signature sets are of size 1, we can compare without HashSets.
6219        if (s1.length == 1) {
6220            return s1[0].equals(s2[0]) ?
6221                    PackageManager.SIGNATURE_MATCH :
6222                    PackageManager.SIGNATURE_NO_MATCH;
6223        }
6224
6225        ArraySet<Signature> set1 = new ArraySet<Signature>();
6226        for (Signature sig : s1) {
6227            set1.add(sig);
6228        }
6229        ArraySet<Signature> set2 = new ArraySet<Signature>();
6230        for (Signature sig : s2) {
6231            set2.add(sig);
6232        }
6233        // Make sure s2 contains all signatures in s1.
6234        if (set1.equals(set2)) {
6235            return PackageManager.SIGNATURE_MATCH;
6236        }
6237        return PackageManager.SIGNATURE_NO_MATCH;
6238    }
6239
6240    /**
6241     * If the database version for this type of package (internal storage or
6242     * external storage) is less than the version where package signatures
6243     * were updated, return true.
6244     */
6245    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6246        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6247        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6248    }
6249
6250    /**
6251     * Used for backward compatibility to make sure any packages with
6252     * certificate chains get upgraded to the new style. {@code existingSigs}
6253     * will be in the old format (since they were stored on disk from before the
6254     * system upgrade) and {@code scannedSigs} will be in the newer format.
6255     */
6256    private int compareSignaturesCompat(PackageSignatures existingSigs,
6257            PackageParser.Package scannedPkg) {
6258        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6259            return PackageManager.SIGNATURE_NO_MATCH;
6260        }
6261
6262        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6263        for (Signature sig : existingSigs.mSignatures) {
6264            existingSet.add(sig);
6265        }
6266        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6267        for (Signature sig : scannedPkg.mSignatures) {
6268            try {
6269                Signature[] chainSignatures = sig.getChainSignatures();
6270                for (Signature chainSig : chainSignatures) {
6271                    scannedCompatSet.add(chainSig);
6272                }
6273            } catch (CertificateEncodingException e) {
6274                scannedCompatSet.add(sig);
6275            }
6276        }
6277        /*
6278         * Make sure the expanded scanned set contains all signatures in the
6279         * existing one.
6280         */
6281        if (scannedCompatSet.equals(existingSet)) {
6282            // Migrate the old signatures to the new scheme.
6283            existingSigs.assignSignatures(scannedPkg.mSignatures);
6284            // The new KeySets will be re-added later in the scanning process.
6285            synchronized (mPackages) {
6286                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6287            }
6288            return PackageManager.SIGNATURE_MATCH;
6289        }
6290        return PackageManager.SIGNATURE_NO_MATCH;
6291    }
6292
6293    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6294        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6295        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6296    }
6297
6298    private int compareSignaturesRecover(PackageSignatures existingSigs,
6299            PackageParser.Package scannedPkg) {
6300        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6301            return PackageManager.SIGNATURE_NO_MATCH;
6302        }
6303
6304        String msg = null;
6305        try {
6306            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6307                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6308                        + scannedPkg.packageName);
6309                return PackageManager.SIGNATURE_MATCH;
6310            }
6311        } catch (CertificateException e) {
6312            msg = e.getMessage();
6313        }
6314
6315        logCriticalInfo(Log.INFO,
6316                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6317        return PackageManager.SIGNATURE_NO_MATCH;
6318    }
6319
6320    @Override
6321    public List<String> getAllPackages() {
6322        final int callingUid = Binder.getCallingUid();
6323        final int callingUserId = UserHandle.getUserId(callingUid);
6324        synchronized (mPackages) {
6325            if (canViewInstantApps(callingUid, callingUserId)) {
6326                return new ArrayList<String>(mPackages.keySet());
6327            }
6328            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6329            final List<String> result = new ArrayList<>();
6330            if (instantAppPkgName != null) {
6331                // caller is an instant application; filter unexposed applications
6332                for (PackageParser.Package pkg : mPackages.values()) {
6333                    if (!pkg.visibleToInstantApps) {
6334                        continue;
6335                    }
6336                    result.add(pkg.packageName);
6337                }
6338            } else {
6339                // caller is a normal application; filter instant applications
6340                for (PackageParser.Package pkg : mPackages.values()) {
6341                    final PackageSetting ps =
6342                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6343                    if (ps != null
6344                            && ps.getInstantApp(callingUserId)
6345                            && !mInstantAppRegistry.isInstantAccessGranted(
6346                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6347                        continue;
6348                    }
6349                    result.add(pkg.packageName);
6350                }
6351            }
6352            return result;
6353        }
6354    }
6355
6356    @Override
6357    public String[] getPackagesForUid(int uid) {
6358        final int callingUid = Binder.getCallingUid();
6359        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6360        final int userId = UserHandle.getUserId(uid);
6361        uid = UserHandle.getAppId(uid);
6362        // reader
6363        synchronized (mPackages) {
6364            Object obj = mSettings.getUserIdLPr(uid);
6365            if (obj instanceof SharedUserSetting) {
6366                if (isCallerInstantApp) {
6367                    return null;
6368                }
6369                final SharedUserSetting sus = (SharedUserSetting) obj;
6370                final int N = sus.packages.size();
6371                String[] res = new String[N];
6372                final Iterator<PackageSetting> it = sus.packages.iterator();
6373                int i = 0;
6374                while (it.hasNext()) {
6375                    PackageSetting ps = it.next();
6376                    if (ps.getInstalled(userId)) {
6377                        res[i++] = ps.name;
6378                    } else {
6379                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6380                    }
6381                }
6382                return res;
6383            } else if (obj instanceof PackageSetting) {
6384                final PackageSetting ps = (PackageSetting) obj;
6385                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6386                    return new String[]{ps.name};
6387                }
6388            }
6389        }
6390        return null;
6391    }
6392
6393    @Override
6394    public String getNameForUid(int uid) {
6395        final int callingUid = Binder.getCallingUid();
6396        if (getInstantAppPackageName(callingUid) != null) {
6397            return null;
6398        }
6399        synchronized (mPackages) {
6400            return getNameForUidLocked(callingUid, uid);
6401        }
6402    }
6403
6404    @Override
6405    public String[] getNamesForUids(int[] uids) {
6406        if (uids == null || uids.length == 0) {
6407            return null;
6408        }
6409        final int callingUid = Binder.getCallingUid();
6410        if (getInstantAppPackageName(callingUid) != null) {
6411            return null;
6412        }
6413        final String[] names = new String[uids.length];
6414        synchronized (mPackages) {
6415            for (int i = uids.length - 1; i >= 0; i--) {
6416                final int uid = uids[i];
6417                names[i] = getNameForUidLocked(callingUid, uid);
6418            }
6419        }
6420        return names;
6421    }
6422
6423    private String getNameForUidLocked(int callingUid, int uid) {
6424        Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6425        if (obj instanceof SharedUserSetting) {
6426            final SharedUserSetting sus = (SharedUserSetting) obj;
6427            return sus.name + ":" + sus.userId;
6428        } else if (obj instanceof PackageSetting) {
6429            final PackageSetting ps = (PackageSetting) obj;
6430            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6431                return null;
6432            }
6433            return ps.name;
6434        }
6435        return null;
6436    }
6437
6438    @Override
6439    public int getUidForSharedUser(String sharedUserName) {
6440        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6441            return -1;
6442        }
6443        if (sharedUserName == null) {
6444            return -1;
6445        }
6446        // reader
6447        synchronized (mPackages) {
6448            SharedUserSetting suid;
6449            try {
6450                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6451                if (suid != null) {
6452                    return suid.userId;
6453                }
6454            } catch (PackageManagerException ignore) {
6455                // can't happen, but, still need to catch it
6456            }
6457            return -1;
6458        }
6459    }
6460
6461    @Override
6462    public int getFlagsForUid(int uid) {
6463        final int callingUid = Binder.getCallingUid();
6464        if (getInstantAppPackageName(callingUid) != null) {
6465            return 0;
6466        }
6467        synchronized (mPackages) {
6468            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6469            if (obj instanceof SharedUserSetting) {
6470                final SharedUserSetting sus = (SharedUserSetting) obj;
6471                return sus.pkgFlags;
6472            } else if (obj instanceof PackageSetting) {
6473                final PackageSetting ps = (PackageSetting) obj;
6474                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6475                    return 0;
6476                }
6477                return ps.pkgFlags;
6478            }
6479        }
6480        return 0;
6481    }
6482
6483    @Override
6484    public int getPrivateFlagsForUid(int uid) {
6485        final int callingUid = Binder.getCallingUid();
6486        if (getInstantAppPackageName(callingUid) != null) {
6487            return 0;
6488        }
6489        synchronized (mPackages) {
6490            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6491            if (obj instanceof SharedUserSetting) {
6492                final SharedUserSetting sus = (SharedUserSetting) obj;
6493                return sus.pkgPrivateFlags;
6494            } else if (obj instanceof PackageSetting) {
6495                final PackageSetting ps = (PackageSetting) obj;
6496                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6497                    return 0;
6498                }
6499                return ps.pkgPrivateFlags;
6500            }
6501        }
6502        return 0;
6503    }
6504
6505    @Override
6506    public boolean isUidPrivileged(int uid) {
6507        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6508            return false;
6509        }
6510        uid = UserHandle.getAppId(uid);
6511        // reader
6512        synchronized (mPackages) {
6513            Object obj = mSettings.getUserIdLPr(uid);
6514            if (obj instanceof SharedUserSetting) {
6515                final SharedUserSetting sus = (SharedUserSetting) obj;
6516                final Iterator<PackageSetting> it = sus.packages.iterator();
6517                while (it.hasNext()) {
6518                    if (it.next().isPrivileged()) {
6519                        return true;
6520                    }
6521                }
6522            } else if (obj instanceof PackageSetting) {
6523                final PackageSetting ps = (PackageSetting) obj;
6524                return ps.isPrivileged();
6525            }
6526        }
6527        return false;
6528    }
6529
6530    @Override
6531    public String[] getAppOpPermissionPackages(String permissionName) {
6532        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6533            return null;
6534        }
6535        synchronized (mPackages) {
6536            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6537            if (pkgs == null) {
6538                return null;
6539            }
6540            return pkgs.toArray(new String[pkgs.size()]);
6541        }
6542    }
6543
6544    @Override
6545    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6546            int flags, int userId) {
6547        return resolveIntentInternal(
6548                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6549    }
6550
6551    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6552            int flags, int userId, boolean resolveForStart) {
6553        try {
6554            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6555
6556            if (!sUserManager.exists(userId)) return null;
6557            final int callingUid = Binder.getCallingUid();
6558            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6559            enforceCrossUserPermission(callingUid, userId,
6560                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6561
6562            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6563            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6564                    flags, callingUid, userId, resolveForStart);
6565            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6566
6567            final ResolveInfo bestChoice =
6568                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6569            return bestChoice;
6570        } finally {
6571            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6572        }
6573    }
6574
6575    @Override
6576    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6577        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6578            throw new SecurityException(
6579                    "findPersistentPreferredActivity can only be run by the system");
6580        }
6581        if (!sUserManager.exists(userId)) {
6582            return null;
6583        }
6584        final int callingUid = Binder.getCallingUid();
6585        intent = updateIntentForResolve(intent);
6586        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6587        final int flags = updateFlagsForResolve(
6588                0, userId, intent, callingUid, false /*includeInstantApps*/);
6589        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6590                userId);
6591        synchronized (mPackages) {
6592            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6593                    userId);
6594        }
6595    }
6596
6597    @Override
6598    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6599            IntentFilter filter, int match, ComponentName activity) {
6600        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6601            return;
6602        }
6603        final int userId = UserHandle.getCallingUserId();
6604        if (DEBUG_PREFERRED) {
6605            Log.v(TAG, "setLastChosenActivity intent=" + intent
6606                + " resolvedType=" + resolvedType
6607                + " flags=" + flags
6608                + " filter=" + filter
6609                + " match=" + match
6610                + " activity=" + activity);
6611            filter.dump(new PrintStreamPrinter(System.out), "    ");
6612        }
6613        intent.setComponent(null);
6614        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6615                userId);
6616        // Find any earlier preferred or last chosen entries and nuke them
6617        findPreferredActivity(intent, resolvedType,
6618                flags, query, 0, false, true, false, userId);
6619        // Add the new activity as the last chosen for this filter
6620        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6621                "Setting last chosen");
6622    }
6623
6624    @Override
6625    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6626        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6627            return null;
6628        }
6629        final int userId = UserHandle.getCallingUserId();
6630        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6631        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6632                userId);
6633        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6634                false, false, false, userId);
6635    }
6636
6637    /**
6638     * Returns whether or not instant apps have been disabled remotely.
6639     */
6640    private boolean isEphemeralDisabled() {
6641        return mEphemeralAppsDisabled;
6642    }
6643
6644    private boolean isInstantAppAllowed(
6645            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6646            boolean skipPackageCheck) {
6647        if (mInstantAppResolverConnection == null) {
6648            return false;
6649        }
6650        if (mInstantAppInstallerActivity == null) {
6651            return false;
6652        }
6653        if (intent.getComponent() != null) {
6654            return false;
6655        }
6656        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6657            return false;
6658        }
6659        if (!skipPackageCheck && intent.getPackage() != null) {
6660            return false;
6661        }
6662        final boolean isWebUri = hasWebURI(intent);
6663        if (!isWebUri || intent.getData().getHost() == null) {
6664            return false;
6665        }
6666        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6667        // Or if there's already an ephemeral app installed that handles the action
6668        synchronized (mPackages) {
6669            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6670            for (int n = 0; n < count; n++) {
6671                final ResolveInfo info = resolvedActivities.get(n);
6672                final String packageName = info.activityInfo.packageName;
6673                final PackageSetting ps = mSettings.mPackages.get(packageName);
6674                if (ps != null) {
6675                    // only check domain verification status if the app is not a browser
6676                    if (!info.handleAllWebDataURI) {
6677                        // Try to get the status from User settings first
6678                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6679                        final int status = (int) (packedStatus >> 32);
6680                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6681                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6682                            if (DEBUG_EPHEMERAL) {
6683                                Slog.v(TAG, "DENY instant app;"
6684                                    + " pkg: " + packageName + ", status: " + status);
6685                            }
6686                            return false;
6687                        }
6688                    }
6689                    if (ps.getInstantApp(userId)) {
6690                        if (DEBUG_EPHEMERAL) {
6691                            Slog.v(TAG, "DENY instant app installed;"
6692                                    + " pkg: " + packageName);
6693                        }
6694                        return false;
6695                    }
6696                }
6697            }
6698        }
6699        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6700        return true;
6701    }
6702
6703    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6704            Intent origIntent, String resolvedType, String callingPackage,
6705            Bundle verificationBundle, int userId) {
6706        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6707                new InstantAppRequest(responseObj, origIntent, resolvedType,
6708                        callingPackage, userId, verificationBundle));
6709        mHandler.sendMessage(msg);
6710    }
6711
6712    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6713            int flags, List<ResolveInfo> query, int userId) {
6714        if (query != null) {
6715            final int N = query.size();
6716            if (N == 1) {
6717                return query.get(0);
6718            } else if (N > 1) {
6719                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6720                // If there is more than one activity with the same priority,
6721                // then let the user decide between them.
6722                ResolveInfo r0 = query.get(0);
6723                ResolveInfo r1 = query.get(1);
6724                if (DEBUG_INTENT_MATCHING || debug) {
6725                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6726                            + r1.activityInfo.name + "=" + r1.priority);
6727                }
6728                // If the first activity has a higher priority, or a different
6729                // default, then it is always desirable to pick it.
6730                if (r0.priority != r1.priority
6731                        || r0.preferredOrder != r1.preferredOrder
6732                        || r0.isDefault != r1.isDefault) {
6733                    return query.get(0);
6734                }
6735                // If we have saved a preference for a preferred activity for
6736                // this Intent, use that.
6737                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6738                        flags, query, r0.priority, true, false, debug, userId);
6739                if (ri != null) {
6740                    return ri;
6741                }
6742                // If we have an ephemeral app, use it
6743                for (int i = 0; i < N; i++) {
6744                    ri = query.get(i);
6745                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6746                        final String packageName = ri.activityInfo.packageName;
6747                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6748                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6749                        final int status = (int)(packedStatus >> 32);
6750                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6751                            return ri;
6752                        }
6753                    }
6754                }
6755                ri = new ResolveInfo(mResolveInfo);
6756                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6757                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6758                // If all of the options come from the same package, show the application's
6759                // label and icon instead of the generic resolver's.
6760                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6761                // and then throw away the ResolveInfo itself, meaning that the caller loses
6762                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6763                // a fallback for this case; we only set the target package's resources on
6764                // the ResolveInfo, not the ActivityInfo.
6765                final String intentPackage = intent.getPackage();
6766                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6767                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6768                    ri.resolvePackageName = intentPackage;
6769                    if (userNeedsBadging(userId)) {
6770                        ri.noResourceId = true;
6771                    } else {
6772                        ri.icon = appi.icon;
6773                    }
6774                    ri.iconResourceId = appi.icon;
6775                    ri.labelRes = appi.labelRes;
6776                }
6777                ri.activityInfo.applicationInfo = new ApplicationInfo(
6778                        ri.activityInfo.applicationInfo);
6779                if (userId != 0) {
6780                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6781                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6782                }
6783                // Make sure that the resolver is displayable in car mode
6784                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6785                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6786                return ri;
6787            }
6788        }
6789        return null;
6790    }
6791
6792    /**
6793     * Return true if the given list is not empty and all of its contents have
6794     * an activityInfo with the given package name.
6795     */
6796    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6797        if (ArrayUtils.isEmpty(list)) {
6798            return false;
6799        }
6800        for (int i = 0, N = list.size(); i < N; i++) {
6801            final ResolveInfo ri = list.get(i);
6802            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6803            if (ai == null || !packageName.equals(ai.packageName)) {
6804                return false;
6805            }
6806        }
6807        return true;
6808    }
6809
6810    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6811            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6812        final int N = query.size();
6813        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6814                .get(userId);
6815        // Get the list of persistent preferred activities that handle the intent
6816        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6817        List<PersistentPreferredActivity> pprefs = ppir != null
6818                ? ppir.queryIntent(intent, resolvedType,
6819                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6820                        userId)
6821                : null;
6822        if (pprefs != null && pprefs.size() > 0) {
6823            final int M = pprefs.size();
6824            for (int i=0; i<M; i++) {
6825                final PersistentPreferredActivity ppa = pprefs.get(i);
6826                if (DEBUG_PREFERRED || debug) {
6827                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6828                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6829                            + "\n  component=" + ppa.mComponent);
6830                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6831                }
6832                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6833                        flags | MATCH_DISABLED_COMPONENTS, userId);
6834                if (DEBUG_PREFERRED || debug) {
6835                    Slog.v(TAG, "Found persistent preferred activity:");
6836                    if (ai != null) {
6837                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6838                    } else {
6839                        Slog.v(TAG, "  null");
6840                    }
6841                }
6842                if (ai == null) {
6843                    // This previously registered persistent preferred activity
6844                    // component is no longer known. Ignore it and do NOT remove it.
6845                    continue;
6846                }
6847                for (int j=0; j<N; j++) {
6848                    final ResolveInfo ri = query.get(j);
6849                    if (!ri.activityInfo.applicationInfo.packageName
6850                            .equals(ai.applicationInfo.packageName)) {
6851                        continue;
6852                    }
6853                    if (!ri.activityInfo.name.equals(ai.name)) {
6854                        continue;
6855                    }
6856                    //  Found a persistent preference that can handle the intent.
6857                    if (DEBUG_PREFERRED || debug) {
6858                        Slog.v(TAG, "Returning persistent preferred activity: " +
6859                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6860                    }
6861                    return ri;
6862                }
6863            }
6864        }
6865        return null;
6866    }
6867
6868    // TODO: handle preferred activities missing while user has amnesia
6869    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6870            List<ResolveInfo> query, int priority, boolean always,
6871            boolean removeMatches, boolean debug, int userId) {
6872        if (!sUserManager.exists(userId)) return null;
6873        final int callingUid = Binder.getCallingUid();
6874        flags = updateFlagsForResolve(
6875                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6876        intent = updateIntentForResolve(intent);
6877        // writer
6878        synchronized (mPackages) {
6879            // Try to find a matching persistent preferred activity.
6880            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6881                    debug, userId);
6882
6883            // If a persistent preferred activity matched, use it.
6884            if (pri != null) {
6885                return pri;
6886            }
6887
6888            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6889            // Get the list of preferred activities that handle the intent
6890            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6891            List<PreferredActivity> prefs = pir != null
6892                    ? pir.queryIntent(intent, resolvedType,
6893                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6894                            userId)
6895                    : null;
6896            if (prefs != null && prefs.size() > 0) {
6897                boolean changed = false;
6898                try {
6899                    // First figure out how good the original match set is.
6900                    // We will only allow preferred activities that came
6901                    // from the same match quality.
6902                    int match = 0;
6903
6904                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6905
6906                    final int N = query.size();
6907                    for (int j=0; j<N; j++) {
6908                        final ResolveInfo ri = query.get(j);
6909                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6910                                + ": 0x" + Integer.toHexString(match));
6911                        if (ri.match > match) {
6912                            match = ri.match;
6913                        }
6914                    }
6915
6916                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6917                            + Integer.toHexString(match));
6918
6919                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6920                    final int M = prefs.size();
6921                    for (int i=0; i<M; i++) {
6922                        final PreferredActivity pa = prefs.get(i);
6923                        if (DEBUG_PREFERRED || debug) {
6924                            Slog.v(TAG, "Checking PreferredActivity ds="
6925                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6926                                    + "\n  component=" + pa.mPref.mComponent);
6927                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6928                        }
6929                        if (pa.mPref.mMatch != match) {
6930                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6931                                    + Integer.toHexString(pa.mPref.mMatch));
6932                            continue;
6933                        }
6934                        // If it's not an "always" type preferred activity and that's what we're
6935                        // looking for, skip it.
6936                        if (always && !pa.mPref.mAlways) {
6937                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6938                            continue;
6939                        }
6940                        final ActivityInfo ai = getActivityInfo(
6941                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6942                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6943                                userId);
6944                        if (DEBUG_PREFERRED || debug) {
6945                            Slog.v(TAG, "Found preferred activity:");
6946                            if (ai != null) {
6947                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6948                            } else {
6949                                Slog.v(TAG, "  null");
6950                            }
6951                        }
6952                        if (ai == null) {
6953                            // This previously registered preferred activity
6954                            // component is no longer known.  Most likely an update
6955                            // to the app was installed and in the new version this
6956                            // component no longer exists.  Clean it up by removing
6957                            // it from the preferred activities list, and skip it.
6958                            Slog.w(TAG, "Removing dangling preferred activity: "
6959                                    + pa.mPref.mComponent);
6960                            pir.removeFilter(pa);
6961                            changed = true;
6962                            continue;
6963                        }
6964                        for (int j=0; j<N; j++) {
6965                            final ResolveInfo ri = query.get(j);
6966                            if (!ri.activityInfo.applicationInfo.packageName
6967                                    .equals(ai.applicationInfo.packageName)) {
6968                                continue;
6969                            }
6970                            if (!ri.activityInfo.name.equals(ai.name)) {
6971                                continue;
6972                            }
6973
6974                            if (removeMatches) {
6975                                pir.removeFilter(pa);
6976                                changed = true;
6977                                if (DEBUG_PREFERRED) {
6978                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6979                                }
6980                                break;
6981                            }
6982
6983                            // Okay we found a previously set preferred or last chosen app.
6984                            // If the result set is different from when this
6985                            // was created, we need to clear it and re-ask the
6986                            // user their preference, if we're looking for an "always" type entry.
6987                            if (always && !pa.mPref.sameSet(query)) {
6988                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6989                                        + intent + " type " + resolvedType);
6990                                if (DEBUG_PREFERRED) {
6991                                    Slog.v(TAG, "Removing preferred activity since set changed "
6992                                            + pa.mPref.mComponent);
6993                                }
6994                                pir.removeFilter(pa);
6995                                // Re-add the filter as a "last chosen" entry (!always)
6996                                PreferredActivity lastChosen = new PreferredActivity(
6997                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6998                                pir.addFilter(lastChosen);
6999                                changed = true;
7000                                return null;
7001                            }
7002
7003                            // Yay! Either the set matched or we're looking for the last chosen
7004                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7005                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7006                            return ri;
7007                        }
7008                    }
7009                } finally {
7010                    if (changed) {
7011                        if (DEBUG_PREFERRED) {
7012                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7013                        }
7014                        scheduleWritePackageRestrictionsLocked(userId);
7015                    }
7016                }
7017            }
7018        }
7019        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7020        return null;
7021    }
7022
7023    /*
7024     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7025     */
7026    @Override
7027    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7028            int targetUserId) {
7029        mContext.enforceCallingOrSelfPermission(
7030                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7031        List<CrossProfileIntentFilter> matches =
7032                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7033        if (matches != null) {
7034            int size = matches.size();
7035            for (int i = 0; i < size; i++) {
7036                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7037            }
7038        }
7039        if (hasWebURI(intent)) {
7040            // cross-profile app linking works only towards the parent.
7041            final int callingUid = Binder.getCallingUid();
7042            final UserInfo parent = getProfileParent(sourceUserId);
7043            synchronized(mPackages) {
7044                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7045                        false /*includeInstantApps*/);
7046                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7047                        intent, resolvedType, flags, sourceUserId, parent.id);
7048                return xpDomainInfo != null;
7049            }
7050        }
7051        return false;
7052    }
7053
7054    private UserInfo getProfileParent(int userId) {
7055        final long identity = Binder.clearCallingIdentity();
7056        try {
7057            return sUserManager.getProfileParent(userId);
7058        } finally {
7059            Binder.restoreCallingIdentity(identity);
7060        }
7061    }
7062
7063    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7064            String resolvedType, int userId) {
7065        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7066        if (resolver != null) {
7067            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7068        }
7069        return null;
7070    }
7071
7072    @Override
7073    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7074            String resolvedType, int flags, int userId) {
7075        try {
7076            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7077
7078            return new ParceledListSlice<>(
7079                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7080        } finally {
7081            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7082        }
7083    }
7084
7085    /**
7086     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7087     * instant, returns {@code null}.
7088     */
7089    private String getInstantAppPackageName(int callingUid) {
7090        synchronized (mPackages) {
7091            // If the caller is an isolated app use the owner's uid for the lookup.
7092            if (Process.isIsolated(callingUid)) {
7093                callingUid = mIsolatedOwners.get(callingUid);
7094            }
7095            final int appId = UserHandle.getAppId(callingUid);
7096            final Object obj = mSettings.getUserIdLPr(appId);
7097            if (obj instanceof PackageSetting) {
7098                final PackageSetting ps = (PackageSetting) obj;
7099                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7100                return isInstantApp ? ps.pkg.packageName : null;
7101            }
7102        }
7103        return null;
7104    }
7105
7106    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7107            String resolvedType, int flags, int userId) {
7108        return queryIntentActivitiesInternal(
7109                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
7110    }
7111
7112    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7113            String resolvedType, int flags, int filterCallingUid, int userId,
7114            boolean resolveForStart) {
7115        if (!sUserManager.exists(userId)) return Collections.emptyList();
7116        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7117        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7118                false /* requireFullPermission */, false /* checkShell */,
7119                "query intent activities");
7120        final String pkgName = intent.getPackage();
7121        ComponentName comp = intent.getComponent();
7122        if (comp == null) {
7123            if (intent.getSelector() != null) {
7124                intent = intent.getSelector();
7125                comp = intent.getComponent();
7126            }
7127        }
7128
7129        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7130                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7131        if (comp != null) {
7132            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7133            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7134            if (ai != null) {
7135                // When specifying an explicit component, we prevent the activity from being
7136                // used when either 1) the calling package is normal and the activity is within
7137                // an ephemeral application or 2) the calling package is ephemeral and the
7138                // activity is not visible to ephemeral applications.
7139                final boolean matchInstantApp =
7140                        (flags & PackageManager.MATCH_INSTANT) != 0;
7141                final boolean matchVisibleToInstantAppOnly =
7142                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7143                final boolean matchExplicitlyVisibleOnly =
7144                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7145                final boolean isCallerInstantApp =
7146                        instantAppPkgName != null;
7147                final boolean isTargetSameInstantApp =
7148                        comp.getPackageName().equals(instantAppPkgName);
7149                final boolean isTargetInstantApp =
7150                        (ai.applicationInfo.privateFlags
7151                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7152                final boolean isTargetVisibleToInstantApp =
7153                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7154                final boolean isTargetExplicitlyVisibleToInstantApp =
7155                        isTargetVisibleToInstantApp
7156                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7157                final boolean isTargetHiddenFromInstantApp =
7158                        !isTargetVisibleToInstantApp
7159                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7160                final boolean blockResolution =
7161                        !isTargetSameInstantApp
7162                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7163                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7164                                        && isTargetHiddenFromInstantApp));
7165                if (!blockResolution) {
7166                    final ResolveInfo ri = new ResolveInfo();
7167                    ri.activityInfo = ai;
7168                    list.add(ri);
7169                }
7170            }
7171            return applyPostResolutionFilter(list, instantAppPkgName);
7172        }
7173
7174        // reader
7175        boolean sortResult = false;
7176        boolean addEphemeral = false;
7177        List<ResolveInfo> result;
7178        final boolean ephemeralDisabled = isEphemeralDisabled();
7179        synchronized (mPackages) {
7180            if (pkgName == null) {
7181                List<CrossProfileIntentFilter> matchingFilters =
7182                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7183                // Check for results that need to skip the current profile.
7184                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7185                        resolvedType, flags, userId);
7186                if (xpResolveInfo != null) {
7187                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7188                    xpResult.add(xpResolveInfo);
7189                    return applyPostResolutionFilter(
7190                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
7191                }
7192
7193                // Check for results in the current profile.
7194                result = filterIfNotSystemUser(mActivities.queryIntent(
7195                        intent, resolvedType, flags, userId), userId);
7196                addEphemeral = !ephemeralDisabled
7197                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7198                // Check for cross profile results.
7199                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7200                xpResolveInfo = queryCrossProfileIntents(
7201                        matchingFilters, intent, resolvedType, flags, userId,
7202                        hasNonNegativePriorityResult);
7203                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7204                    boolean isVisibleToUser = filterIfNotSystemUser(
7205                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7206                    if (isVisibleToUser) {
7207                        result.add(xpResolveInfo);
7208                        sortResult = true;
7209                    }
7210                }
7211                if (hasWebURI(intent)) {
7212                    CrossProfileDomainInfo xpDomainInfo = null;
7213                    final UserInfo parent = getProfileParent(userId);
7214                    if (parent != null) {
7215                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7216                                flags, userId, parent.id);
7217                    }
7218                    if (xpDomainInfo != null) {
7219                        if (xpResolveInfo != null) {
7220                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7221                            // in the result.
7222                            result.remove(xpResolveInfo);
7223                        }
7224                        if (result.size() == 0 && !addEphemeral) {
7225                            // No result in current profile, but found candidate in parent user.
7226                            // And we are not going to add emphemeral app, so we can return the
7227                            // result straight away.
7228                            result.add(xpDomainInfo.resolveInfo);
7229                            return applyPostResolutionFilter(result, instantAppPkgName);
7230                        }
7231                    } else if (result.size() <= 1 && !addEphemeral) {
7232                        // No result in parent user and <= 1 result in current profile, and we
7233                        // are not going to add emphemeral app, so we can return the result without
7234                        // further processing.
7235                        return applyPostResolutionFilter(result, instantAppPkgName);
7236                    }
7237                    // We have more than one candidate (combining results from current and parent
7238                    // profile), so we need filtering and sorting.
7239                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7240                            intent, flags, result, xpDomainInfo, userId);
7241                    sortResult = true;
7242                }
7243            } else {
7244                final PackageParser.Package pkg = mPackages.get(pkgName);
7245                result = null;
7246                if (pkg != null) {
7247                    result = filterIfNotSystemUser(
7248                            mActivities.queryIntentForPackage(
7249                                    intent, resolvedType, flags, pkg.activities, userId),
7250                            userId);
7251                }
7252                if (result == null || result.size() == 0) {
7253                    // the caller wants to resolve for a particular package; however, there
7254                    // were no installed results, so, try to find an ephemeral result
7255                    addEphemeral = !ephemeralDisabled
7256                            && isInstantAppAllowed(
7257                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7258                    if (result == null) {
7259                        result = new ArrayList<>();
7260                    }
7261                }
7262            }
7263        }
7264        if (addEphemeral) {
7265            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7266        }
7267        if (sortResult) {
7268            Collections.sort(result, mResolvePrioritySorter);
7269        }
7270        return applyPostResolutionFilter(result, instantAppPkgName);
7271    }
7272
7273    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7274            String resolvedType, int flags, int userId) {
7275        // first, check to see if we've got an instant app already installed
7276        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7277        ResolveInfo localInstantApp = null;
7278        boolean blockResolution = false;
7279        if (!alreadyResolvedLocally) {
7280            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7281                    flags
7282                        | PackageManager.GET_RESOLVED_FILTER
7283                        | PackageManager.MATCH_INSTANT
7284                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7285                    userId);
7286            for (int i = instantApps.size() - 1; i >= 0; --i) {
7287                final ResolveInfo info = instantApps.get(i);
7288                final String packageName = info.activityInfo.packageName;
7289                final PackageSetting ps = mSettings.mPackages.get(packageName);
7290                if (ps.getInstantApp(userId)) {
7291                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7292                    final int status = (int)(packedStatus >> 32);
7293                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7294                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7295                        // there's a local instant application installed, but, the user has
7296                        // chosen to never use it; skip resolution and don't acknowledge
7297                        // an instant application is even available
7298                        if (DEBUG_EPHEMERAL) {
7299                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7300                        }
7301                        blockResolution = true;
7302                        break;
7303                    } else {
7304                        // we have a locally installed instant application; skip resolution
7305                        // but acknowledge there's an instant application available
7306                        if (DEBUG_EPHEMERAL) {
7307                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7308                        }
7309                        localInstantApp = info;
7310                        break;
7311                    }
7312                }
7313            }
7314        }
7315        // no app installed, let's see if one's available
7316        AuxiliaryResolveInfo auxiliaryResponse = null;
7317        if (!blockResolution) {
7318            if (localInstantApp == null) {
7319                // we don't have an instant app locally, resolve externally
7320                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7321                final InstantAppRequest requestObject = new InstantAppRequest(
7322                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7323                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7324                auxiliaryResponse =
7325                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7326                                mContext, mInstantAppResolverConnection, requestObject);
7327                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7328            } else {
7329                // we have an instant application locally, but, we can't admit that since
7330                // callers shouldn't be able to determine prior browsing. create a dummy
7331                // auxiliary response so the downstream code behaves as if there's an
7332                // instant application available externally. when it comes time to start
7333                // the instant application, we'll do the right thing.
7334                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7335                auxiliaryResponse = new AuxiliaryResolveInfo(
7336                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7337            }
7338        }
7339        if (auxiliaryResponse != null) {
7340            if (DEBUG_EPHEMERAL) {
7341                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7342            }
7343            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7344            final PackageSetting ps =
7345                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7346            if (ps != null) {
7347                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7348                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7349                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7350                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7351                // make sure this resolver is the default
7352                ephemeralInstaller.isDefault = true;
7353                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7354                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7355                // add a non-generic filter
7356                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7357                ephemeralInstaller.filter.addDataPath(
7358                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7359                ephemeralInstaller.isInstantAppAvailable = true;
7360                result.add(ephemeralInstaller);
7361            }
7362        }
7363        return result;
7364    }
7365
7366    private static class CrossProfileDomainInfo {
7367        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7368        ResolveInfo resolveInfo;
7369        /* Best domain verification status of the activities found in the other profile */
7370        int bestDomainVerificationStatus;
7371    }
7372
7373    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7374            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7375        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7376                sourceUserId)) {
7377            return null;
7378        }
7379        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7380                resolvedType, flags, parentUserId);
7381
7382        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7383            return null;
7384        }
7385        CrossProfileDomainInfo result = null;
7386        int size = resultTargetUser.size();
7387        for (int i = 0; i < size; i++) {
7388            ResolveInfo riTargetUser = resultTargetUser.get(i);
7389            // Intent filter verification is only for filters that specify a host. So don't return
7390            // those that handle all web uris.
7391            if (riTargetUser.handleAllWebDataURI) {
7392                continue;
7393            }
7394            String packageName = riTargetUser.activityInfo.packageName;
7395            PackageSetting ps = mSettings.mPackages.get(packageName);
7396            if (ps == null) {
7397                continue;
7398            }
7399            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7400            int status = (int)(verificationState >> 32);
7401            if (result == null) {
7402                result = new CrossProfileDomainInfo();
7403                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7404                        sourceUserId, parentUserId);
7405                result.bestDomainVerificationStatus = status;
7406            } else {
7407                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7408                        result.bestDomainVerificationStatus);
7409            }
7410        }
7411        // Don't consider matches with status NEVER across profiles.
7412        if (result != null && result.bestDomainVerificationStatus
7413                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7414            return null;
7415        }
7416        return result;
7417    }
7418
7419    /**
7420     * Verification statuses are ordered from the worse to the best, except for
7421     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7422     */
7423    private int bestDomainVerificationStatus(int status1, int status2) {
7424        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7425            return status2;
7426        }
7427        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7428            return status1;
7429        }
7430        return (int) MathUtils.max(status1, status2);
7431    }
7432
7433    private boolean isUserEnabled(int userId) {
7434        long callingId = Binder.clearCallingIdentity();
7435        try {
7436            UserInfo userInfo = sUserManager.getUserInfo(userId);
7437            return userInfo != null && userInfo.isEnabled();
7438        } finally {
7439            Binder.restoreCallingIdentity(callingId);
7440        }
7441    }
7442
7443    /**
7444     * Filter out activities with systemUserOnly flag set, when current user is not System.
7445     *
7446     * @return filtered list
7447     */
7448    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7449        if (userId == UserHandle.USER_SYSTEM) {
7450            return resolveInfos;
7451        }
7452        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7453            ResolveInfo info = resolveInfos.get(i);
7454            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7455                resolveInfos.remove(i);
7456            }
7457        }
7458        return resolveInfos;
7459    }
7460
7461    /**
7462     * Filters out ephemeral activities.
7463     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7464     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7465     *
7466     * @param resolveInfos The pre-filtered list of resolved activities
7467     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7468     *          is performed.
7469     * @return A filtered list of resolved activities.
7470     */
7471    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7472            String ephemeralPkgName) {
7473        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7474            final ResolveInfo info = resolveInfos.get(i);
7475            // TODO: When adding on-demand split support for non-instant apps, remove this check
7476            // and always apply post filtering
7477            // allow activities that are defined in the provided package
7478            if (info.activityInfo.splitName != null
7479                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7480                            info.activityInfo.splitName)) {
7481                // requested activity is defined in a split that hasn't been installed yet.
7482                // add the installer to the resolve list
7483                if (DEBUG_INSTALL) {
7484                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7485                }
7486                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7487                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7488                        info.activityInfo.packageName, info.activityInfo.splitName,
7489                        info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7490                // make sure this resolver is the default
7491                installerInfo.isDefault = true;
7492                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7493                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7494                // add a non-generic filter
7495                installerInfo.filter = new IntentFilter();
7496                // load resources from the correct package
7497                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7498                resolveInfos.set(i, installerInfo);
7499                continue;
7500            }
7501            // caller is a full app, don't need to apply any other filtering
7502            if (ephemeralPkgName == null) {
7503                continue;
7504            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7505                // caller is same app; don't need to apply any other filtering
7506                continue;
7507            }
7508            // allow activities that have been explicitly exposed to ephemeral apps
7509            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7510            if (!isEphemeralApp
7511                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7512                continue;
7513            }
7514            resolveInfos.remove(i);
7515        }
7516        return resolveInfos;
7517    }
7518
7519    /**
7520     * @param resolveInfos list of resolve infos in descending priority order
7521     * @return if the list contains a resolve info with non-negative priority
7522     */
7523    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7524        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7525    }
7526
7527    private static boolean hasWebURI(Intent intent) {
7528        if (intent.getData() == null) {
7529            return false;
7530        }
7531        final String scheme = intent.getScheme();
7532        if (TextUtils.isEmpty(scheme)) {
7533            return false;
7534        }
7535        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7536    }
7537
7538    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7539            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7540            int userId) {
7541        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7542
7543        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7544            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7545                    candidates.size());
7546        }
7547
7548        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7549        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7550        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7551        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7552        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7553        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7554
7555        synchronized (mPackages) {
7556            final int count = candidates.size();
7557            // First, try to use linked apps. Partition the candidates into four lists:
7558            // one for the final results, one for the "do not use ever", one for "undefined status"
7559            // and finally one for "browser app type".
7560            for (int n=0; n<count; n++) {
7561                ResolveInfo info = candidates.get(n);
7562                String packageName = info.activityInfo.packageName;
7563                PackageSetting ps = mSettings.mPackages.get(packageName);
7564                if (ps != null) {
7565                    // Add to the special match all list (Browser use case)
7566                    if (info.handleAllWebDataURI) {
7567                        matchAllList.add(info);
7568                        continue;
7569                    }
7570                    // Try to get the status from User settings first
7571                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7572                    int status = (int)(packedStatus >> 32);
7573                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7574                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7575                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7576                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7577                                    + " : linkgen=" + linkGeneration);
7578                        }
7579                        // Use link-enabled generation as preferredOrder, i.e.
7580                        // prefer newly-enabled over earlier-enabled.
7581                        info.preferredOrder = linkGeneration;
7582                        alwaysList.add(info);
7583                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7584                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7585                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7586                        }
7587                        neverList.add(info);
7588                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7589                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7590                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7591                        }
7592                        alwaysAskList.add(info);
7593                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7594                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7595                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7596                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7597                        }
7598                        undefinedList.add(info);
7599                    }
7600                }
7601            }
7602
7603            // We'll want to include browser possibilities in a few cases
7604            boolean includeBrowser = false;
7605
7606            // First try to add the "always" resolution(s) for the current user, if any
7607            if (alwaysList.size() > 0) {
7608                result.addAll(alwaysList);
7609            } else {
7610                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7611                result.addAll(undefinedList);
7612                // Maybe add one for the other profile.
7613                if (xpDomainInfo != null && (
7614                        xpDomainInfo.bestDomainVerificationStatus
7615                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7616                    result.add(xpDomainInfo.resolveInfo);
7617                }
7618                includeBrowser = true;
7619            }
7620
7621            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7622            // If there were 'always' entries their preferred order has been set, so we also
7623            // back that off to make the alternatives equivalent
7624            if (alwaysAskList.size() > 0) {
7625                for (ResolveInfo i : result) {
7626                    i.preferredOrder = 0;
7627                }
7628                result.addAll(alwaysAskList);
7629                includeBrowser = true;
7630            }
7631
7632            if (includeBrowser) {
7633                // Also add browsers (all of them or only the default one)
7634                if (DEBUG_DOMAIN_VERIFICATION) {
7635                    Slog.v(TAG, "   ...including browsers in candidate set");
7636                }
7637                if ((matchFlags & MATCH_ALL) != 0) {
7638                    result.addAll(matchAllList);
7639                } else {
7640                    // Browser/generic handling case.  If there's a default browser, go straight
7641                    // to that (but only if there is no other higher-priority match).
7642                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7643                    int maxMatchPrio = 0;
7644                    ResolveInfo defaultBrowserMatch = null;
7645                    final int numCandidates = matchAllList.size();
7646                    for (int n = 0; n < numCandidates; n++) {
7647                        ResolveInfo info = matchAllList.get(n);
7648                        // track the highest overall match priority...
7649                        if (info.priority > maxMatchPrio) {
7650                            maxMatchPrio = info.priority;
7651                        }
7652                        // ...and the highest-priority default browser match
7653                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7654                            if (defaultBrowserMatch == null
7655                                    || (defaultBrowserMatch.priority < info.priority)) {
7656                                if (debug) {
7657                                    Slog.v(TAG, "Considering default browser match " + info);
7658                                }
7659                                defaultBrowserMatch = info;
7660                            }
7661                        }
7662                    }
7663                    if (defaultBrowserMatch != null
7664                            && defaultBrowserMatch.priority >= maxMatchPrio
7665                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7666                    {
7667                        if (debug) {
7668                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7669                        }
7670                        result.add(defaultBrowserMatch);
7671                    } else {
7672                        result.addAll(matchAllList);
7673                    }
7674                }
7675
7676                // If there is nothing selected, add all candidates and remove the ones that the user
7677                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7678                if (result.size() == 0) {
7679                    result.addAll(candidates);
7680                    result.removeAll(neverList);
7681                }
7682            }
7683        }
7684        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7685            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7686                    result.size());
7687            for (ResolveInfo info : result) {
7688                Slog.v(TAG, "  + " + info.activityInfo);
7689            }
7690        }
7691        return result;
7692    }
7693
7694    // Returns a packed value as a long:
7695    //
7696    // high 'int'-sized word: link status: undefined/ask/never/always.
7697    // low 'int'-sized word: relative priority among 'always' results.
7698    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7699        long result = ps.getDomainVerificationStatusForUser(userId);
7700        // if none available, get the master status
7701        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7702            if (ps.getIntentFilterVerificationInfo() != null) {
7703                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7704            }
7705        }
7706        return result;
7707    }
7708
7709    private ResolveInfo querySkipCurrentProfileIntents(
7710            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7711            int flags, int sourceUserId) {
7712        if (matchingFilters != null) {
7713            int size = matchingFilters.size();
7714            for (int i = 0; i < size; i ++) {
7715                CrossProfileIntentFilter filter = matchingFilters.get(i);
7716                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7717                    // Checking if there are activities in the target user that can handle the
7718                    // intent.
7719                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7720                            resolvedType, flags, sourceUserId);
7721                    if (resolveInfo != null) {
7722                        return resolveInfo;
7723                    }
7724                }
7725            }
7726        }
7727        return null;
7728    }
7729
7730    // Return matching ResolveInfo in target user if any.
7731    private ResolveInfo queryCrossProfileIntents(
7732            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7733            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7734        if (matchingFilters != null) {
7735            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7736            // match the same intent. For performance reasons, it is better not to
7737            // run queryIntent twice for the same userId
7738            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7739            int size = matchingFilters.size();
7740            for (int i = 0; i < size; i++) {
7741                CrossProfileIntentFilter filter = matchingFilters.get(i);
7742                int targetUserId = filter.getTargetUserId();
7743                boolean skipCurrentProfile =
7744                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7745                boolean skipCurrentProfileIfNoMatchFound =
7746                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7747                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7748                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7749                    // Checking if there are activities in the target user that can handle the
7750                    // intent.
7751                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7752                            resolvedType, flags, sourceUserId);
7753                    if (resolveInfo != null) return resolveInfo;
7754                    alreadyTriedUserIds.put(targetUserId, true);
7755                }
7756            }
7757        }
7758        return null;
7759    }
7760
7761    /**
7762     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7763     * will forward the intent to the filter's target user.
7764     * Otherwise, returns null.
7765     */
7766    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7767            String resolvedType, int flags, int sourceUserId) {
7768        int targetUserId = filter.getTargetUserId();
7769        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7770                resolvedType, flags, targetUserId);
7771        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7772            // If all the matches in the target profile are suspended, return null.
7773            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7774                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7775                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7776                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7777                            targetUserId);
7778                }
7779            }
7780        }
7781        return null;
7782    }
7783
7784    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7785            int sourceUserId, int targetUserId) {
7786        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7787        long ident = Binder.clearCallingIdentity();
7788        boolean targetIsProfile;
7789        try {
7790            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7791        } finally {
7792            Binder.restoreCallingIdentity(ident);
7793        }
7794        String className;
7795        if (targetIsProfile) {
7796            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7797        } else {
7798            className = FORWARD_INTENT_TO_PARENT;
7799        }
7800        ComponentName forwardingActivityComponentName = new ComponentName(
7801                mAndroidApplication.packageName, className);
7802        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7803                sourceUserId);
7804        if (!targetIsProfile) {
7805            forwardingActivityInfo.showUserIcon = targetUserId;
7806            forwardingResolveInfo.noResourceId = true;
7807        }
7808        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7809        forwardingResolveInfo.priority = 0;
7810        forwardingResolveInfo.preferredOrder = 0;
7811        forwardingResolveInfo.match = 0;
7812        forwardingResolveInfo.isDefault = true;
7813        forwardingResolveInfo.filter = filter;
7814        forwardingResolveInfo.targetUserId = targetUserId;
7815        return forwardingResolveInfo;
7816    }
7817
7818    @Override
7819    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7820            Intent[] specifics, String[] specificTypes, Intent intent,
7821            String resolvedType, int flags, int userId) {
7822        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7823                specificTypes, intent, resolvedType, flags, userId));
7824    }
7825
7826    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7827            Intent[] specifics, String[] specificTypes, Intent intent,
7828            String resolvedType, int flags, int userId) {
7829        if (!sUserManager.exists(userId)) return Collections.emptyList();
7830        final int callingUid = Binder.getCallingUid();
7831        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7832                false /*includeInstantApps*/);
7833        enforceCrossUserPermission(callingUid, userId,
7834                false /*requireFullPermission*/, false /*checkShell*/,
7835                "query intent activity options");
7836        final String resultsAction = intent.getAction();
7837
7838        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7839                | PackageManager.GET_RESOLVED_FILTER, userId);
7840
7841        if (DEBUG_INTENT_MATCHING) {
7842            Log.v(TAG, "Query " + intent + ": " + results);
7843        }
7844
7845        int specificsPos = 0;
7846        int N;
7847
7848        // todo: note that the algorithm used here is O(N^2).  This
7849        // isn't a problem in our current environment, but if we start running
7850        // into situations where we have more than 5 or 10 matches then this
7851        // should probably be changed to something smarter...
7852
7853        // First we go through and resolve each of the specific items
7854        // that were supplied, taking care of removing any corresponding
7855        // duplicate items in the generic resolve list.
7856        if (specifics != null) {
7857            for (int i=0; i<specifics.length; i++) {
7858                final Intent sintent = specifics[i];
7859                if (sintent == null) {
7860                    continue;
7861                }
7862
7863                if (DEBUG_INTENT_MATCHING) {
7864                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7865                }
7866
7867                String action = sintent.getAction();
7868                if (resultsAction != null && resultsAction.equals(action)) {
7869                    // If this action was explicitly requested, then don't
7870                    // remove things that have it.
7871                    action = null;
7872                }
7873
7874                ResolveInfo ri = null;
7875                ActivityInfo ai = null;
7876
7877                ComponentName comp = sintent.getComponent();
7878                if (comp == null) {
7879                    ri = resolveIntent(
7880                        sintent,
7881                        specificTypes != null ? specificTypes[i] : null,
7882                            flags, userId);
7883                    if (ri == null) {
7884                        continue;
7885                    }
7886                    if (ri == mResolveInfo) {
7887                        // ACK!  Must do something better with this.
7888                    }
7889                    ai = ri.activityInfo;
7890                    comp = new ComponentName(ai.applicationInfo.packageName,
7891                            ai.name);
7892                } else {
7893                    ai = getActivityInfo(comp, flags, userId);
7894                    if (ai == null) {
7895                        continue;
7896                    }
7897                }
7898
7899                // Look for any generic query activities that are duplicates
7900                // of this specific one, and remove them from the results.
7901                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7902                N = results.size();
7903                int j;
7904                for (j=specificsPos; j<N; j++) {
7905                    ResolveInfo sri = results.get(j);
7906                    if ((sri.activityInfo.name.equals(comp.getClassName())
7907                            && sri.activityInfo.applicationInfo.packageName.equals(
7908                                    comp.getPackageName()))
7909                        || (action != null && sri.filter.matchAction(action))) {
7910                        results.remove(j);
7911                        if (DEBUG_INTENT_MATCHING) Log.v(
7912                            TAG, "Removing duplicate item from " + j
7913                            + " due to specific " + specificsPos);
7914                        if (ri == null) {
7915                            ri = sri;
7916                        }
7917                        j--;
7918                        N--;
7919                    }
7920                }
7921
7922                // Add this specific item to its proper place.
7923                if (ri == null) {
7924                    ri = new ResolveInfo();
7925                    ri.activityInfo = ai;
7926                }
7927                results.add(specificsPos, ri);
7928                ri.specificIndex = i;
7929                specificsPos++;
7930            }
7931        }
7932
7933        // Now we go through the remaining generic results and remove any
7934        // duplicate actions that are found here.
7935        N = results.size();
7936        for (int i=specificsPos; i<N-1; i++) {
7937            final ResolveInfo rii = results.get(i);
7938            if (rii.filter == null) {
7939                continue;
7940            }
7941
7942            // Iterate over all of the actions of this result's intent
7943            // filter...  typically this should be just one.
7944            final Iterator<String> it = rii.filter.actionsIterator();
7945            if (it == null) {
7946                continue;
7947            }
7948            while (it.hasNext()) {
7949                final String action = it.next();
7950                if (resultsAction != null && resultsAction.equals(action)) {
7951                    // If this action was explicitly requested, then don't
7952                    // remove things that have it.
7953                    continue;
7954                }
7955                for (int j=i+1; j<N; j++) {
7956                    final ResolveInfo rij = results.get(j);
7957                    if (rij.filter != null && rij.filter.hasAction(action)) {
7958                        results.remove(j);
7959                        if (DEBUG_INTENT_MATCHING) Log.v(
7960                            TAG, "Removing duplicate item from " + j
7961                            + " due to action " + action + " at " + i);
7962                        j--;
7963                        N--;
7964                    }
7965                }
7966            }
7967
7968            // If the caller didn't request filter information, drop it now
7969            // so we don't have to marshall/unmarshall it.
7970            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7971                rii.filter = null;
7972            }
7973        }
7974
7975        // Filter out the caller activity if so requested.
7976        if (caller != null) {
7977            N = results.size();
7978            for (int i=0; i<N; i++) {
7979                ActivityInfo ainfo = results.get(i).activityInfo;
7980                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7981                        && caller.getClassName().equals(ainfo.name)) {
7982                    results.remove(i);
7983                    break;
7984                }
7985            }
7986        }
7987
7988        // If the caller didn't request filter information,
7989        // drop them now so we don't have to
7990        // marshall/unmarshall it.
7991        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7992            N = results.size();
7993            for (int i=0; i<N; i++) {
7994                results.get(i).filter = null;
7995            }
7996        }
7997
7998        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7999        return results;
8000    }
8001
8002    @Override
8003    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8004            String resolvedType, int flags, int userId) {
8005        return new ParceledListSlice<>(
8006                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
8007    }
8008
8009    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8010            String resolvedType, int flags, int userId) {
8011        if (!sUserManager.exists(userId)) return Collections.emptyList();
8012        final int callingUid = Binder.getCallingUid();
8013        enforceCrossUserPermission(callingUid, userId,
8014                false /*requireFullPermission*/, false /*checkShell*/,
8015                "query intent receivers");
8016        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8017        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8018                false /*includeInstantApps*/);
8019        ComponentName comp = intent.getComponent();
8020        if (comp == null) {
8021            if (intent.getSelector() != null) {
8022                intent = intent.getSelector();
8023                comp = intent.getComponent();
8024            }
8025        }
8026        if (comp != null) {
8027            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8028            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8029            if (ai != null) {
8030                // When specifying an explicit component, we prevent the activity from being
8031                // used when either 1) the calling package is normal and the activity is within
8032                // an instant application or 2) the calling package is ephemeral and the
8033                // activity is not visible to instant applications.
8034                final boolean matchInstantApp =
8035                        (flags & PackageManager.MATCH_INSTANT) != 0;
8036                final boolean matchVisibleToInstantAppOnly =
8037                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8038                final boolean matchExplicitlyVisibleOnly =
8039                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8040                final boolean isCallerInstantApp =
8041                        instantAppPkgName != null;
8042                final boolean isTargetSameInstantApp =
8043                        comp.getPackageName().equals(instantAppPkgName);
8044                final boolean isTargetInstantApp =
8045                        (ai.applicationInfo.privateFlags
8046                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8047                final boolean isTargetVisibleToInstantApp =
8048                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8049                final boolean isTargetExplicitlyVisibleToInstantApp =
8050                        isTargetVisibleToInstantApp
8051                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8052                final boolean isTargetHiddenFromInstantApp =
8053                        !isTargetVisibleToInstantApp
8054                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8055                final boolean blockResolution =
8056                        !isTargetSameInstantApp
8057                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8058                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8059                                        && isTargetHiddenFromInstantApp));
8060                if (!blockResolution) {
8061                    ResolveInfo ri = new ResolveInfo();
8062                    ri.activityInfo = ai;
8063                    list.add(ri);
8064                }
8065            }
8066            return applyPostResolutionFilter(list, instantAppPkgName);
8067        }
8068
8069        // reader
8070        synchronized (mPackages) {
8071            String pkgName = intent.getPackage();
8072            if (pkgName == null) {
8073                final List<ResolveInfo> result =
8074                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8075                return applyPostResolutionFilter(result, instantAppPkgName);
8076            }
8077            final PackageParser.Package pkg = mPackages.get(pkgName);
8078            if (pkg != null) {
8079                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8080                        intent, resolvedType, flags, pkg.receivers, userId);
8081                return applyPostResolutionFilter(result, instantAppPkgName);
8082            }
8083            return Collections.emptyList();
8084        }
8085    }
8086
8087    @Override
8088    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8089        final int callingUid = Binder.getCallingUid();
8090        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8091    }
8092
8093    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8094            int userId, int callingUid) {
8095        if (!sUserManager.exists(userId)) return null;
8096        flags = updateFlagsForResolve(
8097                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8098        List<ResolveInfo> query = queryIntentServicesInternal(
8099                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8100        if (query != null) {
8101            if (query.size() >= 1) {
8102                // If there is more than one service with the same priority,
8103                // just arbitrarily pick the first one.
8104                return query.get(0);
8105            }
8106        }
8107        return null;
8108    }
8109
8110    @Override
8111    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8112            String resolvedType, int flags, int userId) {
8113        final int callingUid = Binder.getCallingUid();
8114        return new ParceledListSlice<>(queryIntentServicesInternal(
8115                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8116    }
8117
8118    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8119            String resolvedType, int flags, int userId, int callingUid,
8120            boolean includeInstantApps) {
8121        if (!sUserManager.exists(userId)) return Collections.emptyList();
8122        enforceCrossUserPermission(callingUid, userId,
8123                false /*requireFullPermission*/, false /*checkShell*/,
8124                "query intent receivers");
8125        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8126        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8127        ComponentName comp = intent.getComponent();
8128        if (comp == null) {
8129            if (intent.getSelector() != null) {
8130                intent = intent.getSelector();
8131                comp = intent.getComponent();
8132            }
8133        }
8134        if (comp != null) {
8135            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8136            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8137            if (si != null) {
8138                // When specifying an explicit component, we prevent the service from being
8139                // used when either 1) the service is in an instant application and the
8140                // caller is not the same instant application or 2) the calling package is
8141                // ephemeral and the activity is not visible to ephemeral applications.
8142                final boolean matchInstantApp =
8143                        (flags & PackageManager.MATCH_INSTANT) != 0;
8144                final boolean matchVisibleToInstantAppOnly =
8145                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8146                final boolean isCallerInstantApp =
8147                        instantAppPkgName != null;
8148                final boolean isTargetSameInstantApp =
8149                        comp.getPackageName().equals(instantAppPkgName);
8150                final boolean isTargetInstantApp =
8151                        (si.applicationInfo.privateFlags
8152                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8153                final boolean isTargetHiddenFromInstantApp =
8154                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8155                final boolean blockResolution =
8156                        !isTargetSameInstantApp
8157                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8158                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8159                                        && isTargetHiddenFromInstantApp));
8160                if (!blockResolution) {
8161                    final ResolveInfo ri = new ResolveInfo();
8162                    ri.serviceInfo = si;
8163                    list.add(ri);
8164                }
8165            }
8166            return list;
8167        }
8168
8169        // reader
8170        synchronized (mPackages) {
8171            String pkgName = intent.getPackage();
8172            if (pkgName == null) {
8173                return applyPostServiceResolutionFilter(
8174                        mServices.queryIntent(intent, resolvedType, flags, userId),
8175                        instantAppPkgName);
8176            }
8177            final PackageParser.Package pkg = mPackages.get(pkgName);
8178            if (pkg != null) {
8179                return applyPostServiceResolutionFilter(
8180                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8181                                userId),
8182                        instantAppPkgName);
8183            }
8184            return Collections.emptyList();
8185        }
8186    }
8187
8188    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8189            String instantAppPkgName) {
8190        // TODO: When adding on-demand split support for non-instant apps, remove this check
8191        // and always apply post filtering
8192        if (instantAppPkgName == null) {
8193            return resolveInfos;
8194        }
8195        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8196            final ResolveInfo info = resolveInfos.get(i);
8197            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8198            // allow services that are defined in the provided package
8199            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8200                if (info.serviceInfo.splitName != null
8201                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8202                                info.serviceInfo.splitName)) {
8203                    // requested service is defined in a split that hasn't been installed yet.
8204                    // add the installer to the resolve list
8205                    if (DEBUG_EPHEMERAL) {
8206                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8207                    }
8208                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8209                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8210                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8211                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
8212                    // make sure this resolver is the default
8213                    installerInfo.isDefault = true;
8214                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8215                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8216                    // add a non-generic filter
8217                    installerInfo.filter = new IntentFilter();
8218                    // load resources from the correct package
8219                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8220                    resolveInfos.set(i, installerInfo);
8221                }
8222                continue;
8223            }
8224            // allow services that have been explicitly exposed to ephemeral apps
8225            if (!isEphemeralApp
8226                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8227                continue;
8228            }
8229            resolveInfos.remove(i);
8230        }
8231        return resolveInfos;
8232    }
8233
8234    @Override
8235    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8236            String resolvedType, int flags, int userId) {
8237        return new ParceledListSlice<>(
8238                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8239    }
8240
8241    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8242            Intent intent, String resolvedType, int flags, int userId) {
8243        if (!sUserManager.exists(userId)) return Collections.emptyList();
8244        final int callingUid = Binder.getCallingUid();
8245        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8246        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8247                false /*includeInstantApps*/);
8248        ComponentName comp = intent.getComponent();
8249        if (comp == null) {
8250            if (intent.getSelector() != null) {
8251                intent = intent.getSelector();
8252                comp = intent.getComponent();
8253            }
8254        }
8255        if (comp != null) {
8256            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8257            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8258            if (pi != null) {
8259                // When specifying an explicit component, we prevent the provider from being
8260                // used when either 1) the provider is in an instant application and the
8261                // caller is not the same instant application or 2) the calling package is an
8262                // instant application and the provider is not visible to instant applications.
8263                final boolean matchInstantApp =
8264                        (flags & PackageManager.MATCH_INSTANT) != 0;
8265                final boolean matchVisibleToInstantAppOnly =
8266                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8267                final boolean isCallerInstantApp =
8268                        instantAppPkgName != null;
8269                final boolean isTargetSameInstantApp =
8270                        comp.getPackageName().equals(instantAppPkgName);
8271                final boolean isTargetInstantApp =
8272                        (pi.applicationInfo.privateFlags
8273                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8274                final boolean isTargetHiddenFromInstantApp =
8275                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8276                final boolean blockResolution =
8277                        !isTargetSameInstantApp
8278                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8279                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8280                                        && isTargetHiddenFromInstantApp));
8281                if (!blockResolution) {
8282                    final ResolveInfo ri = new ResolveInfo();
8283                    ri.providerInfo = pi;
8284                    list.add(ri);
8285                }
8286            }
8287            return list;
8288        }
8289
8290        // reader
8291        synchronized (mPackages) {
8292            String pkgName = intent.getPackage();
8293            if (pkgName == null) {
8294                return applyPostContentProviderResolutionFilter(
8295                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8296                        instantAppPkgName);
8297            }
8298            final PackageParser.Package pkg = mPackages.get(pkgName);
8299            if (pkg != null) {
8300                return applyPostContentProviderResolutionFilter(
8301                        mProviders.queryIntentForPackage(
8302                        intent, resolvedType, flags, pkg.providers, userId),
8303                        instantAppPkgName);
8304            }
8305            return Collections.emptyList();
8306        }
8307    }
8308
8309    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8310            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8311        // TODO: When adding on-demand split support for non-instant applications, remove
8312        // this check and always apply post filtering
8313        if (instantAppPkgName == null) {
8314            return resolveInfos;
8315        }
8316        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8317            final ResolveInfo info = resolveInfos.get(i);
8318            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8319            // allow providers that are defined in the provided package
8320            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8321                if (info.providerInfo.splitName != null
8322                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8323                                info.providerInfo.splitName)) {
8324                    // requested provider is defined in a split that hasn't been installed yet.
8325                    // add the installer to the resolve list
8326                    if (DEBUG_EPHEMERAL) {
8327                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8328                    }
8329                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8330                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8331                            info.providerInfo.packageName, info.providerInfo.splitName,
8332                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8333                    // make sure this resolver is the default
8334                    installerInfo.isDefault = true;
8335                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8336                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8337                    // add a non-generic filter
8338                    installerInfo.filter = new IntentFilter();
8339                    // load resources from the correct package
8340                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8341                    resolveInfos.set(i, installerInfo);
8342                }
8343                continue;
8344            }
8345            // allow providers that have been explicitly exposed to instant applications
8346            if (!isEphemeralApp
8347                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8348                continue;
8349            }
8350            resolveInfos.remove(i);
8351        }
8352        return resolveInfos;
8353    }
8354
8355    @Override
8356    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8357        final int callingUid = Binder.getCallingUid();
8358        if (getInstantAppPackageName(callingUid) != null) {
8359            return ParceledListSlice.emptyList();
8360        }
8361        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8362        flags = updateFlagsForPackage(flags, userId, null);
8363        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8364        enforceCrossUserPermission(callingUid, userId,
8365                true /* requireFullPermission */, false /* checkShell */,
8366                "get installed packages");
8367
8368        // writer
8369        synchronized (mPackages) {
8370            ArrayList<PackageInfo> list;
8371            if (listUninstalled) {
8372                list = new ArrayList<>(mSettings.mPackages.size());
8373                for (PackageSetting ps : mSettings.mPackages.values()) {
8374                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8375                        continue;
8376                    }
8377                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8378                        return null;
8379                    }
8380                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8381                    if (pi != null) {
8382                        list.add(pi);
8383                    }
8384                }
8385            } else {
8386                list = new ArrayList<>(mPackages.size());
8387                for (PackageParser.Package p : mPackages.values()) {
8388                    final PackageSetting ps = (PackageSetting) p.mExtras;
8389                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8390                        continue;
8391                    }
8392                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8393                        return null;
8394                    }
8395                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8396                            p.mExtras, flags, userId);
8397                    if (pi != null) {
8398                        list.add(pi);
8399                    }
8400                }
8401            }
8402
8403            return new ParceledListSlice<>(list);
8404        }
8405    }
8406
8407    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8408            String[] permissions, boolean[] tmp, int flags, int userId) {
8409        int numMatch = 0;
8410        final PermissionsState permissionsState = ps.getPermissionsState();
8411        for (int i=0; i<permissions.length; i++) {
8412            final String permission = permissions[i];
8413            if (permissionsState.hasPermission(permission, userId)) {
8414                tmp[i] = true;
8415                numMatch++;
8416            } else {
8417                tmp[i] = false;
8418            }
8419        }
8420        if (numMatch == 0) {
8421            return;
8422        }
8423        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8424
8425        // The above might return null in cases of uninstalled apps or install-state
8426        // skew across users/profiles.
8427        if (pi != null) {
8428            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8429                if (numMatch == permissions.length) {
8430                    pi.requestedPermissions = permissions;
8431                } else {
8432                    pi.requestedPermissions = new String[numMatch];
8433                    numMatch = 0;
8434                    for (int i=0; i<permissions.length; i++) {
8435                        if (tmp[i]) {
8436                            pi.requestedPermissions[numMatch] = permissions[i];
8437                            numMatch++;
8438                        }
8439                    }
8440                }
8441            }
8442            list.add(pi);
8443        }
8444    }
8445
8446    @Override
8447    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8448            String[] permissions, int flags, int userId) {
8449        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8450        flags = updateFlagsForPackage(flags, userId, permissions);
8451        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8452                true /* requireFullPermission */, false /* checkShell */,
8453                "get packages holding permissions");
8454        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8455
8456        // writer
8457        synchronized (mPackages) {
8458            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8459            boolean[] tmpBools = new boolean[permissions.length];
8460            if (listUninstalled) {
8461                for (PackageSetting ps : mSettings.mPackages.values()) {
8462                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8463                            userId);
8464                }
8465            } else {
8466                for (PackageParser.Package pkg : mPackages.values()) {
8467                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8468                    if (ps != null) {
8469                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8470                                userId);
8471                    }
8472                }
8473            }
8474
8475            return new ParceledListSlice<PackageInfo>(list);
8476        }
8477    }
8478
8479    @Override
8480    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8481        final int callingUid = Binder.getCallingUid();
8482        if (getInstantAppPackageName(callingUid) != null) {
8483            return ParceledListSlice.emptyList();
8484        }
8485        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8486        flags = updateFlagsForApplication(flags, userId, null);
8487        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8488
8489        // writer
8490        synchronized (mPackages) {
8491            ArrayList<ApplicationInfo> list;
8492            if (listUninstalled) {
8493                list = new ArrayList<>(mSettings.mPackages.size());
8494                for (PackageSetting ps : mSettings.mPackages.values()) {
8495                    ApplicationInfo ai;
8496                    int effectiveFlags = flags;
8497                    if (ps.isSystem()) {
8498                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8499                    }
8500                    if (ps.pkg != null) {
8501                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8502                            continue;
8503                        }
8504                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8505                            return null;
8506                        }
8507                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8508                                ps.readUserState(userId), userId);
8509                        if (ai != null) {
8510                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8511                        }
8512                    } else {
8513                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8514                        // and already converts to externally visible package name
8515                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8516                                callingUid, effectiveFlags, userId);
8517                    }
8518                    if (ai != null) {
8519                        list.add(ai);
8520                    }
8521                }
8522            } else {
8523                list = new ArrayList<>(mPackages.size());
8524                for (PackageParser.Package p : mPackages.values()) {
8525                    if (p.mExtras != null) {
8526                        PackageSetting ps = (PackageSetting) p.mExtras;
8527                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8528                            continue;
8529                        }
8530                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8531                            return null;
8532                        }
8533                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8534                                ps.readUserState(userId), userId);
8535                        if (ai != null) {
8536                            ai.packageName = resolveExternalPackageNameLPr(p);
8537                            list.add(ai);
8538                        }
8539                    }
8540                }
8541            }
8542
8543            return new ParceledListSlice<>(list);
8544        }
8545    }
8546
8547    @Override
8548    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8549        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8550            return null;
8551        }
8552        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8553            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8554                    "getEphemeralApplications");
8555        }
8556        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8557                true /* requireFullPermission */, false /* checkShell */,
8558                "getEphemeralApplications");
8559        synchronized (mPackages) {
8560            List<InstantAppInfo> instantApps = mInstantAppRegistry
8561                    .getInstantAppsLPr(userId);
8562            if (instantApps != null) {
8563                return new ParceledListSlice<>(instantApps);
8564            }
8565        }
8566        return null;
8567    }
8568
8569    @Override
8570    public boolean isInstantApp(String packageName, int userId) {
8571        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8572                true /* requireFullPermission */, false /* checkShell */,
8573                "isInstantApp");
8574        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8575            return false;
8576        }
8577
8578        synchronized (mPackages) {
8579            int callingUid = Binder.getCallingUid();
8580            if (Process.isIsolated(callingUid)) {
8581                callingUid = mIsolatedOwners.get(callingUid);
8582            }
8583            final PackageSetting ps = mSettings.mPackages.get(packageName);
8584            PackageParser.Package pkg = mPackages.get(packageName);
8585            final boolean returnAllowed =
8586                    ps != null
8587                    && (isCallerSameApp(packageName, callingUid)
8588                            || canViewInstantApps(callingUid, userId)
8589                            || mInstantAppRegistry.isInstantAccessGranted(
8590                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8591            if (returnAllowed) {
8592                return ps.getInstantApp(userId);
8593            }
8594        }
8595        return false;
8596    }
8597
8598    @Override
8599    public byte[] getInstantAppCookie(String packageName, int userId) {
8600        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8601            return null;
8602        }
8603
8604        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8605                true /* requireFullPermission */, false /* checkShell */,
8606                "getInstantAppCookie");
8607        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8608            return null;
8609        }
8610        synchronized (mPackages) {
8611            return mInstantAppRegistry.getInstantAppCookieLPw(
8612                    packageName, userId);
8613        }
8614    }
8615
8616    @Override
8617    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8618        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8619            return true;
8620        }
8621
8622        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8623                true /* requireFullPermission */, true /* checkShell */,
8624                "setInstantAppCookie");
8625        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8626            return false;
8627        }
8628        synchronized (mPackages) {
8629            return mInstantAppRegistry.setInstantAppCookieLPw(
8630                    packageName, cookie, userId);
8631        }
8632    }
8633
8634    @Override
8635    public Bitmap getInstantAppIcon(String packageName, int userId) {
8636        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8637            return null;
8638        }
8639
8640        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8641            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8642                    "getInstantAppIcon");
8643        }
8644        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8645                true /* requireFullPermission */, false /* checkShell */,
8646                "getInstantAppIcon");
8647
8648        synchronized (mPackages) {
8649            return mInstantAppRegistry.getInstantAppIconLPw(
8650                    packageName, userId);
8651        }
8652    }
8653
8654    private boolean isCallerSameApp(String packageName, int uid) {
8655        PackageParser.Package pkg = mPackages.get(packageName);
8656        return pkg != null
8657                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8658    }
8659
8660    @Override
8661    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8662        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8663            return ParceledListSlice.emptyList();
8664        }
8665        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8666    }
8667
8668    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8669        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8670
8671        // reader
8672        synchronized (mPackages) {
8673            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8674            final int userId = UserHandle.getCallingUserId();
8675            while (i.hasNext()) {
8676                final PackageParser.Package p = i.next();
8677                if (p.applicationInfo == null) continue;
8678
8679                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8680                        && !p.applicationInfo.isDirectBootAware();
8681                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8682                        && p.applicationInfo.isDirectBootAware();
8683
8684                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8685                        && (!mSafeMode || isSystemApp(p))
8686                        && (matchesUnaware || matchesAware)) {
8687                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8688                    if (ps != null) {
8689                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8690                                ps.readUserState(userId), userId);
8691                        if (ai != null) {
8692                            finalList.add(ai);
8693                        }
8694                    }
8695                }
8696            }
8697        }
8698
8699        return finalList;
8700    }
8701
8702    @Override
8703    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8704        if (!sUserManager.exists(userId)) return null;
8705        flags = updateFlagsForComponent(flags, userId, name);
8706        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8707        // reader
8708        synchronized (mPackages) {
8709            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8710            PackageSetting ps = provider != null
8711                    ? mSettings.mPackages.get(provider.owner.packageName)
8712                    : null;
8713            if (ps != null) {
8714                final boolean isInstantApp = ps.getInstantApp(userId);
8715                // normal application; filter out instant application provider
8716                if (instantAppPkgName == null && isInstantApp) {
8717                    return null;
8718                }
8719                // instant application; filter out other instant applications
8720                if (instantAppPkgName != null
8721                        && isInstantApp
8722                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8723                    return null;
8724                }
8725                // instant application; filter out non-exposed provider
8726                if (instantAppPkgName != null
8727                        && !isInstantApp
8728                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8729                    return null;
8730                }
8731                // provider not enabled
8732                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8733                    return null;
8734                }
8735                return PackageParser.generateProviderInfo(
8736                        provider, flags, ps.readUserState(userId), userId);
8737            }
8738            return null;
8739        }
8740    }
8741
8742    /**
8743     * @deprecated
8744     */
8745    @Deprecated
8746    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8747        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8748            return;
8749        }
8750        // reader
8751        synchronized (mPackages) {
8752            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8753                    .entrySet().iterator();
8754            final int userId = UserHandle.getCallingUserId();
8755            while (i.hasNext()) {
8756                Map.Entry<String, PackageParser.Provider> entry = i.next();
8757                PackageParser.Provider p = entry.getValue();
8758                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8759
8760                if (ps != null && p.syncable
8761                        && (!mSafeMode || (p.info.applicationInfo.flags
8762                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8763                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8764                            ps.readUserState(userId), userId);
8765                    if (info != null) {
8766                        outNames.add(entry.getKey());
8767                        outInfo.add(info);
8768                    }
8769                }
8770            }
8771        }
8772    }
8773
8774    @Override
8775    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8776            int uid, int flags, String metaDataKey) {
8777        final int callingUid = Binder.getCallingUid();
8778        final int userId = processName != null ? UserHandle.getUserId(uid)
8779                : UserHandle.getCallingUserId();
8780        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8781        flags = updateFlagsForComponent(flags, userId, processName);
8782        ArrayList<ProviderInfo> finalList = null;
8783        // reader
8784        synchronized (mPackages) {
8785            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8786            while (i.hasNext()) {
8787                final PackageParser.Provider p = i.next();
8788                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8789                if (ps != null && p.info.authority != null
8790                        && (processName == null
8791                                || (p.info.processName.equals(processName)
8792                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8793                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8794
8795                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8796                    // parameter.
8797                    if (metaDataKey != null
8798                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8799                        continue;
8800                    }
8801                    final ComponentName component =
8802                            new ComponentName(p.info.packageName, p.info.name);
8803                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8804                        continue;
8805                    }
8806                    if (finalList == null) {
8807                        finalList = new ArrayList<ProviderInfo>(3);
8808                    }
8809                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8810                            ps.readUserState(userId), userId);
8811                    if (info != null) {
8812                        finalList.add(info);
8813                    }
8814                }
8815            }
8816        }
8817
8818        if (finalList != null) {
8819            Collections.sort(finalList, mProviderInitOrderSorter);
8820            return new ParceledListSlice<ProviderInfo>(finalList);
8821        }
8822
8823        return ParceledListSlice.emptyList();
8824    }
8825
8826    @Override
8827    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8828        // reader
8829        synchronized (mPackages) {
8830            final int callingUid = Binder.getCallingUid();
8831            final int callingUserId = UserHandle.getUserId(callingUid);
8832            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8833            if (ps == null) return null;
8834            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8835                return null;
8836            }
8837            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8838            return PackageParser.generateInstrumentationInfo(i, flags);
8839        }
8840    }
8841
8842    @Override
8843    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8844            String targetPackage, int flags) {
8845        final int callingUid = Binder.getCallingUid();
8846        final int callingUserId = UserHandle.getUserId(callingUid);
8847        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8848        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8849            return ParceledListSlice.emptyList();
8850        }
8851        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8852    }
8853
8854    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8855            int flags) {
8856        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8857
8858        // reader
8859        synchronized (mPackages) {
8860            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8861            while (i.hasNext()) {
8862                final PackageParser.Instrumentation p = i.next();
8863                if (targetPackage == null
8864                        || targetPackage.equals(p.info.targetPackage)) {
8865                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8866                            flags);
8867                    if (ii != null) {
8868                        finalList.add(ii);
8869                    }
8870                }
8871            }
8872        }
8873
8874        return finalList;
8875    }
8876
8877    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8878        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8879        try {
8880            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8881        } finally {
8882            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8883        }
8884    }
8885
8886    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8887        final File[] files = dir.listFiles();
8888        if (ArrayUtils.isEmpty(files)) {
8889            Log.d(TAG, "No files in app dir " + dir);
8890            return;
8891        }
8892
8893        if (DEBUG_PACKAGE_SCANNING) {
8894            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8895                    + " flags=0x" + Integer.toHexString(parseFlags));
8896        }
8897        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8898                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8899                mParallelPackageParserCallback);
8900
8901        // Submit files for parsing in parallel
8902        int fileCount = 0;
8903        for (File file : files) {
8904            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8905                    && !PackageInstallerService.isStageName(file.getName());
8906            if (!isPackage) {
8907                // Ignore entries which are not packages
8908                continue;
8909            }
8910            parallelPackageParser.submit(file, parseFlags);
8911            fileCount++;
8912        }
8913
8914        // Process results one by one
8915        for (; fileCount > 0; fileCount--) {
8916            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8917            Throwable throwable = parseResult.throwable;
8918            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8919
8920            if (throwable == null) {
8921                // Static shared libraries have synthetic package names
8922                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8923                    renameStaticSharedLibraryPackage(parseResult.pkg);
8924                }
8925                try {
8926                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8927                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8928                                currentTime, null);
8929                    }
8930                } catch (PackageManagerException e) {
8931                    errorCode = e.error;
8932                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8933                }
8934            } else if (throwable instanceof PackageParser.PackageParserException) {
8935                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8936                        throwable;
8937                errorCode = e.error;
8938                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8939            } else {
8940                throw new IllegalStateException("Unexpected exception occurred while parsing "
8941                        + parseResult.scanFile, throwable);
8942            }
8943
8944            // Delete invalid userdata apps
8945            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8946                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8947                logCriticalInfo(Log.WARN,
8948                        "Deleting invalid package at " + parseResult.scanFile);
8949                removeCodePathLI(parseResult.scanFile);
8950            }
8951        }
8952        parallelPackageParser.close();
8953    }
8954
8955    private static File getSettingsProblemFile() {
8956        File dataDir = Environment.getDataDirectory();
8957        File systemDir = new File(dataDir, "system");
8958        File fname = new File(systemDir, "uiderrors.txt");
8959        return fname;
8960    }
8961
8962    static void reportSettingsProblem(int priority, String msg) {
8963        logCriticalInfo(priority, msg);
8964    }
8965
8966    public static void logCriticalInfo(int priority, String msg) {
8967        Slog.println(priority, TAG, msg);
8968        EventLogTags.writePmCriticalInfo(msg);
8969        try {
8970            File fname = getSettingsProblemFile();
8971            FileOutputStream out = new FileOutputStream(fname, true);
8972            PrintWriter pw = new FastPrintWriter(out);
8973            SimpleDateFormat formatter = new SimpleDateFormat();
8974            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8975            pw.println(dateString + ": " + msg);
8976            pw.close();
8977            FileUtils.setPermissions(
8978                    fname.toString(),
8979                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8980                    -1, -1);
8981        } catch (java.io.IOException e) {
8982        }
8983    }
8984
8985    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8986        if (srcFile.isDirectory()) {
8987            final File baseFile = new File(pkg.baseCodePath);
8988            long maxModifiedTime = baseFile.lastModified();
8989            if (pkg.splitCodePaths != null) {
8990                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8991                    final File splitFile = new File(pkg.splitCodePaths[i]);
8992                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8993                }
8994            }
8995            return maxModifiedTime;
8996        }
8997        return srcFile.lastModified();
8998    }
8999
9000    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9001            final int policyFlags) throws PackageManagerException {
9002        // When upgrading from pre-N MR1, verify the package time stamp using the package
9003        // directory and not the APK file.
9004        final long lastModifiedTime = mIsPreNMR1Upgrade
9005                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9006        if (ps != null
9007                && ps.codePath.equals(srcFile)
9008                && ps.timeStamp == lastModifiedTime
9009                && !isCompatSignatureUpdateNeeded(pkg)
9010                && !isRecoverSignatureUpdateNeeded(pkg)) {
9011            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9012            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9013            ArraySet<PublicKey> signingKs;
9014            synchronized (mPackages) {
9015                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9016            }
9017            if (ps.signatures.mSignatures != null
9018                    && ps.signatures.mSignatures.length != 0
9019                    && signingKs != null) {
9020                // Optimization: reuse the existing cached certificates
9021                // if the package appears to be unchanged.
9022                pkg.mSignatures = ps.signatures.mSignatures;
9023                pkg.mSigningKeys = signingKs;
9024                return;
9025            }
9026
9027            Slog.w(TAG, "PackageSetting for " + ps.name
9028                    + " is missing signatures.  Collecting certs again to recover them.");
9029        } else {
9030            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9031        }
9032
9033        try {
9034            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9035            PackageParser.collectCertificates(pkg, policyFlags);
9036        } catch (PackageParserException e) {
9037            throw PackageManagerException.from(e);
9038        } finally {
9039            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9040        }
9041    }
9042
9043    /**
9044     *  Traces a package scan.
9045     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9046     */
9047    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9048            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9049        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9050        try {
9051            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9052        } finally {
9053            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9054        }
9055    }
9056
9057    /**
9058     *  Scans a package and returns the newly parsed package.
9059     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9060     */
9061    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9062            long currentTime, UserHandle user) throws PackageManagerException {
9063        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9064        PackageParser pp = new PackageParser();
9065        pp.setSeparateProcesses(mSeparateProcesses);
9066        pp.setOnlyCoreApps(mOnlyCore);
9067        pp.setDisplayMetrics(mMetrics);
9068        pp.setCallback(mPackageParserCallback);
9069
9070        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9071            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9072        }
9073
9074        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9075        final PackageParser.Package pkg;
9076        try {
9077            pkg = pp.parsePackage(scanFile, parseFlags);
9078        } catch (PackageParserException e) {
9079            throw PackageManagerException.from(e);
9080        } finally {
9081            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9082        }
9083
9084        // Static shared libraries have synthetic package names
9085        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9086            renameStaticSharedLibraryPackage(pkg);
9087        }
9088
9089        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9090    }
9091
9092    /**
9093     *  Scans a package and returns the newly parsed package.
9094     *  @throws PackageManagerException on a parse error.
9095     */
9096    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9097            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9098            throws PackageManagerException {
9099        // If the package has children and this is the first dive in the function
9100        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9101        // packages (parent and children) would be successfully scanned before the
9102        // actual scan since scanning mutates internal state and we want to atomically
9103        // install the package and its children.
9104        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9105            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9106                scanFlags |= SCAN_CHECK_ONLY;
9107            }
9108        } else {
9109            scanFlags &= ~SCAN_CHECK_ONLY;
9110        }
9111
9112        // Scan the parent
9113        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9114                scanFlags, currentTime, user);
9115
9116        // Scan the children
9117        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9118        for (int i = 0; i < childCount; i++) {
9119            PackageParser.Package childPackage = pkg.childPackages.get(i);
9120            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9121                    currentTime, user);
9122        }
9123
9124
9125        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9126            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9127        }
9128
9129        return scannedPkg;
9130    }
9131
9132    /**
9133     *  Scans a package and returns the newly parsed package.
9134     *  @throws PackageManagerException on a parse error.
9135     */
9136    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9137            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9138            throws PackageManagerException {
9139        PackageSetting ps = null;
9140        PackageSetting updatedPkg;
9141        // reader
9142        synchronized (mPackages) {
9143            // Look to see if we already know about this package.
9144            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9145            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9146                // This package has been renamed to its original name.  Let's
9147                // use that.
9148                ps = mSettings.getPackageLPr(oldName);
9149            }
9150            // If there was no original package, see one for the real package name.
9151            if (ps == null) {
9152                ps = mSettings.getPackageLPr(pkg.packageName);
9153            }
9154            // Check to see if this package could be hiding/updating a system
9155            // package.  Must look for it either under the original or real
9156            // package name depending on our state.
9157            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9158            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9159
9160            // If this is a package we don't know about on the system partition, we
9161            // may need to remove disabled child packages on the system partition
9162            // or may need to not add child packages if the parent apk is updated
9163            // on the data partition and no longer defines this child package.
9164            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9165                // If this is a parent package for an updated system app and this system
9166                // app got an OTA update which no longer defines some of the child packages
9167                // we have to prune them from the disabled system packages.
9168                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9169                if (disabledPs != null) {
9170                    final int scannedChildCount = (pkg.childPackages != null)
9171                            ? pkg.childPackages.size() : 0;
9172                    final int disabledChildCount = disabledPs.childPackageNames != null
9173                            ? disabledPs.childPackageNames.size() : 0;
9174                    for (int i = 0; i < disabledChildCount; i++) {
9175                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9176                        boolean disabledPackageAvailable = false;
9177                        for (int j = 0; j < scannedChildCount; j++) {
9178                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9179                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9180                                disabledPackageAvailable = true;
9181                                break;
9182                            }
9183                         }
9184                         if (!disabledPackageAvailable) {
9185                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9186                         }
9187                    }
9188                }
9189            }
9190        }
9191
9192        final boolean isUpdatedPkg = updatedPkg != null;
9193        final boolean isUpdatedSystemPkg = isUpdatedPkg
9194                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9195        boolean isUpdatedPkgBetter = false;
9196        // First check if this is a system package that may involve an update
9197        if (isUpdatedSystemPkg) {
9198            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9199            // it needs to drop FLAG_PRIVILEGED.
9200            if (locationIsPrivileged(scanFile)) {
9201                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9202            } else {
9203                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9204            }
9205
9206            if (ps != null && !ps.codePath.equals(scanFile)) {
9207                // The path has changed from what was last scanned...  check the
9208                // version of the new path against what we have stored to determine
9209                // what to do.
9210                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9211                if (pkg.mVersionCode <= ps.versionCode) {
9212                    // The system package has been updated and the code path does not match
9213                    // Ignore entry. Skip it.
9214                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9215                            + " ignored: updated version " + ps.versionCode
9216                            + " better than this " + pkg.mVersionCode);
9217                    if (!updatedPkg.codePath.equals(scanFile)) {
9218                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9219                                + ps.name + " changing from " + updatedPkg.codePathString
9220                                + " to " + scanFile);
9221                        updatedPkg.codePath = scanFile;
9222                        updatedPkg.codePathString = scanFile.toString();
9223                        updatedPkg.resourcePath = scanFile;
9224                        updatedPkg.resourcePathString = scanFile.toString();
9225                    }
9226                    updatedPkg.pkg = pkg;
9227                    updatedPkg.versionCode = pkg.mVersionCode;
9228
9229                    // Update the disabled system child packages to point to the package too.
9230                    final int childCount = updatedPkg.childPackageNames != null
9231                            ? updatedPkg.childPackageNames.size() : 0;
9232                    for (int i = 0; i < childCount; i++) {
9233                        String childPackageName = updatedPkg.childPackageNames.get(i);
9234                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9235                                childPackageName);
9236                        if (updatedChildPkg != null) {
9237                            updatedChildPkg.pkg = pkg;
9238                            updatedChildPkg.versionCode = pkg.mVersionCode;
9239                        }
9240                    }
9241                } else {
9242                    // The current app on the system partition is better than
9243                    // what we have updated to on the data partition; switch
9244                    // back to the system partition version.
9245                    // At this point, its safely assumed that package installation for
9246                    // apps in system partition will go through. If not there won't be a working
9247                    // version of the app
9248                    // writer
9249                    synchronized (mPackages) {
9250                        // Just remove the loaded entries from package lists.
9251                        mPackages.remove(ps.name);
9252                    }
9253
9254                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9255                            + " reverting from " + ps.codePathString
9256                            + ": new version " + pkg.mVersionCode
9257                            + " better than installed " + ps.versionCode);
9258
9259                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9260                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9261                    synchronized (mInstallLock) {
9262                        args.cleanUpResourcesLI();
9263                    }
9264                    synchronized (mPackages) {
9265                        mSettings.enableSystemPackageLPw(ps.name);
9266                    }
9267                    isUpdatedPkgBetter = true;
9268                }
9269            }
9270        }
9271
9272        String resourcePath = null;
9273        String baseResourcePath = null;
9274        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9275            if (ps != null && ps.resourcePathString != null) {
9276                resourcePath = ps.resourcePathString;
9277                baseResourcePath = ps.resourcePathString;
9278            } else {
9279                // Should not happen at all. Just log an error.
9280                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9281            }
9282        } else {
9283            resourcePath = pkg.codePath;
9284            baseResourcePath = pkg.baseCodePath;
9285        }
9286
9287        // Set application objects path explicitly.
9288        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9289        pkg.setApplicationInfoCodePath(pkg.codePath);
9290        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9291        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9292        pkg.setApplicationInfoResourcePath(resourcePath);
9293        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9294        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9295
9296        // throw an exception if we have an update to a system application, but, it's not more
9297        // recent than the package we've already scanned
9298        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9299            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9300                    + scanFile + " ignored: updated version " + ps.versionCode
9301                    + " better than this " + pkg.mVersionCode);
9302        }
9303
9304        if (isUpdatedPkg) {
9305            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9306            // initially
9307            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9308
9309            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9310            // flag set initially
9311            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9312                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9313            }
9314        }
9315
9316        // Verify certificates against what was last scanned
9317        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9318
9319        /*
9320         * A new system app appeared, but we already had a non-system one of the
9321         * same name installed earlier.
9322         */
9323        boolean shouldHideSystemApp = false;
9324        if (!isUpdatedPkg && ps != null
9325                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9326            /*
9327             * Check to make sure the signatures match first. If they don't,
9328             * wipe the installed application and its data.
9329             */
9330            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9331                    != PackageManager.SIGNATURE_MATCH) {
9332                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9333                        + " signatures don't match existing userdata copy; removing");
9334                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9335                        "scanPackageInternalLI")) {
9336                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9337                }
9338                ps = null;
9339            } else {
9340                /*
9341                 * If the newly-added system app is an older version than the
9342                 * already installed version, hide it. It will be scanned later
9343                 * and re-added like an update.
9344                 */
9345                if (pkg.mVersionCode <= ps.versionCode) {
9346                    shouldHideSystemApp = true;
9347                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9348                            + " but new version " + pkg.mVersionCode + " better than installed "
9349                            + ps.versionCode + "; hiding system");
9350                } else {
9351                    /*
9352                     * The newly found system app is a newer version that the
9353                     * one previously installed. Simply remove the
9354                     * already-installed application and replace it with our own
9355                     * while keeping the application data.
9356                     */
9357                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9358                            + " reverting from " + ps.codePathString + ": new version "
9359                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9360                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9361                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9362                    synchronized (mInstallLock) {
9363                        args.cleanUpResourcesLI();
9364                    }
9365                }
9366            }
9367        }
9368
9369        // The apk is forward locked (not public) if its code and resources
9370        // are kept in different files. (except for app in either system or
9371        // vendor path).
9372        // TODO grab this value from PackageSettings
9373        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9374            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9375                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9376            }
9377        }
9378
9379        final int userId = ((user == null) ? 0 : user.getIdentifier());
9380        if (ps != null && ps.getInstantApp(userId)) {
9381            scanFlags |= SCAN_AS_INSTANT_APP;
9382        }
9383
9384        // Note that we invoke the following method only if we are about to unpack an application
9385        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9386                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9387
9388        /*
9389         * If the system app should be overridden by a previously installed
9390         * data, hide the system app now and let the /data/app scan pick it up
9391         * again.
9392         */
9393        if (shouldHideSystemApp) {
9394            synchronized (mPackages) {
9395                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9396            }
9397        }
9398
9399        return scannedPkg;
9400    }
9401
9402    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9403        // Derive the new package synthetic package name
9404        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9405                + pkg.staticSharedLibVersion);
9406    }
9407
9408    private static String fixProcessName(String defProcessName,
9409            String processName) {
9410        if (processName == null) {
9411            return defProcessName;
9412        }
9413        return processName;
9414    }
9415
9416    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9417            throws PackageManagerException {
9418        if (pkgSetting.signatures.mSignatures != null) {
9419            // Already existing package. Make sure signatures match
9420            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9421                    == PackageManager.SIGNATURE_MATCH;
9422            if (!match) {
9423                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9424                        == PackageManager.SIGNATURE_MATCH;
9425            }
9426            if (!match) {
9427                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9428                        == PackageManager.SIGNATURE_MATCH;
9429            }
9430            if (!match) {
9431                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9432                        + pkg.packageName + " signatures do not match the "
9433                        + "previously installed version; ignoring!");
9434            }
9435        }
9436
9437        // Check for shared user signatures
9438        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9439            // Already existing package. Make sure signatures match
9440            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9441                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9442            if (!match) {
9443                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9444                        == PackageManager.SIGNATURE_MATCH;
9445            }
9446            if (!match) {
9447                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9448                        == PackageManager.SIGNATURE_MATCH;
9449            }
9450            if (!match) {
9451                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9452                        "Package " + pkg.packageName
9453                        + " has no signatures that match those in shared user "
9454                        + pkgSetting.sharedUser.name + "; ignoring!");
9455            }
9456        }
9457    }
9458
9459    /**
9460     * Enforces that only the system UID or root's UID can call a method exposed
9461     * via Binder.
9462     *
9463     * @param message used as message if SecurityException is thrown
9464     * @throws SecurityException if the caller is not system or root
9465     */
9466    private static final void enforceSystemOrRoot(String message) {
9467        final int uid = Binder.getCallingUid();
9468        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9469            throw new SecurityException(message);
9470        }
9471    }
9472
9473    @Override
9474    public void performFstrimIfNeeded() {
9475        enforceSystemOrRoot("Only the system can request fstrim");
9476
9477        // Before everything else, see whether we need to fstrim.
9478        try {
9479            IStorageManager sm = PackageHelper.getStorageManager();
9480            if (sm != null) {
9481                boolean doTrim = false;
9482                final long interval = android.provider.Settings.Global.getLong(
9483                        mContext.getContentResolver(),
9484                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9485                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9486                if (interval > 0) {
9487                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9488                    if (timeSinceLast > interval) {
9489                        doTrim = true;
9490                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9491                                + "; running immediately");
9492                    }
9493                }
9494                if (doTrim) {
9495                    final boolean dexOptDialogShown;
9496                    synchronized (mPackages) {
9497                        dexOptDialogShown = mDexOptDialogShown;
9498                    }
9499                    if (!isFirstBoot() && dexOptDialogShown) {
9500                        try {
9501                            ActivityManager.getService().showBootMessage(
9502                                    mContext.getResources().getString(
9503                                            R.string.android_upgrading_fstrim), true);
9504                        } catch (RemoteException e) {
9505                        }
9506                    }
9507                    sm.runMaintenance();
9508                }
9509            } else {
9510                Slog.e(TAG, "storageManager service unavailable!");
9511            }
9512        } catch (RemoteException e) {
9513            // Can't happen; StorageManagerService is local
9514        }
9515    }
9516
9517    @Override
9518    public void updatePackagesIfNeeded() {
9519        enforceSystemOrRoot("Only the system can request package update");
9520
9521        // We need to re-extract after an OTA.
9522        boolean causeUpgrade = isUpgrade();
9523
9524        // First boot or factory reset.
9525        // Note: we also handle devices that are upgrading to N right now as if it is their
9526        //       first boot, as they do not have profile data.
9527        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9528
9529        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9530        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9531
9532        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9533            return;
9534        }
9535
9536        List<PackageParser.Package> pkgs;
9537        synchronized (mPackages) {
9538            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9539        }
9540
9541        final long startTime = System.nanoTime();
9542        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9543                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9544                    false /* bootComplete */);
9545
9546        final int elapsedTimeSeconds =
9547                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9548
9549        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9550        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9551        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9552        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9553        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9554    }
9555
9556    /*
9557     * Return the prebuilt profile path given a package base code path.
9558     */
9559    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9560        return pkg.baseCodePath + ".prof";
9561    }
9562
9563    /**
9564     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9565     * containing statistics about the invocation. The array consists of three elements,
9566     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9567     * and {@code numberOfPackagesFailed}.
9568     */
9569    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9570            String compilerFilter, boolean bootComplete) {
9571
9572        int numberOfPackagesVisited = 0;
9573        int numberOfPackagesOptimized = 0;
9574        int numberOfPackagesSkipped = 0;
9575        int numberOfPackagesFailed = 0;
9576        final int numberOfPackagesToDexopt = pkgs.size();
9577
9578        for (PackageParser.Package pkg : pkgs) {
9579            numberOfPackagesVisited++;
9580
9581            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9582                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9583                // that are already compiled.
9584                File profileFile = new File(getPrebuildProfilePath(pkg));
9585                // Copy profile if it exists.
9586                if (profileFile.exists()) {
9587                    try {
9588                        // We could also do this lazily before calling dexopt in
9589                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9590                        // is that we don't have a good way to say "do this only once".
9591                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9592                                pkg.applicationInfo.uid, pkg.packageName)) {
9593                            Log.e(TAG, "Installer failed to copy system profile!");
9594                        }
9595                    } catch (Exception e) {
9596                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9597                                e);
9598                    }
9599                }
9600            }
9601
9602            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9603                if (DEBUG_DEXOPT) {
9604                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9605                }
9606                numberOfPackagesSkipped++;
9607                continue;
9608            }
9609
9610            if (DEBUG_DEXOPT) {
9611                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9612                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9613            }
9614
9615            if (showDialog) {
9616                try {
9617                    ActivityManager.getService().showBootMessage(
9618                            mContext.getResources().getString(R.string.android_upgrading_apk,
9619                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9620                } catch (RemoteException e) {
9621                }
9622                synchronized (mPackages) {
9623                    mDexOptDialogShown = true;
9624                }
9625            }
9626
9627            // If the OTA updates a system app which was previously preopted to a non-preopted state
9628            // the app might end up being verified at runtime. That's because by default the apps
9629            // are verify-profile but for preopted apps there's no profile.
9630            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9631            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9632            // filter (by default 'quicken').
9633            // Note that at this stage unused apps are already filtered.
9634            if (isSystemApp(pkg) &&
9635                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9636                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9637                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9638            }
9639
9640            // checkProfiles is false to avoid merging profiles during boot which
9641            // might interfere with background compilation (b/28612421).
9642            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9643            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9644            // trade-off worth doing to save boot time work.
9645            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9646            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9647                    pkg.packageName,
9648                    compilerFilter,
9649                    dexoptFlags));
9650
9651            if (pkg.isSystemApp()) {
9652                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9653                // too much boot after an OTA.
9654                int secondaryDexoptFlags = dexoptFlags |
9655                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9656                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9657                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9658                        pkg.packageName,
9659                        compilerFilter,
9660                        secondaryDexoptFlags));
9661            }
9662
9663            // TODO(shubhamajmera): Record secondary dexopt stats.
9664            switch (primaryDexOptStaus) {
9665                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9666                    numberOfPackagesOptimized++;
9667                    break;
9668                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9669                    numberOfPackagesSkipped++;
9670                    break;
9671                case PackageDexOptimizer.DEX_OPT_FAILED:
9672                    numberOfPackagesFailed++;
9673                    break;
9674                default:
9675                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9676                    break;
9677            }
9678        }
9679
9680        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9681                numberOfPackagesFailed };
9682    }
9683
9684    @Override
9685    public void notifyPackageUse(String packageName, int reason) {
9686        synchronized (mPackages) {
9687            final int callingUid = Binder.getCallingUid();
9688            final int callingUserId = UserHandle.getUserId(callingUid);
9689            if (getInstantAppPackageName(callingUid) != null) {
9690                if (!isCallerSameApp(packageName, callingUid)) {
9691                    return;
9692                }
9693            } else {
9694                if (isInstantApp(packageName, callingUserId)) {
9695                    return;
9696                }
9697            }
9698            final PackageParser.Package p = mPackages.get(packageName);
9699            if (p == null) {
9700                return;
9701            }
9702            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9703        }
9704    }
9705
9706    @Override
9707    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9708        int userId = UserHandle.getCallingUserId();
9709        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9710        if (ai == null) {
9711            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9712                + loadingPackageName + ", user=" + userId);
9713            return;
9714        }
9715        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9716    }
9717
9718    @Override
9719    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9720            IDexModuleRegisterCallback callback) {
9721        int userId = UserHandle.getCallingUserId();
9722        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9723        DexManager.RegisterDexModuleResult result;
9724        if (ai == null) {
9725            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9726                     " calling user. package=" + packageName + ", user=" + userId);
9727            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9728        } else {
9729            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9730        }
9731
9732        if (callback != null) {
9733            mHandler.post(() -> {
9734                try {
9735                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9736                } catch (RemoteException e) {
9737                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9738                }
9739            });
9740        }
9741    }
9742
9743    /**
9744     * Ask the package manager to perform a dex-opt with the given compiler filter.
9745     *
9746     * Note: exposed only for the shell command to allow moving packages explicitly to a
9747     *       definite state.
9748     */
9749    @Override
9750    public boolean performDexOptMode(String packageName,
9751            boolean checkProfiles, String targetCompilerFilter, boolean force,
9752            boolean bootComplete, String splitName) {
9753        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9754                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9755                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9756        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9757                splitName, flags));
9758    }
9759
9760    /**
9761     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9762     * secondary dex files belonging to the given package.
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 performDexOptSecondary(String packageName, String compilerFilter,
9769            boolean force) {
9770        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9771                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9772                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9773                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9774        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9775    }
9776
9777    /*package*/ boolean performDexOpt(DexoptOptions options) {
9778        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9779            return false;
9780        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9781            return false;
9782        }
9783
9784        if (options.isDexoptOnlySecondaryDex()) {
9785            return mDexManager.dexoptSecondaryDex(options);
9786        } else {
9787            int dexoptStatus = performDexOptWithStatus(options);
9788            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9789        }
9790    }
9791
9792    /**
9793     * Perform dexopt on the given package and return one of following result:
9794     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9795     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9796     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9797     */
9798    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9799        return performDexOptTraced(options);
9800    }
9801
9802    private int performDexOptTraced(DexoptOptions options) {
9803        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9804        try {
9805            return performDexOptInternal(options);
9806        } finally {
9807            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9808        }
9809    }
9810
9811    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9812    // if the package can now be considered up to date for the given filter.
9813    private int performDexOptInternal(DexoptOptions options) {
9814        PackageParser.Package p;
9815        synchronized (mPackages) {
9816            p = mPackages.get(options.getPackageName());
9817            if (p == null) {
9818                // Package could not be found. Report failure.
9819                return PackageDexOptimizer.DEX_OPT_FAILED;
9820            }
9821            mPackageUsage.maybeWriteAsync(mPackages);
9822            mCompilerStats.maybeWriteAsync();
9823        }
9824        long callingId = Binder.clearCallingIdentity();
9825        try {
9826            synchronized (mInstallLock) {
9827                return performDexOptInternalWithDependenciesLI(p, options);
9828            }
9829        } finally {
9830            Binder.restoreCallingIdentity(callingId);
9831        }
9832    }
9833
9834    public ArraySet<String> getOptimizablePackages() {
9835        ArraySet<String> pkgs = new ArraySet<String>();
9836        synchronized (mPackages) {
9837            for (PackageParser.Package p : mPackages.values()) {
9838                if (PackageDexOptimizer.canOptimizePackage(p)) {
9839                    pkgs.add(p.packageName);
9840                }
9841            }
9842        }
9843        return pkgs;
9844    }
9845
9846    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9847            DexoptOptions options) {
9848        // Select the dex optimizer based on the force parameter.
9849        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9850        //       allocate an object here.
9851        PackageDexOptimizer pdo = options.isForce()
9852                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9853                : mPackageDexOptimizer;
9854
9855        // Dexopt all dependencies first. Note: we ignore the return value and march on
9856        // on errors.
9857        // Note that we are going to call performDexOpt on those libraries as many times as
9858        // they are referenced in packages. When we do a batch of performDexOpt (for example
9859        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9860        // and the first package that uses the library will dexopt it. The
9861        // others will see that the compiled code for the library is up to date.
9862        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9863        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9864        if (!deps.isEmpty()) {
9865            for (PackageParser.Package depPackage : deps) {
9866                // TODO: Analyze and investigate if we (should) profile libraries.
9867                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9868                        getOrCreateCompilerPackageStats(depPackage),
9869                        true /* isUsedByOtherApps */,
9870                        options);
9871            }
9872        }
9873        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9874                getOrCreateCompilerPackageStats(p),
9875                mDexManager.isUsedByOtherApps(p.packageName), options);
9876    }
9877
9878    /**
9879     * Reconcile the information we have about the secondary dex files belonging to
9880     * {@code packagName} and the actual dex files. For all dex files that were
9881     * deleted, update the internal records and delete the generated oat files.
9882     */
9883    @Override
9884    public void reconcileSecondaryDexFiles(String packageName) {
9885        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9886            return;
9887        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9888            return;
9889        }
9890        mDexManager.reconcileSecondaryDexFiles(packageName);
9891    }
9892
9893    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9894    // a reference there.
9895    /*package*/ DexManager getDexManager() {
9896        return mDexManager;
9897    }
9898
9899    /**
9900     * Execute the background dexopt job immediately.
9901     */
9902    @Override
9903    public boolean runBackgroundDexoptJob() {
9904        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9905            return false;
9906        }
9907        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9908    }
9909
9910    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9911        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9912                || p.usesStaticLibraries != null) {
9913            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9914            Set<String> collectedNames = new HashSet<>();
9915            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9916
9917            retValue.remove(p);
9918
9919            return retValue;
9920        } else {
9921            return Collections.emptyList();
9922        }
9923    }
9924
9925    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9926            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9927        if (!collectedNames.contains(p.packageName)) {
9928            collectedNames.add(p.packageName);
9929            collected.add(p);
9930
9931            if (p.usesLibraries != null) {
9932                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9933                        null, collected, collectedNames);
9934            }
9935            if (p.usesOptionalLibraries != null) {
9936                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9937                        null, collected, collectedNames);
9938            }
9939            if (p.usesStaticLibraries != null) {
9940                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9941                        p.usesStaticLibrariesVersions, collected, collectedNames);
9942            }
9943        }
9944    }
9945
9946    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9947            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9948        final int libNameCount = libs.size();
9949        for (int i = 0; i < libNameCount; i++) {
9950            String libName = libs.get(i);
9951            int version = (versions != null && versions.length == libNameCount)
9952                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9953            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9954            if (libPkg != null) {
9955                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9956            }
9957        }
9958    }
9959
9960    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9961        synchronized (mPackages) {
9962            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9963            if (libEntry != null) {
9964                return mPackages.get(libEntry.apk);
9965            }
9966            return null;
9967        }
9968    }
9969
9970    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9971        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9972        if (versionedLib == null) {
9973            return null;
9974        }
9975        return versionedLib.get(version);
9976    }
9977
9978    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9979        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9980                pkg.staticSharedLibName);
9981        if (versionedLib == null) {
9982            return null;
9983        }
9984        int previousLibVersion = -1;
9985        final int versionCount = versionedLib.size();
9986        for (int i = 0; i < versionCount; i++) {
9987            final int libVersion = versionedLib.keyAt(i);
9988            if (libVersion < pkg.staticSharedLibVersion) {
9989                previousLibVersion = Math.max(previousLibVersion, libVersion);
9990            }
9991        }
9992        if (previousLibVersion >= 0) {
9993            return versionedLib.get(previousLibVersion);
9994        }
9995        return null;
9996    }
9997
9998    public void shutdown() {
9999        mPackageUsage.writeNow(mPackages);
10000        mCompilerStats.writeNow();
10001    }
10002
10003    @Override
10004    public void dumpProfiles(String packageName) {
10005        PackageParser.Package pkg;
10006        synchronized (mPackages) {
10007            pkg = mPackages.get(packageName);
10008            if (pkg == null) {
10009                throw new IllegalArgumentException("Unknown package: " + packageName);
10010            }
10011        }
10012        /* Only the shell, root, or the app user should be able to dump profiles. */
10013        int callingUid = Binder.getCallingUid();
10014        if (callingUid != Process.SHELL_UID &&
10015            callingUid != Process.ROOT_UID &&
10016            callingUid != pkg.applicationInfo.uid) {
10017            throw new SecurityException("dumpProfiles");
10018        }
10019
10020        synchronized (mInstallLock) {
10021            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10022            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10023            try {
10024                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10025                String codePaths = TextUtils.join(";", allCodePaths);
10026                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10027            } catch (InstallerException e) {
10028                Slog.w(TAG, "Failed to dump profiles", e);
10029            }
10030            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10031        }
10032    }
10033
10034    @Override
10035    public void forceDexOpt(String packageName) {
10036        enforceSystemOrRoot("forceDexOpt");
10037
10038        PackageParser.Package pkg;
10039        synchronized (mPackages) {
10040            pkg = mPackages.get(packageName);
10041            if (pkg == null) {
10042                throw new IllegalArgumentException("Unknown package: " + packageName);
10043            }
10044        }
10045
10046        synchronized (mInstallLock) {
10047            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10048
10049            // Whoever is calling forceDexOpt wants a compiled package.
10050            // Don't use profiles since that may cause compilation to be skipped.
10051            final int res = performDexOptInternalWithDependenciesLI(
10052                    pkg,
10053                    new DexoptOptions(packageName,
10054                            getDefaultCompilerFilter(),
10055                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10056
10057            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10058            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10059                throw new IllegalStateException("Failed to dexopt: " + res);
10060            }
10061        }
10062    }
10063
10064    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10065        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10066            Slog.w(TAG, "Unable to update from " + oldPkg.name
10067                    + " to " + newPkg.packageName
10068                    + ": old package not in system partition");
10069            return false;
10070        } else if (mPackages.get(oldPkg.name) != null) {
10071            Slog.w(TAG, "Unable to update from " + oldPkg.name
10072                    + " to " + newPkg.packageName
10073                    + ": old package still exists");
10074            return false;
10075        }
10076        return true;
10077    }
10078
10079    void removeCodePathLI(File codePath) {
10080        if (codePath.isDirectory()) {
10081            try {
10082                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10083            } catch (InstallerException e) {
10084                Slog.w(TAG, "Failed to remove code path", e);
10085            }
10086        } else {
10087            codePath.delete();
10088        }
10089    }
10090
10091    private int[] resolveUserIds(int userId) {
10092        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10093    }
10094
10095    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10096        if (pkg == null) {
10097            Slog.wtf(TAG, "Package was null!", new Throwable());
10098            return;
10099        }
10100        clearAppDataLeafLIF(pkg, userId, flags);
10101        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10102        for (int i = 0; i < childCount; i++) {
10103            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10104        }
10105    }
10106
10107    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10108        final PackageSetting ps;
10109        synchronized (mPackages) {
10110            ps = mSettings.mPackages.get(pkg.packageName);
10111        }
10112        for (int realUserId : resolveUserIds(userId)) {
10113            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10114            try {
10115                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10116                        ceDataInode);
10117            } catch (InstallerException e) {
10118                Slog.w(TAG, String.valueOf(e));
10119            }
10120        }
10121    }
10122
10123    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10124        if (pkg == null) {
10125            Slog.wtf(TAG, "Package was null!", new Throwable());
10126            return;
10127        }
10128        destroyAppDataLeafLIF(pkg, userId, flags);
10129        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10130        for (int i = 0; i < childCount; i++) {
10131            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10132        }
10133    }
10134
10135    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10136        final PackageSetting ps;
10137        synchronized (mPackages) {
10138            ps = mSettings.mPackages.get(pkg.packageName);
10139        }
10140        for (int realUserId : resolveUserIds(userId)) {
10141            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10142            try {
10143                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10144                        ceDataInode);
10145            } catch (InstallerException e) {
10146                Slog.w(TAG, String.valueOf(e));
10147            }
10148            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10149        }
10150    }
10151
10152    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10153        if (pkg == null) {
10154            Slog.wtf(TAG, "Package was null!", new Throwable());
10155            return;
10156        }
10157        destroyAppProfilesLeafLIF(pkg);
10158        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10159        for (int i = 0; i < childCount; i++) {
10160            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10161        }
10162    }
10163
10164    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10165        try {
10166            mInstaller.destroyAppProfiles(pkg.packageName);
10167        } catch (InstallerException e) {
10168            Slog.w(TAG, String.valueOf(e));
10169        }
10170    }
10171
10172    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10173        if (pkg == null) {
10174            Slog.wtf(TAG, "Package was null!", new Throwable());
10175            return;
10176        }
10177        clearAppProfilesLeafLIF(pkg);
10178        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10179        for (int i = 0; i < childCount; i++) {
10180            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10181        }
10182    }
10183
10184    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10185        try {
10186            mInstaller.clearAppProfiles(pkg.packageName);
10187        } catch (InstallerException e) {
10188            Slog.w(TAG, String.valueOf(e));
10189        }
10190    }
10191
10192    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10193            long lastUpdateTime) {
10194        // Set parent install/update time
10195        PackageSetting ps = (PackageSetting) pkg.mExtras;
10196        if (ps != null) {
10197            ps.firstInstallTime = firstInstallTime;
10198            ps.lastUpdateTime = lastUpdateTime;
10199        }
10200        // Set children install/update time
10201        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10202        for (int i = 0; i < childCount; i++) {
10203            PackageParser.Package childPkg = pkg.childPackages.get(i);
10204            ps = (PackageSetting) childPkg.mExtras;
10205            if (ps != null) {
10206                ps.firstInstallTime = firstInstallTime;
10207                ps.lastUpdateTime = lastUpdateTime;
10208            }
10209        }
10210    }
10211
10212    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10213            PackageParser.Package changingLib) {
10214        if (file.path != null) {
10215            usesLibraryFiles.add(file.path);
10216            return;
10217        }
10218        PackageParser.Package p = mPackages.get(file.apk);
10219        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10220            // If we are doing this while in the middle of updating a library apk,
10221            // then we need to make sure to use that new apk for determining the
10222            // dependencies here.  (We haven't yet finished committing the new apk
10223            // to the package manager state.)
10224            if (p == null || p.packageName.equals(changingLib.packageName)) {
10225                p = changingLib;
10226            }
10227        }
10228        if (p != null) {
10229            usesLibraryFiles.addAll(p.getAllCodePaths());
10230            if (p.usesLibraryFiles != null) {
10231                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10232            }
10233        }
10234    }
10235
10236    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10237            PackageParser.Package changingLib) throws PackageManagerException {
10238        if (pkg == null) {
10239            return;
10240        }
10241        ArraySet<String> usesLibraryFiles = null;
10242        if (pkg.usesLibraries != null) {
10243            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10244                    null, null, pkg.packageName, changingLib, true, null);
10245        }
10246        if (pkg.usesStaticLibraries != null) {
10247            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10248                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10249                    pkg.packageName, changingLib, true, usesLibraryFiles);
10250        }
10251        if (pkg.usesOptionalLibraries != null) {
10252            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10253                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
10254        }
10255        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10256            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10257        } else {
10258            pkg.usesLibraryFiles = null;
10259        }
10260    }
10261
10262    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10263            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10264            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10265            boolean required, @Nullable ArraySet<String> outUsedLibraries)
10266            throws PackageManagerException {
10267        final int libCount = requestedLibraries.size();
10268        for (int i = 0; i < libCount; i++) {
10269            final String libName = requestedLibraries.get(i);
10270            final int libVersion = requiredVersions != null ? requiredVersions[i]
10271                    : SharedLibraryInfo.VERSION_UNDEFINED;
10272            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10273            if (libEntry == null) {
10274                if (required) {
10275                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10276                            "Package " + packageName + " requires unavailable shared library "
10277                                    + libName + "; failing!");
10278                } else if (DEBUG_SHARED_LIBRARIES) {
10279                    Slog.i(TAG, "Package " + packageName
10280                            + " desires unavailable shared library "
10281                            + libName + "; ignoring!");
10282                }
10283            } else {
10284                if (requiredVersions != null && requiredCertDigests != null) {
10285                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10286                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10287                            "Package " + packageName + " requires unavailable static shared"
10288                                    + " library " + libName + " version "
10289                                    + libEntry.info.getVersion() + "; failing!");
10290                    }
10291
10292                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10293                    if (libPkg == null) {
10294                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10295                                "Package " + packageName + " requires unavailable static shared"
10296                                        + " library; failing!");
10297                    }
10298
10299                    String expectedCertDigest = requiredCertDigests[i];
10300                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10301                                libPkg.mSignatures[0]);
10302                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10303                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10304                                "Package " + packageName + " requires differently signed" +
10305                                        " static shared library; failing!");
10306                    }
10307                }
10308
10309                if (outUsedLibraries == null) {
10310                    outUsedLibraries = new ArraySet<>();
10311                }
10312                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10313            }
10314        }
10315        return outUsedLibraries;
10316    }
10317
10318    private static boolean hasString(List<String> list, List<String> which) {
10319        if (list == null) {
10320            return false;
10321        }
10322        for (int i=list.size()-1; i>=0; i--) {
10323            for (int j=which.size()-1; j>=0; j--) {
10324                if (which.get(j).equals(list.get(i))) {
10325                    return true;
10326                }
10327            }
10328        }
10329        return false;
10330    }
10331
10332    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10333            PackageParser.Package changingPkg) {
10334        ArrayList<PackageParser.Package> res = null;
10335        for (PackageParser.Package pkg : mPackages.values()) {
10336            if (changingPkg != null
10337                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10338                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10339                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10340                            changingPkg.staticSharedLibName)) {
10341                return null;
10342            }
10343            if (res == null) {
10344                res = new ArrayList<>();
10345            }
10346            res.add(pkg);
10347            try {
10348                updateSharedLibrariesLPr(pkg, changingPkg);
10349            } catch (PackageManagerException e) {
10350                // If a system app update or an app and a required lib missing we
10351                // delete the package and for updated system apps keep the data as
10352                // it is better for the user to reinstall than to be in an limbo
10353                // state. Also libs disappearing under an app should never happen
10354                // - just in case.
10355                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10356                    final int flags = pkg.isUpdatedSystemApp()
10357                            ? PackageManager.DELETE_KEEP_DATA : 0;
10358                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10359                            flags , null, true, null);
10360                }
10361                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10362            }
10363        }
10364        return res;
10365    }
10366
10367    /**
10368     * Derive the value of the {@code cpuAbiOverride} based on the provided
10369     * value and an optional stored value from the package settings.
10370     */
10371    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10372        String cpuAbiOverride = null;
10373
10374        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10375            cpuAbiOverride = null;
10376        } else if (abiOverride != null) {
10377            cpuAbiOverride = abiOverride;
10378        } else if (settings != null) {
10379            cpuAbiOverride = settings.cpuAbiOverrideString;
10380        }
10381
10382        return cpuAbiOverride;
10383    }
10384
10385    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10386            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10387                    throws PackageManagerException {
10388        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10389        // If the package has children and this is the first dive in the function
10390        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10391        // whether all packages (parent and children) would be successfully scanned
10392        // before the actual scan since scanning mutates internal state and we want
10393        // to atomically install the package and its children.
10394        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10395            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10396                scanFlags |= SCAN_CHECK_ONLY;
10397            }
10398        } else {
10399            scanFlags &= ~SCAN_CHECK_ONLY;
10400        }
10401
10402        final PackageParser.Package scannedPkg;
10403        try {
10404            // Scan the parent
10405            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10406            // Scan the children
10407            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10408            for (int i = 0; i < childCount; i++) {
10409                PackageParser.Package childPkg = pkg.childPackages.get(i);
10410                scanPackageLI(childPkg, policyFlags,
10411                        scanFlags, currentTime, user);
10412            }
10413        } finally {
10414            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10415        }
10416
10417        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10418            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10419        }
10420
10421        return scannedPkg;
10422    }
10423
10424    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10425            int scanFlags, long currentTime, @Nullable UserHandle user)
10426                    throws PackageManagerException {
10427        boolean success = false;
10428        try {
10429            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10430                    currentTime, user);
10431            success = true;
10432            return res;
10433        } finally {
10434            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10435                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10436                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10437                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10438                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10439            }
10440        }
10441    }
10442
10443    /**
10444     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10445     */
10446    private static boolean apkHasCode(String fileName) {
10447        StrictJarFile jarFile = null;
10448        try {
10449            jarFile = new StrictJarFile(fileName,
10450                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10451            return jarFile.findEntry("classes.dex") != null;
10452        } catch (IOException ignore) {
10453        } finally {
10454            try {
10455                if (jarFile != null) {
10456                    jarFile.close();
10457                }
10458            } catch (IOException ignore) {}
10459        }
10460        return false;
10461    }
10462
10463    /**
10464     * Enforces code policy for the package. This ensures that if an APK has
10465     * declared hasCode="true" in its manifest that the APK actually contains
10466     * code.
10467     *
10468     * @throws PackageManagerException If bytecode could not be found when it should exist
10469     */
10470    private static void assertCodePolicy(PackageParser.Package pkg)
10471            throws PackageManagerException {
10472        final boolean shouldHaveCode =
10473                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10474        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10475            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10476                    "Package " + pkg.baseCodePath + " code is missing");
10477        }
10478
10479        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10480            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10481                final boolean splitShouldHaveCode =
10482                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10483                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10484                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10485                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10486                }
10487            }
10488        }
10489    }
10490
10491    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10492            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10493                    throws PackageManagerException {
10494        if (DEBUG_PACKAGE_SCANNING) {
10495            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10496                Log.d(TAG, "Scanning package " + pkg.packageName);
10497        }
10498
10499        applyPolicy(pkg, policyFlags);
10500
10501        assertPackageIsValid(pkg, policyFlags, scanFlags);
10502
10503        // Initialize package source and resource directories
10504        final File scanFile = new File(pkg.codePath);
10505        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10506        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10507
10508        SharedUserSetting suid = null;
10509        PackageSetting pkgSetting = null;
10510
10511        // Getting the package setting may have a side-effect, so if we
10512        // are only checking if scan would succeed, stash a copy of the
10513        // old setting to restore at the end.
10514        PackageSetting nonMutatedPs = null;
10515
10516        // We keep references to the derived CPU Abis from settings in oder to reuse
10517        // them in the case where we're not upgrading or booting for the first time.
10518        String primaryCpuAbiFromSettings = null;
10519        String secondaryCpuAbiFromSettings = null;
10520
10521        // writer
10522        synchronized (mPackages) {
10523            if (pkg.mSharedUserId != null) {
10524                // SIDE EFFECTS; may potentially allocate a new shared user
10525                suid = mSettings.getSharedUserLPw(
10526                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10527                if (DEBUG_PACKAGE_SCANNING) {
10528                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10529                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10530                                + "): packages=" + suid.packages);
10531                }
10532            }
10533
10534            // Check if we are renaming from an original package name.
10535            PackageSetting origPackage = null;
10536            String realName = null;
10537            if (pkg.mOriginalPackages != null) {
10538                // This package may need to be renamed to a previously
10539                // installed name.  Let's check on that...
10540                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10541                if (pkg.mOriginalPackages.contains(renamed)) {
10542                    // This package had originally been installed as the
10543                    // original name, and we have already taken care of
10544                    // transitioning to the new one.  Just update the new
10545                    // one to continue using the old name.
10546                    realName = pkg.mRealPackage;
10547                    if (!pkg.packageName.equals(renamed)) {
10548                        // Callers into this function may have already taken
10549                        // care of renaming the package; only do it here if
10550                        // it is not already done.
10551                        pkg.setPackageName(renamed);
10552                    }
10553                } else {
10554                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10555                        if ((origPackage = mSettings.getPackageLPr(
10556                                pkg.mOriginalPackages.get(i))) != null) {
10557                            // We do have the package already installed under its
10558                            // original name...  should we use it?
10559                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10560                                // New package is not compatible with original.
10561                                origPackage = null;
10562                                continue;
10563                            } else if (origPackage.sharedUser != null) {
10564                                // Make sure uid is compatible between packages.
10565                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10566                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10567                                            + " to " + pkg.packageName + ": old uid "
10568                                            + origPackage.sharedUser.name
10569                                            + " differs from " + pkg.mSharedUserId);
10570                                    origPackage = null;
10571                                    continue;
10572                                }
10573                                // TODO: Add case when shared user id is added [b/28144775]
10574                            } else {
10575                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10576                                        + pkg.packageName + " to old name " + origPackage.name);
10577                            }
10578                            break;
10579                        }
10580                    }
10581                }
10582            }
10583
10584            if (mTransferedPackages.contains(pkg.packageName)) {
10585                Slog.w(TAG, "Package " + pkg.packageName
10586                        + " was transferred to another, but its .apk remains");
10587            }
10588
10589            // See comments in nonMutatedPs declaration
10590            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10591                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10592                if (foundPs != null) {
10593                    nonMutatedPs = new PackageSetting(foundPs);
10594                }
10595            }
10596
10597            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10598                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10599                if (foundPs != null) {
10600                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10601                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10602                }
10603            }
10604
10605            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10606            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10607                PackageManagerService.reportSettingsProblem(Log.WARN,
10608                        "Package " + pkg.packageName + " shared user changed from "
10609                                + (pkgSetting.sharedUser != null
10610                                        ? pkgSetting.sharedUser.name : "<nothing>")
10611                                + " to "
10612                                + (suid != null ? suid.name : "<nothing>")
10613                                + "; replacing with new");
10614                pkgSetting = null;
10615            }
10616            final PackageSetting oldPkgSetting =
10617                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10618            final PackageSetting disabledPkgSetting =
10619                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10620
10621            String[] usesStaticLibraries = null;
10622            if (pkg.usesStaticLibraries != null) {
10623                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10624                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10625            }
10626
10627            if (pkgSetting == null) {
10628                final String parentPackageName = (pkg.parentPackage != null)
10629                        ? pkg.parentPackage.packageName : null;
10630                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10631                // REMOVE SharedUserSetting from method; update in a separate call
10632                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10633                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10634                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10635                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10636                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10637                        true /*allowInstall*/, instantApp, parentPackageName,
10638                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10639                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10640                // SIDE EFFECTS; updates system state; move elsewhere
10641                if (origPackage != null) {
10642                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10643                }
10644                mSettings.addUserToSettingLPw(pkgSetting);
10645            } else {
10646                // REMOVE SharedUserSetting from method; update in a separate call.
10647                //
10648                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10649                // secondaryCpuAbi are not known at this point so we always update them
10650                // to null here, only to reset them at a later point.
10651                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10652                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10653                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10654                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10655                        UserManagerService.getInstance(), usesStaticLibraries,
10656                        pkg.usesStaticLibrariesVersions);
10657            }
10658            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10659            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10660
10661            // SIDE EFFECTS; modifies system state; move elsewhere
10662            if (pkgSetting.origPackage != null) {
10663                // If we are first transitioning from an original package,
10664                // fix up the new package's name now.  We need to do this after
10665                // looking up the package under its new name, so getPackageLP
10666                // can take care of fiddling things correctly.
10667                pkg.setPackageName(origPackage.name);
10668
10669                // File a report about this.
10670                String msg = "New package " + pkgSetting.realName
10671                        + " renamed to replace old package " + pkgSetting.name;
10672                reportSettingsProblem(Log.WARN, msg);
10673
10674                // Make a note of it.
10675                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10676                    mTransferedPackages.add(origPackage.name);
10677                }
10678
10679                // No longer need to retain this.
10680                pkgSetting.origPackage = null;
10681            }
10682
10683            // SIDE EFFECTS; modifies system state; move elsewhere
10684            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10685                // Make a note of it.
10686                mTransferedPackages.add(pkg.packageName);
10687            }
10688
10689            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10690                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10691            }
10692
10693            if ((scanFlags & SCAN_BOOTING) == 0
10694                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10695                // Check all shared libraries and map to their actual file path.
10696                // We only do this here for apps not on a system dir, because those
10697                // are the only ones that can fail an install due to this.  We
10698                // will take care of the system apps by updating all of their
10699                // library paths after the scan is done. Also during the initial
10700                // scan don't update any libs as we do this wholesale after all
10701                // apps are scanned to avoid dependency based scanning.
10702                updateSharedLibrariesLPr(pkg, null);
10703            }
10704
10705            if (mFoundPolicyFile) {
10706                SELinuxMMAC.assignSeInfoValue(pkg);
10707            }
10708            pkg.applicationInfo.uid = pkgSetting.appId;
10709            pkg.mExtras = pkgSetting;
10710
10711
10712            // Static shared libs have same package with different versions where
10713            // we internally use a synthetic package name to allow multiple versions
10714            // of the same package, therefore we need to compare signatures against
10715            // the package setting for the latest library version.
10716            PackageSetting signatureCheckPs = pkgSetting;
10717            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10718                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10719                if (libraryEntry != null) {
10720                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10721                }
10722            }
10723
10724            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10725                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10726                    // We just determined the app is signed correctly, so bring
10727                    // over the latest parsed certs.
10728                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10729                } else {
10730                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10731                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10732                                "Package " + pkg.packageName + " upgrade keys do not match the "
10733                                + "previously installed version");
10734                    } else {
10735                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10736                        String msg = "System package " + pkg.packageName
10737                                + " signature changed; retaining data.";
10738                        reportSettingsProblem(Log.WARN, msg);
10739                    }
10740                }
10741            } else {
10742                try {
10743                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10744                    verifySignaturesLP(signatureCheckPs, pkg);
10745                    // We just determined the app is signed correctly, so bring
10746                    // over the latest parsed certs.
10747                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10748                } catch (PackageManagerException e) {
10749                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10750                        throw e;
10751                    }
10752                    // The signature has changed, but this package is in the system
10753                    // image...  let's recover!
10754                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10755                    // However...  if this package is part of a shared user, but it
10756                    // doesn't match the signature of the shared user, let's fail.
10757                    // What this means is that you can't change the signatures
10758                    // associated with an overall shared user, which doesn't seem all
10759                    // that unreasonable.
10760                    if (signatureCheckPs.sharedUser != null) {
10761                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10762                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10763                            throw new PackageManagerException(
10764                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10765                                    "Signature mismatch for shared user: "
10766                                            + pkgSetting.sharedUser);
10767                        }
10768                    }
10769                    // File a report about this.
10770                    String msg = "System package " + pkg.packageName
10771                            + " signature changed; retaining data.";
10772                    reportSettingsProblem(Log.WARN, msg);
10773                }
10774            }
10775
10776            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10777                // This package wants to adopt ownership of permissions from
10778                // another package.
10779                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10780                    final String origName = pkg.mAdoptPermissions.get(i);
10781                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10782                    if (orig != null) {
10783                        if (verifyPackageUpdateLPr(orig, pkg)) {
10784                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10785                                    + pkg.packageName);
10786                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10787                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10788                        }
10789                    }
10790                }
10791            }
10792        }
10793
10794        pkg.applicationInfo.processName = fixProcessName(
10795                pkg.applicationInfo.packageName,
10796                pkg.applicationInfo.processName);
10797
10798        if (pkg != mPlatformPackage) {
10799            // Get all of our default paths setup
10800            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10801        }
10802
10803        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10804
10805        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10806            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10807                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10808                final boolean extractNativeLibs = !pkg.isLibrary();
10809                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10810                        mAppLib32InstallDir);
10811                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10812
10813                // Some system apps still use directory structure for native libraries
10814                // in which case we might end up not detecting abi solely based on apk
10815                // structure. Try to detect abi based on directory structure.
10816                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10817                        pkg.applicationInfo.primaryCpuAbi == null) {
10818                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10819                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10820                }
10821            } else {
10822                // This is not a first boot or an upgrade, don't bother deriving the
10823                // ABI during the scan. Instead, trust the value that was stored in the
10824                // package setting.
10825                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10826                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10827
10828                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10829
10830                if (DEBUG_ABI_SELECTION) {
10831                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10832                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10833                        pkg.applicationInfo.secondaryCpuAbi);
10834                }
10835            }
10836        } else {
10837            if ((scanFlags & SCAN_MOVE) != 0) {
10838                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10839                // but we already have this packages package info in the PackageSetting. We just
10840                // use that and derive the native library path based on the new codepath.
10841                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10842                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10843            }
10844
10845            // Set native library paths again. For moves, the path will be updated based on the
10846            // ABIs we've determined above. For non-moves, the path will be updated based on the
10847            // ABIs we determined during compilation, but the path will depend on the final
10848            // package path (after the rename away from the stage path).
10849            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10850        }
10851
10852        // This is a special case for the "system" package, where the ABI is
10853        // dictated by the zygote configuration (and init.rc). We should keep track
10854        // of this ABI so that we can deal with "normal" applications that run under
10855        // the same UID correctly.
10856        if (mPlatformPackage == pkg) {
10857            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10858                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10859        }
10860
10861        // If there's a mismatch between the abi-override in the package setting
10862        // and the abiOverride specified for the install. Warn about this because we
10863        // would've already compiled the app without taking the package setting into
10864        // account.
10865        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10866            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10867                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10868                        " for package " + pkg.packageName);
10869            }
10870        }
10871
10872        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10873        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10874        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10875
10876        // Copy the derived override back to the parsed package, so that we can
10877        // update the package settings accordingly.
10878        pkg.cpuAbiOverride = cpuAbiOverride;
10879
10880        if (DEBUG_ABI_SELECTION) {
10881            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10882                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10883                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10884        }
10885
10886        // Push the derived path down into PackageSettings so we know what to
10887        // clean up at uninstall time.
10888        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10889
10890        if (DEBUG_ABI_SELECTION) {
10891            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10892                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10893                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10894        }
10895
10896        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10897        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10898            // We don't do this here during boot because we can do it all
10899            // at once after scanning all existing packages.
10900            //
10901            // We also do this *before* we perform dexopt on this package, so that
10902            // we can avoid redundant dexopts, and also to make sure we've got the
10903            // code and package path correct.
10904            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10905        }
10906
10907        if (mFactoryTest && pkg.requestedPermissions.contains(
10908                android.Manifest.permission.FACTORY_TEST)) {
10909            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10910        }
10911
10912        if (isSystemApp(pkg)) {
10913            pkgSetting.isOrphaned = true;
10914        }
10915
10916        // Take care of first install / last update times.
10917        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10918        if (currentTime != 0) {
10919            if (pkgSetting.firstInstallTime == 0) {
10920                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10921            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10922                pkgSetting.lastUpdateTime = currentTime;
10923            }
10924        } else if (pkgSetting.firstInstallTime == 0) {
10925            // We need *something*.  Take time time stamp of the file.
10926            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10927        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10928            if (scanFileTime != pkgSetting.timeStamp) {
10929                // A package on the system image has changed; consider this
10930                // to be an update.
10931                pkgSetting.lastUpdateTime = scanFileTime;
10932            }
10933        }
10934        pkgSetting.setTimeStamp(scanFileTime);
10935
10936        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10937            if (nonMutatedPs != null) {
10938                synchronized (mPackages) {
10939                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10940                }
10941            }
10942        } else {
10943            final int userId = user == null ? 0 : user.getIdentifier();
10944            // Modify state for the given package setting
10945            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10946                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10947            if (pkgSetting.getInstantApp(userId)) {
10948                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10949            }
10950        }
10951        return pkg;
10952    }
10953
10954    /**
10955     * Applies policy to the parsed package based upon the given policy flags.
10956     * Ensures the package is in a good state.
10957     * <p>
10958     * Implementation detail: This method must NOT have any side effect. It would
10959     * ideally be static, but, it requires locks to read system state.
10960     */
10961    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10962        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10963            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10964            if (pkg.applicationInfo.isDirectBootAware()) {
10965                // we're direct boot aware; set for all components
10966                for (PackageParser.Service s : pkg.services) {
10967                    s.info.encryptionAware = s.info.directBootAware = true;
10968                }
10969                for (PackageParser.Provider p : pkg.providers) {
10970                    p.info.encryptionAware = p.info.directBootAware = true;
10971                }
10972                for (PackageParser.Activity a : pkg.activities) {
10973                    a.info.encryptionAware = a.info.directBootAware = true;
10974                }
10975                for (PackageParser.Activity r : pkg.receivers) {
10976                    r.info.encryptionAware = r.info.directBootAware = true;
10977                }
10978            }
10979            if (compressedFileExists(pkg.baseCodePath)) {
10980                pkg.isStub = true;
10981            }
10982        } else {
10983            // Only allow system apps to be flagged as core apps.
10984            pkg.coreApp = false;
10985            // clear flags not applicable to regular apps
10986            pkg.applicationInfo.privateFlags &=
10987                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10988            pkg.applicationInfo.privateFlags &=
10989                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10990        }
10991        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10992
10993        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10994            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10995        }
10996
10997        if (!isSystemApp(pkg)) {
10998            // Only system apps can use these features.
10999            pkg.mOriginalPackages = null;
11000            pkg.mRealPackage = null;
11001            pkg.mAdoptPermissions = null;
11002        }
11003    }
11004
11005    /**
11006     * Asserts the parsed package is valid according to the given policy. If the
11007     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11008     * <p>
11009     * Implementation detail: This method must NOT have any side effects. It would
11010     * ideally be static, but, it requires locks to read system state.
11011     *
11012     * @throws PackageManagerException If the package fails any of the validation checks
11013     */
11014    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11015            throws PackageManagerException {
11016        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11017            assertCodePolicy(pkg);
11018        }
11019
11020        if (pkg.applicationInfo.getCodePath() == null ||
11021                pkg.applicationInfo.getResourcePath() == null) {
11022            // Bail out. The resource and code paths haven't been set.
11023            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11024                    "Code and resource paths haven't been set correctly");
11025        }
11026
11027        // Make sure we're not adding any bogus keyset info
11028        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11029        ksms.assertScannedPackageValid(pkg);
11030
11031        synchronized (mPackages) {
11032            // The special "android" package can only be defined once
11033            if (pkg.packageName.equals("android")) {
11034                if (mAndroidApplication != null) {
11035                    Slog.w(TAG, "*************************************************");
11036                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11037                    Slog.w(TAG, " codePath=" + pkg.codePath);
11038                    Slog.w(TAG, "*************************************************");
11039                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11040                            "Core android package being redefined.  Skipping.");
11041                }
11042            }
11043
11044            // A package name must be unique; don't allow duplicates
11045            if (mPackages.containsKey(pkg.packageName)) {
11046                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11047                        "Application package " + pkg.packageName
11048                        + " already installed.  Skipping duplicate.");
11049            }
11050
11051            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11052                // Static libs have a synthetic package name containing the version
11053                // but we still want the base name to be unique.
11054                if (mPackages.containsKey(pkg.manifestPackageName)) {
11055                    throw new PackageManagerException(
11056                            "Duplicate static shared lib provider package");
11057                }
11058
11059                // Static shared libraries should have at least O target SDK
11060                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11061                    throw new PackageManagerException(
11062                            "Packages declaring static-shared libs must target O SDK or higher");
11063                }
11064
11065                // Package declaring static a shared lib cannot be instant apps
11066                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11067                    throw new PackageManagerException(
11068                            "Packages declaring static-shared libs cannot be instant apps");
11069                }
11070
11071                // Package declaring static a shared lib cannot be renamed since the package
11072                // name is synthetic and apps can't code around package manager internals.
11073                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11074                    throw new PackageManagerException(
11075                            "Packages declaring static-shared libs cannot be renamed");
11076                }
11077
11078                // Package declaring static a shared lib cannot declare child packages
11079                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11080                    throw new PackageManagerException(
11081                            "Packages declaring static-shared libs cannot have child packages");
11082                }
11083
11084                // Package declaring static a shared lib cannot declare dynamic libs
11085                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11086                    throw new PackageManagerException(
11087                            "Packages declaring static-shared libs cannot declare dynamic libs");
11088                }
11089
11090                // Package declaring static a shared lib cannot declare shared users
11091                if (pkg.mSharedUserId != null) {
11092                    throw new PackageManagerException(
11093                            "Packages declaring static-shared libs cannot declare shared users");
11094                }
11095
11096                // Static shared libs cannot declare activities
11097                if (!pkg.activities.isEmpty()) {
11098                    throw new PackageManagerException(
11099                            "Static shared libs cannot declare activities");
11100                }
11101
11102                // Static shared libs cannot declare services
11103                if (!pkg.services.isEmpty()) {
11104                    throw new PackageManagerException(
11105                            "Static shared libs cannot declare services");
11106                }
11107
11108                // Static shared libs cannot declare providers
11109                if (!pkg.providers.isEmpty()) {
11110                    throw new PackageManagerException(
11111                            "Static shared libs cannot declare content providers");
11112                }
11113
11114                // Static shared libs cannot declare receivers
11115                if (!pkg.receivers.isEmpty()) {
11116                    throw new PackageManagerException(
11117                            "Static shared libs cannot declare broadcast receivers");
11118                }
11119
11120                // Static shared libs cannot declare permission groups
11121                if (!pkg.permissionGroups.isEmpty()) {
11122                    throw new PackageManagerException(
11123                            "Static shared libs cannot declare permission groups");
11124                }
11125
11126                // Static shared libs cannot declare permissions
11127                if (!pkg.permissions.isEmpty()) {
11128                    throw new PackageManagerException(
11129                            "Static shared libs cannot declare permissions");
11130                }
11131
11132                // Static shared libs cannot declare protected broadcasts
11133                if (pkg.protectedBroadcasts != null) {
11134                    throw new PackageManagerException(
11135                            "Static shared libs cannot declare protected broadcasts");
11136                }
11137
11138                // Static shared libs cannot be overlay targets
11139                if (pkg.mOverlayTarget != null) {
11140                    throw new PackageManagerException(
11141                            "Static shared libs cannot be overlay targets");
11142                }
11143
11144                // The version codes must be ordered as lib versions
11145                int minVersionCode = Integer.MIN_VALUE;
11146                int maxVersionCode = Integer.MAX_VALUE;
11147
11148                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11149                        pkg.staticSharedLibName);
11150                if (versionedLib != null) {
11151                    final int versionCount = versionedLib.size();
11152                    for (int i = 0; i < versionCount; i++) {
11153                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11154                        final int libVersionCode = libInfo.getDeclaringPackage()
11155                                .getVersionCode();
11156                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11157                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11158                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11159                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11160                        } else {
11161                            minVersionCode = maxVersionCode = libVersionCode;
11162                            break;
11163                        }
11164                    }
11165                }
11166                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11167                    throw new PackageManagerException("Static shared"
11168                            + " lib version codes must be ordered as lib versions");
11169                }
11170            }
11171
11172            // Only privileged apps and updated privileged apps can add child packages.
11173            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11174                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11175                    throw new PackageManagerException("Only privileged apps can add child "
11176                            + "packages. Ignoring package " + pkg.packageName);
11177                }
11178                final int childCount = pkg.childPackages.size();
11179                for (int i = 0; i < childCount; i++) {
11180                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11181                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11182                            childPkg.packageName)) {
11183                        throw new PackageManagerException("Can't override child of "
11184                                + "another disabled app. Ignoring package " + pkg.packageName);
11185                    }
11186                }
11187            }
11188
11189            // If we're only installing presumed-existing packages, require that the
11190            // scanned APK is both already known and at the path previously established
11191            // for it.  Previously unknown packages we pick up normally, but if we have an
11192            // a priori expectation about this package's install presence, enforce it.
11193            // With a singular exception for new system packages. When an OTA contains
11194            // a new system package, we allow the codepath to change from a system location
11195            // to the user-installed location. If we don't allow this change, any newer,
11196            // user-installed version of the application will be ignored.
11197            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11198                if (mExpectingBetter.containsKey(pkg.packageName)) {
11199                    logCriticalInfo(Log.WARN,
11200                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11201                } else {
11202                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11203                    if (known != null) {
11204                        if (DEBUG_PACKAGE_SCANNING) {
11205                            Log.d(TAG, "Examining " + pkg.codePath
11206                                    + " and requiring known paths " + known.codePathString
11207                                    + " & " + known.resourcePathString);
11208                        }
11209                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11210                                || !pkg.applicationInfo.getResourcePath().equals(
11211                                        known.resourcePathString)) {
11212                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11213                                    "Application package " + pkg.packageName
11214                                    + " found at " + pkg.applicationInfo.getCodePath()
11215                                    + " but expected at " + known.codePathString
11216                                    + "; ignoring.");
11217                        }
11218                    }
11219                }
11220            }
11221
11222            // Verify that this new package doesn't have any content providers
11223            // that conflict with existing packages.  Only do this if the
11224            // package isn't already installed, since we don't want to break
11225            // things that are installed.
11226            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11227                final int N = pkg.providers.size();
11228                int i;
11229                for (i=0; i<N; i++) {
11230                    PackageParser.Provider p = pkg.providers.get(i);
11231                    if (p.info.authority != null) {
11232                        String names[] = p.info.authority.split(";");
11233                        for (int j = 0; j < names.length; j++) {
11234                            if (mProvidersByAuthority.containsKey(names[j])) {
11235                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11236                                final String otherPackageName =
11237                                        ((other != null && other.getComponentName() != null) ?
11238                                                other.getComponentName().getPackageName() : "?");
11239                                throw new PackageManagerException(
11240                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11241                                        "Can't install because provider name " + names[j]
11242                                                + " (in package " + pkg.applicationInfo.packageName
11243                                                + ") is already used by " + otherPackageName);
11244                            }
11245                        }
11246                    }
11247                }
11248            }
11249        }
11250    }
11251
11252    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11253            int type, String declaringPackageName, int declaringVersionCode) {
11254        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11255        if (versionedLib == null) {
11256            versionedLib = new SparseArray<>();
11257            mSharedLibraries.put(name, versionedLib);
11258            if (type == SharedLibraryInfo.TYPE_STATIC) {
11259                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11260            }
11261        } else if (versionedLib.indexOfKey(version) >= 0) {
11262            return false;
11263        }
11264        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11265                version, type, declaringPackageName, declaringVersionCode);
11266        versionedLib.put(version, libEntry);
11267        return true;
11268    }
11269
11270    private boolean removeSharedLibraryLPw(String name, int version) {
11271        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11272        if (versionedLib == null) {
11273            return false;
11274        }
11275        final int libIdx = versionedLib.indexOfKey(version);
11276        if (libIdx < 0) {
11277            return false;
11278        }
11279        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11280        versionedLib.remove(version);
11281        if (versionedLib.size() <= 0) {
11282            mSharedLibraries.remove(name);
11283            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11284                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11285                        .getPackageName());
11286            }
11287        }
11288        return true;
11289    }
11290
11291    /**
11292     * Adds a scanned package to the system. When this method is finished, the package will
11293     * be available for query, resolution, etc...
11294     */
11295    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11296            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11297        final String pkgName = pkg.packageName;
11298        if (mCustomResolverComponentName != null &&
11299                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11300            setUpCustomResolverActivity(pkg);
11301        }
11302
11303        if (pkg.packageName.equals("android")) {
11304            synchronized (mPackages) {
11305                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11306                    // Set up information for our fall-back user intent resolution activity.
11307                    mPlatformPackage = pkg;
11308                    pkg.mVersionCode = mSdkVersion;
11309                    mAndroidApplication = pkg.applicationInfo;
11310                    if (!mResolverReplaced) {
11311                        mResolveActivity.applicationInfo = mAndroidApplication;
11312                        mResolveActivity.name = ResolverActivity.class.getName();
11313                        mResolveActivity.packageName = mAndroidApplication.packageName;
11314                        mResolveActivity.processName = "system:ui";
11315                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11316                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11317                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11318                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11319                        mResolveActivity.exported = true;
11320                        mResolveActivity.enabled = true;
11321                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11322                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11323                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11324                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11325                                | ActivityInfo.CONFIG_ORIENTATION
11326                                | ActivityInfo.CONFIG_KEYBOARD
11327                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11328                        mResolveInfo.activityInfo = mResolveActivity;
11329                        mResolveInfo.priority = 0;
11330                        mResolveInfo.preferredOrder = 0;
11331                        mResolveInfo.match = 0;
11332                        mResolveComponentName = new ComponentName(
11333                                mAndroidApplication.packageName, mResolveActivity.name);
11334                    }
11335                }
11336            }
11337        }
11338
11339        ArrayList<PackageParser.Package> clientLibPkgs = null;
11340        // writer
11341        synchronized (mPackages) {
11342            boolean hasStaticSharedLibs = false;
11343
11344            // Any app can add new static shared libraries
11345            if (pkg.staticSharedLibName != null) {
11346                // Static shared libs don't allow renaming as they have synthetic package
11347                // names to allow install of multiple versions, so use name from manifest.
11348                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11349                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11350                        pkg.manifestPackageName, pkg.mVersionCode)) {
11351                    hasStaticSharedLibs = true;
11352                } else {
11353                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11354                                + pkg.staticSharedLibName + " already exists; skipping");
11355                }
11356                // Static shared libs cannot be updated once installed since they
11357                // use synthetic package name which includes the version code, so
11358                // not need to update other packages's shared lib dependencies.
11359            }
11360
11361            if (!hasStaticSharedLibs
11362                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11363                // Only system apps can add new dynamic shared libraries.
11364                if (pkg.libraryNames != null) {
11365                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11366                        String name = pkg.libraryNames.get(i);
11367                        boolean allowed = false;
11368                        if (pkg.isUpdatedSystemApp()) {
11369                            // New library entries can only be added through the
11370                            // system image.  This is important to get rid of a lot
11371                            // of nasty edge cases: for example if we allowed a non-
11372                            // system update of the app to add a library, then uninstalling
11373                            // the update would make the library go away, and assumptions
11374                            // we made such as through app install filtering would now
11375                            // have allowed apps on the device which aren't compatible
11376                            // with it.  Better to just have the restriction here, be
11377                            // conservative, and create many fewer cases that can negatively
11378                            // impact the user experience.
11379                            final PackageSetting sysPs = mSettings
11380                                    .getDisabledSystemPkgLPr(pkg.packageName);
11381                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11382                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11383                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11384                                        allowed = true;
11385                                        break;
11386                                    }
11387                                }
11388                            }
11389                        } else {
11390                            allowed = true;
11391                        }
11392                        if (allowed) {
11393                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11394                                    SharedLibraryInfo.VERSION_UNDEFINED,
11395                                    SharedLibraryInfo.TYPE_DYNAMIC,
11396                                    pkg.packageName, pkg.mVersionCode)) {
11397                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11398                                        + name + " already exists; skipping");
11399                            }
11400                        } else {
11401                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11402                                    + name + " that is not declared on system image; skipping");
11403                        }
11404                    }
11405
11406                    if ((scanFlags & SCAN_BOOTING) == 0) {
11407                        // If we are not booting, we need to update any applications
11408                        // that are clients of our shared library.  If we are booting,
11409                        // this will all be done once the scan is complete.
11410                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11411                    }
11412                }
11413            }
11414        }
11415
11416        if ((scanFlags & SCAN_BOOTING) != 0) {
11417            // No apps can run during boot scan, so they don't need to be frozen
11418        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11419            // Caller asked to not kill app, so it's probably not frozen
11420        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11421            // Caller asked us to ignore frozen check for some reason; they
11422            // probably didn't know the package name
11423        } else {
11424            // We're doing major surgery on this package, so it better be frozen
11425            // right now to keep it from launching
11426            checkPackageFrozen(pkgName);
11427        }
11428
11429        // Also need to kill any apps that are dependent on the library.
11430        if (clientLibPkgs != null) {
11431            for (int i=0; i<clientLibPkgs.size(); i++) {
11432                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11433                killApplication(clientPkg.applicationInfo.packageName,
11434                        clientPkg.applicationInfo.uid, "update lib");
11435            }
11436        }
11437
11438        // writer
11439        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11440
11441        synchronized (mPackages) {
11442            // We don't expect installation to fail beyond this point
11443
11444            // Add the new setting to mSettings
11445            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11446            // Add the new setting to mPackages
11447            mPackages.put(pkg.applicationInfo.packageName, pkg);
11448            // Make sure we don't accidentally delete its data.
11449            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11450            while (iter.hasNext()) {
11451                PackageCleanItem item = iter.next();
11452                if (pkgName.equals(item.packageName)) {
11453                    iter.remove();
11454                }
11455            }
11456
11457            // Add the package's KeySets to the global KeySetManagerService
11458            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11459            ksms.addScannedPackageLPw(pkg);
11460
11461            int N = pkg.providers.size();
11462            StringBuilder r = null;
11463            int i;
11464            for (i=0; i<N; i++) {
11465                PackageParser.Provider p = pkg.providers.get(i);
11466                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11467                        p.info.processName);
11468                mProviders.addProvider(p);
11469                p.syncable = p.info.isSyncable;
11470                if (p.info.authority != null) {
11471                    String names[] = p.info.authority.split(";");
11472                    p.info.authority = null;
11473                    for (int j = 0; j < names.length; j++) {
11474                        if (j == 1 && p.syncable) {
11475                            // We only want the first authority for a provider to possibly be
11476                            // syncable, so if we already added this provider using a different
11477                            // authority clear the syncable flag. We copy the provider before
11478                            // changing it because the mProviders object contains a reference
11479                            // to a provider that we don't want to change.
11480                            // Only do this for the second authority since the resulting provider
11481                            // object can be the same for all future authorities for this provider.
11482                            p = new PackageParser.Provider(p);
11483                            p.syncable = false;
11484                        }
11485                        if (!mProvidersByAuthority.containsKey(names[j])) {
11486                            mProvidersByAuthority.put(names[j], p);
11487                            if (p.info.authority == null) {
11488                                p.info.authority = names[j];
11489                            } else {
11490                                p.info.authority = p.info.authority + ";" + names[j];
11491                            }
11492                            if (DEBUG_PACKAGE_SCANNING) {
11493                                if (chatty)
11494                                    Log.d(TAG, "Registered content provider: " + names[j]
11495                                            + ", className = " + p.info.name + ", isSyncable = "
11496                                            + p.info.isSyncable);
11497                            }
11498                        } else {
11499                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11500                            Slog.w(TAG, "Skipping provider name " + names[j] +
11501                                    " (in package " + pkg.applicationInfo.packageName +
11502                                    "): name already used by "
11503                                    + ((other != null && other.getComponentName() != null)
11504                                            ? other.getComponentName().getPackageName() : "?"));
11505                        }
11506                    }
11507                }
11508                if (chatty) {
11509                    if (r == null) {
11510                        r = new StringBuilder(256);
11511                    } else {
11512                        r.append(' ');
11513                    }
11514                    r.append(p.info.name);
11515                }
11516            }
11517            if (r != null) {
11518                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11519            }
11520
11521            N = pkg.services.size();
11522            r = null;
11523            for (i=0; i<N; i++) {
11524                PackageParser.Service s = pkg.services.get(i);
11525                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11526                        s.info.processName);
11527                mServices.addService(s);
11528                if (chatty) {
11529                    if (r == null) {
11530                        r = new StringBuilder(256);
11531                    } else {
11532                        r.append(' ');
11533                    }
11534                    r.append(s.info.name);
11535                }
11536            }
11537            if (r != null) {
11538                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11539            }
11540
11541            N = pkg.receivers.size();
11542            r = null;
11543            for (i=0; i<N; i++) {
11544                PackageParser.Activity a = pkg.receivers.get(i);
11545                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11546                        a.info.processName);
11547                mReceivers.addActivity(a, "receiver");
11548                if (chatty) {
11549                    if (r == null) {
11550                        r = new StringBuilder(256);
11551                    } else {
11552                        r.append(' ');
11553                    }
11554                    r.append(a.info.name);
11555                }
11556            }
11557            if (r != null) {
11558                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11559            }
11560
11561            N = pkg.activities.size();
11562            r = null;
11563            for (i=0; i<N; i++) {
11564                PackageParser.Activity a = pkg.activities.get(i);
11565                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11566                        a.info.processName);
11567                mActivities.addActivity(a, "activity");
11568                if (chatty) {
11569                    if (r == null) {
11570                        r = new StringBuilder(256);
11571                    } else {
11572                        r.append(' ');
11573                    }
11574                    r.append(a.info.name);
11575                }
11576            }
11577            if (r != null) {
11578                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11579            }
11580
11581            N = pkg.permissionGroups.size();
11582            r = null;
11583            for (i=0; i<N; i++) {
11584                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11585                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11586                final String curPackageName = cur == null ? null : cur.info.packageName;
11587                // Dont allow ephemeral apps to define new permission groups.
11588                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11589                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11590                            + pg.info.packageName
11591                            + " ignored: instant apps cannot define new permission groups.");
11592                    continue;
11593                }
11594                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11595                if (cur == null || isPackageUpdate) {
11596                    mPermissionGroups.put(pg.info.name, pg);
11597                    if (chatty) {
11598                        if (r == null) {
11599                            r = new StringBuilder(256);
11600                        } else {
11601                            r.append(' ');
11602                        }
11603                        if (isPackageUpdate) {
11604                            r.append("UPD:");
11605                        }
11606                        r.append(pg.info.name);
11607                    }
11608                } else {
11609                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11610                            + pg.info.packageName + " ignored: original from "
11611                            + cur.info.packageName);
11612                    if (chatty) {
11613                        if (r == null) {
11614                            r = new StringBuilder(256);
11615                        } else {
11616                            r.append(' ');
11617                        }
11618                        r.append("DUP:");
11619                        r.append(pg.info.name);
11620                    }
11621                }
11622            }
11623            if (r != null) {
11624                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11625            }
11626
11627            N = pkg.permissions.size();
11628            r = null;
11629            for (i=0; i<N; i++) {
11630                PackageParser.Permission p = pkg.permissions.get(i);
11631
11632                // Dont allow ephemeral apps to define new permissions.
11633                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11634                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11635                            + p.info.packageName
11636                            + " ignored: instant apps cannot define new permissions.");
11637                    continue;
11638                }
11639
11640                // Assume by default that we did not install this permission into the system.
11641                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11642
11643                // Now that permission groups have a special meaning, we ignore permission
11644                // groups for legacy apps to prevent unexpected behavior. In particular,
11645                // permissions for one app being granted to someone just because they happen
11646                // to be in a group defined by another app (before this had no implications).
11647                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11648                    p.group = mPermissionGroups.get(p.info.group);
11649                    // Warn for a permission in an unknown group.
11650                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11651                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11652                                + p.info.packageName + " in an unknown group " + p.info.group);
11653                    }
11654                }
11655
11656                ArrayMap<String, BasePermission> permissionMap =
11657                        p.tree ? mSettings.mPermissionTrees
11658                                : mSettings.mPermissions;
11659                BasePermission bp = permissionMap.get(p.info.name);
11660
11661                // Allow system apps to redefine non-system permissions
11662                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11663                    final boolean currentOwnerIsSystem = (bp.perm != null
11664                            && isSystemApp(bp.perm.owner));
11665                    if (isSystemApp(p.owner)) {
11666                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11667                            // It's a built-in permission and no owner, take ownership now
11668                            bp.packageSetting = pkgSetting;
11669                            bp.perm = p;
11670                            bp.uid = pkg.applicationInfo.uid;
11671                            bp.sourcePackage = p.info.packageName;
11672                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11673                        } else if (!currentOwnerIsSystem) {
11674                            String msg = "New decl " + p.owner + " of permission  "
11675                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11676                            reportSettingsProblem(Log.WARN, msg);
11677                            bp = null;
11678                        }
11679                    }
11680                }
11681
11682                if (bp == null) {
11683                    bp = new BasePermission(p.info.name, p.info.packageName,
11684                            BasePermission.TYPE_NORMAL);
11685                    permissionMap.put(p.info.name, bp);
11686                }
11687
11688                if (bp.perm == null) {
11689                    if (bp.sourcePackage == null
11690                            || bp.sourcePackage.equals(p.info.packageName)) {
11691                        BasePermission tree = findPermissionTreeLP(p.info.name);
11692                        if (tree == null
11693                                || tree.sourcePackage.equals(p.info.packageName)) {
11694                            bp.packageSetting = pkgSetting;
11695                            bp.perm = p;
11696                            bp.uid = pkg.applicationInfo.uid;
11697                            bp.sourcePackage = p.info.packageName;
11698                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11699                            if (chatty) {
11700                                if (r == null) {
11701                                    r = new StringBuilder(256);
11702                                } else {
11703                                    r.append(' ');
11704                                }
11705                                r.append(p.info.name);
11706                            }
11707                        } else {
11708                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11709                                    + p.info.packageName + " ignored: base tree "
11710                                    + tree.name + " is from package "
11711                                    + tree.sourcePackage);
11712                        }
11713                    } else {
11714                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11715                                + p.info.packageName + " ignored: original from "
11716                                + bp.sourcePackage);
11717                    }
11718                } else if (chatty) {
11719                    if (r == null) {
11720                        r = new StringBuilder(256);
11721                    } else {
11722                        r.append(' ');
11723                    }
11724                    r.append("DUP:");
11725                    r.append(p.info.name);
11726                }
11727                if (bp.perm == p) {
11728                    bp.protectionLevel = p.info.protectionLevel;
11729                }
11730            }
11731
11732            if (r != null) {
11733                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11734            }
11735
11736            N = pkg.instrumentation.size();
11737            r = null;
11738            for (i=0; i<N; i++) {
11739                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11740                a.info.packageName = pkg.applicationInfo.packageName;
11741                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11742                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11743                a.info.splitNames = pkg.splitNames;
11744                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11745                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11746                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11747                a.info.dataDir = pkg.applicationInfo.dataDir;
11748                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11749                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11750                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11751                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11752                mInstrumentation.put(a.getComponentName(), a);
11753                if (chatty) {
11754                    if (r == null) {
11755                        r = new StringBuilder(256);
11756                    } else {
11757                        r.append(' ');
11758                    }
11759                    r.append(a.info.name);
11760                }
11761            }
11762            if (r != null) {
11763                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11764            }
11765
11766            if (pkg.protectedBroadcasts != null) {
11767                N = pkg.protectedBroadcasts.size();
11768                synchronized (mProtectedBroadcasts) {
11769                    for (i = 0; i < N; i++) {
11770                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11771                    }
11772                }
11773            }
11774        }
11775
11776        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11777    }
11778
11779    /**
11780     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11781     * is derived purely on the basis of the contents of {@code scanFile} and
11782     * {@code cpuAbiOverride}.
11783     *
11784     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11785     */
11786    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11787                                 String cpuAbiOverride, boolean extractLibs,
11788                                 File appLib32InstallDir)
11789            throws PackageManagerException {
11790        // Give ourselves some initial paths; we'll come back for another
11791        // pass once we've determined ABI below.
11792        setNativeLibraryPaths(pkg, appLib32InstallDir);
11793
11794        // We would never need to extract libs for forward-locked and external packages,
11795        // since the container service will do it for us. We shouldn't attempt to
11796        // extract libs from system app when it was not updated.
11797        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11798                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11799            extractLibs = false;
11800        }
11801
11802        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11803        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11804
11805        NativeLibraryHelper.Handle handle = null;
11806        try {
11807            handle = NativeLibraryHelper.Handle.create(pkg);
11808            // TODO(multiArch): This can be null for apps that didn't go through the
11809            // usual installation process. We can calculate it again, like we
11810            // do during install time.
11811            //
11812            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11813            // unnecessary.
11814            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11815
11816            // Null out the abis so that they can be recalculated.
11817            pkg.applicationInfo.primaryCpuAbi = null;
11818            pkg.applicationInfo.secondaryCpuAbi = null;
11819            if (isMultiArch(pkg.applicationInfo)) {
11820                // Warn if we've set an abiOverride for multi-lib packages..
11821                // By definition, we need to copy both 32 and 64 bit libraries for
11822                // such packages.
11823                if (pkg.cpuAbiOverride != null
11824                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11825                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11826                }
11827
11828                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11829                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11830                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11831                    if (extractLibs) {
11832                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11833                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11834                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11835                                useIsaSpecificSubdirs);
11836                    } else {
11837                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11838                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11839                    }
11840                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11841                }
11842
11843                // Shared library native code should be in the APK zip aligned
11844                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11845                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11846                            "Shared library native lib extraction not supported");
11847                }
11848
11849                maybeThrowExceptionForMultiArchCopy(
11850                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11851
11852                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11853                    if (extractLibs) {
11854                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11855                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11856                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11857                                useIsaSpecificSubdirs);
11858                    } else {
11859                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11860                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11861                    }
11862                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11863                }
11864
11865                maybeThrowExceptionForMultiArchCopy(
11866                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11867
11868                if (abi64 >= 0) {
11869                    // Shared library native libs should be in the APK zip aligned
11870                    if (extractLibs && pkg.isLibrary()) {
11871                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11872                                "Shared library native lib extraction not supported");
11873                    }
11874                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11875                }
11876
11877                if (abi32 >= 0) {
11878                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11879                    if (abi64 >= 0) {
11880                        if (pkg.use32bitAbi) {
11881                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11882                            pkg.applicationInfo.primaryCpuAbi = abi;
11883                        } else {
11884                            pkg.applicationInfo.secondaryCpuAbi = abi;
11885                        }
11886                    } else {
11887                        pkg.applicationInfo.primaryCpuAbi = abi;
11888                    }
11889                }
11890            } else {
11891                String[] abiList = (cpuAbiOverride != null) ?
11892                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11893
11894                // Enable gross and lame hacks for apps that are built with old
11895                // SDK tools. We must scan their APKs for renderscript bitcode and
11896                // not launch them if it's present. Don't bother checking on devices
11897                // that don't have 64 bit support.
11898                boolean needsRenderScriptOverride = false;
11899                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11900                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11901                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11902                    needsRenderScriptOverride = true;
11903                }
11904
11905                final int copyRet;
11906                if (extractLibs) {
11907                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11908                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11909                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11910                } else {
11911                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11912                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11913                }
11914                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11915
11916                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11917                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11918                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11919                }
11920
11921                if (copyRet >= 0) {
11922                    // Shared libraries that have native libs must be multi-architecture
11923                    if (pkg.isLibrary()) {
11924                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11925                                "Shared library with native libs must be multiarch");
11926                    }
11927                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11928                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11929                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11930                } else if (needsRenderScriptOverride) {
11931                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11932                }
11933            }
11934        } catch (IOException ioe) {
11935            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11936        } finally {
11937            IoUtils.closeQuietly(handle);
11938        }
11939
11940        // Now that we've calculated the ABIs and determined if it's an internal app,
11941        // we will go ahead and populate the nativeLibraryPath.
11942        setNativeLibraryPaths(pkg, appLib32InstallDir);
11943    }
11944
11945    /**
11946     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11947     * i.e, so that all packages can be run inside a single process if required.
11948     *
11949     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11950     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11951     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11952     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11953     * updating a package that belongs to a shared user.
11954     *
11955     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11956     * adds unnecessary complexity.
11957     */
11958    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11959            PackageParser.Package scannedPackage) {
11960        String requiredInstructionSet = null;
11961        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11962            requiredInstructionSet = VMRuntime.getInstructionSet(
11963                     scannedPackage.applicationInfo.primaryCpuAbi);
11964        }
11965
11966        PackageSetting requirer = null;
11967        for (PackageSetting ps : packagesForUser) {
11968            // If packagesForUser contains scannedPackage, we skip it. This will happen
11969            // when scannedPackage is an update of an existing package. Without this check,
11970            // we will never be able to change the ABI of any package belonging to a shared
11971            // user, even if it's compatible with other packages.
11972            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11973                if (ps.primaryCpuAbiString == null) {
11974                    continue;
11975                }
11976
11977                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11978                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11979                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11980                    // this but there's not much we can do.
11981                    String errorMessage = "Instruction set mismatch, "
11982                            + ((requirer == null) ? "[caller]" : requirer)
11983                            + " requires " + requiredInstructionSet + " whereas " + ps
11984                            + " requires " + instructionSet;
11985                    Slog.w(TAG, errorMessage);
11986                }
11987
11988                if (requiredInstructionSet == null) {
11989                    requiredInstructionSet = instructionSet;
11990                    requirer = ps;
11991                }
11992            }
11993        }
11994
11995        if (requiredInstructionSet != null) {
11996            String adjustedAbi;
11997            if (requirer != null) {
11998                // requirer != null implies that either scannedPackage was null or that scannedPackage
11999                // did not require an ABI, in which case we have to adjust scannedPackage to match
12000                // the ABI of the set (which is the same as requirer's ABI)
12001                adjustedAbi = requirer.primaryCpuAbiString;
12002                if (scannedPackage != null) {
12003                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12004                }
12005            } else {
12006                // requirer == null implies that we're updating all ABIs in the set to
12007                // match scannedPackage.
12008                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12009            }
12010
12011            for (PackageSetting ps : packagesForUser) {
12012                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12013                    if (ps.primaryCpuAbiString != null) {
12014                        continue;
12015                    }
12016
12017                    ps.primaryCpuAbiString = adjustedAbi;
12018                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12019                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12020                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12021                        if (DEBUG_ABI_SELECTION) {
12022                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12023                                    + " (requirer="
12024                                    + (requirer != null ? requirer.pkg : "null")
12025                                    + ", scannedPackage="
12026                                    + (scannedPackage != null ? scannedPackage : "null")
12027                                    + ")");
12028                        }
12029                        try {
12030                            mInstaller.rmdex(ps.codePathString,
12031                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12032                        } catch (InstallerException ignored) {
12033                        }
12034                    }
12035                }
12036            }
12037        }
12038    }
12039
12040    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12041        synchronized (mPackages) {
12042            mResolverReplaced = true;
12043            // Set up information for custom user intent resolution activity.
12044            mResolveActivity.applicationInfo = pkg.applicationInfo;
12045            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12046            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12047            mResolveActivity.processName = pkg.applicationInfo.packageName;
12048            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12049            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12050                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12051            mResolveActivity.theme = 0;
12052            mResolveActivity.exported = true;
12053            mResolveActivity.enabled = true;
12054            mResolveInfo.activityInfo = mResolveActivity;
12055            mResolveInfo.priority = 0;
12056            mResolveInfo.preferredOrder = 0;
12057            mResolveInfo.match = 0;
12058            mResolveComponentName = mCustomResolverComponentName;
12059            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12060                    mResolveComponentName);
12061        }
12062    }
12063
12064    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12065        if (installerActivity == null) {
12066            if (DEBUG_EPHEMERAL) {
12067                Slog.d(TAG, "Clear ephemeral installer activity");
12068            }
12069            mInstantAppInstallerActivity = null;
12070            return;
12071        }
12072
12073        if (DEBUG_EPHEMERAL) {
12074            Slog.d(TAG, "Set ephemeral installer activity: "
12075                    + installerActivity.getComponentName());
12076        }
12077        // Set up information for ephemeral installer activity
12078        mInstantAppInstallerActivity = installerActivity;
12079        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12080                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12081        mInstantAppInstallerActivity.exported = true;
12082        mInstantAppInstallerActivity.enabled = true;
12083        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12084        mInstantAppInstallerInfo.priority = 0;
12085        mInstantAppInstallerInfo.preferredOrder = 1;
12086        mInstantAppInstallerInfo.isDefault = true;
12087        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12088                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12089    }
12090
12091    private static String calculateBundledApkRoot(final String codePathString) {
12092        final File codePath = new File(codePathString);
12093        final File codeRoot;
12094        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12095            codeRoot = Environment.getRootDirectory();
12096        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12097            codeRoot = Environment.getOemDirectory();
12098        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12099            codeRoot = Environment.getVendorDirectory();
12100        } else {
12101            // Unrecognized code path; take its top real segment as the apk root:
12102            // e.g. /something/app/blah.apk => /something
12103            try {
12104                File f = codePath.getCanonicalFile();
12105                File parent = f.getParentFile();    // non-null because codePath is a file
12106                File tmp;
12107                while ((tmp = parent.getParentFile()) != null) {
12108                    f = parent;
12109                    parent = tmp;
12110                }
12111                codeRoot = f;
12112                Slog.w(TAG, "Unrecognized code path "
12113                        + codePath + " - using " + codeRoot);
12114            } catch (IOException e) {
12115                // Can't canonicalize the code path -- shenanigans?
12116                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12117                return Environment.getRootDirectory().getPath();
12118            }
12119        }
12120        return codeRoot.getPath();
12121    }
12122
12123    /**
12124     * Derive and set the location of native libraries for the given package,
12125     * which varies depending on where and how the package was installed.
12126     */
12127    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12128        final ApplicationInfo info = pkg.applicationInfo;
12129        final String codePath = pkg.codePath;
12130        final File codeFile = new File(codePath);
12131        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12132        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12133
12134        info.nativeLibraryRootDir = null;
12135        info.nativeLibraryRootRequiresIsa = false;
12136        info.nativeLibraryDir = null;
12137        info.secondaryNativeLibraryDir = null;
12138
12139        if (isApkFile(codeFile)) {
12140            // Monolithic install
12141            if (bundledApp) {
12142                // If "/system/lib64/apkname" exists, assume that is the per-package
12143                // native library directory to use; otherwise use "/system/lib/apkname".
12144                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12145                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12146                        getPrimaryInstructionSet(info));
12147
12148                // This is a bundled system app so choose the path based on the ABI.
12149                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12150                // is just the default path.
12151                final String apkName = deriveCodePathName(codePath);
12152                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12153                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12154                        apkName).getAbsolutePath();
12155
12156                if (info.secondaryCpuAbi != null) {
12157                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12158                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12159                            secondaryLibDir, apkName).getAbsolutePath();
12160                }
12161            } else if (asecApp) {
12162                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12163                        .getAbsolutePath();
12164            } else {
12165                final String apkName = deriveCodePathName(codePath);
12166                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12167                        .getAbsolutePath();
12168            }
12169
12170            info.nativeLibraryRootRequiresIsa = false;
12171            info.nativeLibraryDir = info.nativeLibraryRootDir;
12172        } else {
12173            // Cluster install
12174            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12175            info.nativeLibraryRootRequiresIsa = true;
12176
12177            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12178                    getPrimaryInstructionSet(info)).getAbsolutePath();
12179
12180            if (info.secondaryCpuAbi != null) {
12181                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12182                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12183            }
12184        }
12185    }
12186
12187    /**
12188     * Calculate the abis and roots for a bundled app. These can uniquely
12189     * be determined from the contents of the system partition, i.e whether
12190     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12191     * of this information, and instead assume that the system was built
12192     * sensibly.
12193     */
12194    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12195                                           PackageSetting pkgSetting) {
12196        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12197
12198        // If "/system/lib64/apkname" exists, assume that is the per-package
12199        // native library directory to use; otherwise use "/system/lib/apkname".
12200        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12201        setBundledAppAbi(pkg, apkRoot, apkName);
12202        // pkgSetting might be null during rescan following uninstall of updates
12203        // to a bundled app, so accommodate that possibility.  The settings in
12204        // that case will be established later from the parsed package.
12205        //
12206        // If the settings aren't null, sync them up with what we've just derived.
12207        // note that apkRoot isn't stored in the package settings.
12208        if (pkgSetting != null) {
12209            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12210            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12211        }
12212    }
12213
12214    /**
12215     * Deduces the ABI of a bundled app and sets the relevant fields on the
12216     * parsed pkg object.
12217     *
12218     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12219     *        under which system libraries are installed.
12220     * @param apkName the name of the installed package.
12221     */
12222    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12223        final File codeFile = new File(pkg.codePath);
12224
12225        final boolean has64BitLibs;
12226        final boolean has32BitLibs;
12227        if (isApkFile(codeFile)) {
12228            // Monolithic install
12229            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12230            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12231        } else {
12232            // Cluster install
12233            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12234            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12235                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12236                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12237                has64BitLibs = (new File(rootDir, isa)).exists();
12238            } else {
12239                has64BitLibs = false;
12240            }
12241            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12242                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12243                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12244                has32BitLibs = (new File(rootDir, isa)).exists();
12245            } else {
12246                has32BitLibs = false;
12247            }
12248        }
12249
12250        if (has64BitLibs && !has32BitLibs) {
12251            // The package has 64 bit libs, but not 32 bit libs. Its primary
12252            // ABI should be 64 bit. We can safely assume here that the bundled
12253            // native libraries correspond to the most preferred ABI in the list.
12254
12255            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12256            pkg.applicationInfo.secondaryCpuAbi = null;
12257        } else if (has32BitLibs && !has64BitLibs) {
12258            // The package has 32 bit libs but not 64 bit libs. Its primary
12259            // ABI should be 32 bit.
12260
12261            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12262            pkg.applicationInfo.secondaryCpuAbi = null;
12263        } else if (has32BitLibs && has64BitLibs) {
12264            // The application has both 64 and 32 bit bundled libraries. We check
12265            // here that the app declares multiArch support, and warn if it doesn't.
12266            //
12267            // We will be lenient here and record both ABIs. The primary will be the
12268            // ABI that's higher on the list, i.e, a device that's configured to prefer
12269            // 64 bit apps will see a 64 bit primary ABI,
12270
12271            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12272                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12273            }
12274
12275            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12276                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12277                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12278            } else {
12279                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12280                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12281            }
12282        } else {
12283            pkg.applicationInfo.primaryCpuAbi = null;
12284            pkg.applicationInfo.secondaryCpuAbi = null;
12285        }
12286    }
12287
12288    private void killApplication(String pkgName, int appId, String reason) {
12289        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12290    }
12291
12292    private void killApplication(String pkgName, int appId, int userId, String reason) {
12293        // Request the ActivityManager to kill the process(only for existing packages)
12294        // so that we do not end up in a confused state while the user is still using the older
12295        // version of the application while the new one gets installed.
12296        final long token = Binder.clearCallingIdentity();
12297        try {
12298            IActivityManager am = ActivityManager.getService();
12299            if (am != null) {
12300                try {
12301                    am.killApplication(pkgName, appId, userId, reason);
12302                } catch (RemoteException e) {
12303                }
12304            }
12305        } finally {
12306            Binder.restoreCallingIdentity(token);
12307        }
12308    }
12309
12310    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12311        // Remove the parent package setting
12312        PackageSetting ps = (PackageSetting) pkg.mExtras;
12313        if (ps != null) {
12314            removePackageLI(ps, chatty);
12315        }
12316        // Remove the child package setting
12317        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12318        for (int i = 0; i < childCount; i++) {
12319            PackageParser.Package childPkg = pkg.childPackages.get(i);
12320            ps = (PackageSetting) childPkg.mExtras;
12321            if (ps != null) {
12322                removePackageLI(ps, chatty);
12323            }
12324        }
12325    }
12326
12327    void removePackageLI(PackageSetting ps, boolean chatty) {
12328        if (DEBUG_INSTALL) {
12329            if (chatty)
12330                Log.d(TAG, "Removing package " + ps.name);
12331        }
12332
12333        // writer
12334        synchronized (mPackages) {
12335            mPackages.remove(ps.name);
12336            final PackageParser.Package pkg = ps.pkg;
12337            if (pkg != null) {
12338                cleanPackageDataStructuresLILPw(pkg, chatty);
12339            }
12340        }
12341    }
12342
12343    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12344        if (DEBUG_INSTALL) {
12345            if (chatty)
12346                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12347        }
12348
12349        // writer
12350        synchronized (mPackages) {
12351            // Remove the parent package
12352            mPackages.remove(pkg.applicationInfo.packageName);
12353            cleanPackageDataStructuresLILPw(pkg, chatty);
12354
12355            // Remove the child packages
12356            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12357            for (int i = 0; i < childCount; i++) {
12358                PackageParser.Package childPkg = pkg.childPackages.get(i);
12359                mPackages.remove(childPkg.applicationInfo.packageName);
12360                cleanPackageDataStructuresLILPw(childPkg, chatty);
12361            }
12362        }
12363    }
12364
12365    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12366        int N = pkg.providers.size();
12367        StringBuilder r = null;
12368        int i;
12369        for (i=0; i<N; i++) {
12370            PackageParser.Provider p = pkg.providers.get(i);
12371            mProviders.removeProvider(p);
12372            if (p.info.authority == null) {
12373
12374                /* There was another ContentProvider with this authority when
12375                 * this app was installed so this authority is null,
12376                 * Ignore it as we don't have to unregister the provider.
12377                 */
12378                continue;
12379            }
12380            String names[] = p.info.authority.split(";");
12381            for (int j = 0; j < names.length; j++) {
12382                if (mProvidersByAuthority.get(names[j]) == p) {
12383                    mProvidersByAuthority.remove(names[j]);
12384                    if (DEBUG_REMOVE) {
12385                        if (chatty)
12386                            Log.d(TAG, "Unregistered content provider: " + names[j]
12387                                    + ", className = " + p.info.name + ", isSyncable = "
12388                                    + p.info.isSyncable);
12389                    }
12390                }
12391            }
12392            if (DEBUG_REMOVE && chatty) {
12393                if (r == null) {
12394                    r = new StringBuilder(256);
12395                } else {
12396                    r.append(' ');
12397                }
12398                r.append(p.info.name);
12399            }
12400        }
12401        if (r != null) {
12402            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12403        }
12404
12405        N = pkg.services.size();
12406        r = null;
12407        for (i=0; i<N; i++) {
12408            PackageParser.Service s = pkg.services.get(i);
12409            mServices.removeService(s);
12410            if (chatty) {
12411                if (r == null) {
12412                    r = new StringBuilder(256);
12413                } else {
12414                    r.append(' ');
12415                }
12416                r.append(s.info.name);
12417            }
12418        }
12419        if (r != null) {
12420            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12421        }
12422
12423        N = pkg.receivers.size();
12424        r = null;
12425        for (i=0; i<N; i++) {
12426            PackageParser.Activity a = pkg.receivers.get(i);
12427            mReceivers.removeActivity(a, "receiver");
12428            if (DEBUG_REMOVE && chatty) {
12429                if (r == null) {
12430                    r = new StringBuilder(256);
12431                } else {
12432                    r.append(' ');
12433                }
12434                r.append(a.info.name);
12435            }
12436        }
12437        if (r != null) {
12438            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12439        }
12440
12441        N = pkg.activities.size();
12442        r = null;
12443        for (i=0; i<N; i++) {
12444            PackageParser.Activity a = pkg.activities.get(i);
12445            mActivities.removeActivity(a, "activity");
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, "  Activities: " + r);
12457        }
12458
12459        N = pkg.permissions.size();
12460        r = null;
12461        for (i=0; i<N; i++) {
12462            PackageParser.Permission p = pkg.permissions.get(i);
12463            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12464            if (bp == null) {
12465                bp = mSettings.mPermissionTrees.get(p.info.name);
12466            }
12467            if (bp != null && bp.perm == p) {
12468                bp.perm = null;
12469                if (DEBUG_REMOVE && chatty) {
12470                    if (r == null) {
12471                        r = new StringBuilder(256);
12472                    } else {
12473                        r.append(' ');
12474                    }
12475                    r.append(p.info.name);
12476                }
12477            }
12478            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12479                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12480                if (appOpPkgs != null) {
12481                    appOpPkgs.remove(pkg.packageName);
12482                }
12483            }
12484        }
12485        if (r != null) {
12486            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12487        }
12488
12489        N = pkg.requestedPermissions.size();
12490        r = null;
12491        for (i=0; i<N; i++) {
12492            String perm = pkg.requestedPermissions.get(i);
12493            BasePermission bp = mSettings.mPermissions.get(perm);
12494            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12495                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12496                if (appOpPkgs != null) {
12497                    appOpPkgs.remove(pkg.packageName);
12498                    if (appOpPkgs.isEmpty()) {
12499                        mAppOpPermissionPackages.remove(perm);
12500                    }
12501                }
12502            }
12503        }
12504        if (r != null) {
12505            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12506        }
12507
12508        N = pkg.instrumentation.size();
12509        r = null;
12510        for (i=0; i<N; i++) {
12511            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12512            mInstrumentation.remove(a.getComponentName());
12513            if (DEBUG_REMOVE && chatty) {
12514                if (r == null) {
12515                    r = new StringBuilder(256);
12516                } else {
12517                    r.append(' ');
12518                }
12519                r.append(a.info.name);
12520            }
12521        }
12522        if (r != null) {
12523            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12524        }
12525
12526        r = null;
12527        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12528            // Only system apps can hold shared libraries.
12529            if (pkg.libraryNames != null) {
12530                for (i = 0; i < pkg.libraryNames.size(); i++) {
12531                    String name = pkg.libraryNames.get(i);
12532                    if (removeSharedLibraryLPw(name, 0)) {
12533                        if (DEBUG_REMOVE && chatty) {
12534                            if (r == null) {
12535                                r = new StringBuilder(256);
12536                            } else {
12537                                r.append(' ');
12538                            }
12539                            r.append(name);
12540                        }
12541                    }
12542                }
12543            }
12544        }
12545
12546        r = null;
12547
12548        // Any package can hold static shared libraries.
12549        if (pkg.staticSharedLibName != null) {
12550            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12551                if (DEBUG_REMOVE && chatty) {
12552                    if (r == null) {
12553                        r = new StringBuilder(256);
12554                    } else {
12555                        r.append(' ');
12556                    }
12557                    r.append(pkg.staticSharedLibName);
12558                }
12559            }
12560        }
12561
12562        if (r != null) {
12563            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12564        }
12565    }
12566
12567    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12568        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12569            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12570                return true;
12571            }
12572        }
12573        return false;
12574    }
12575
12576    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12577    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12578    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12579
12580    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12581        // Update the parent permissions
12582        updatePermissionsLPw(pkg.packageName, pkg, flags);
12583        // Update the child permissions
12584        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12585        for (int i = 0; i < childCount; i++) {
12586            PackageParser.Package childPkg = pkg.childPackages.get(i);
12587            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12588        }
12589    }
12590
12591    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12592            int flags) {
12593        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12594        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12595    }
12596
12597    private void updatePermissionsLPw(String changingPkg,
12598            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12599        // Make sure there are no dangling permission trees.
12600        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12601        while (it.hasNext()) {
12602            final BasePermission bp = it.next();
12603            if (bp.packageSetting == null) {
12604                // We may not yet have parsed the package, so just see if
12605                // we still know about its settings.
12606                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12607            }
12608            if (bp.packageSetting == null) {
12609                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12610                        + " from package " + bp.sourcePackage);
12611                it.remove();
12612            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12613                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12614                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12615                            + " from package " + bp.sourcePackage);
12616                    flags |= UPDATE_PERMISSIONS_ALL;
12617                    it.remove();
12618                }
12619            }
12620        }
12621
12622        // Make sure all dynamic permissions have been assigned to a package,
12623        // and make sure there are no dangling permissions.
12624        it = mSettings.mPermissions.values().iterator();
12625        while (it.hasNext()) {
12626            final BasePermission bp = it.next();
12627            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12628                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12629                        + bp.name + " pkg=" + bp.sourcePackage
12630                        + " info=" + bp.pendingInfo);
12631                if (bp.packageSetting == null && bp.pendingInfo != null) {
12632                    final BasePermission tree = findPermissionTreeLP(bp.name);
12633                    if (tree != null && tree.perm != null) {
12634                        bp.packageSetting = tree.packageSetting;
12635                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12636                                new PermissionInfo(bp.pendingInfo));
12637                        bp.perm.info.packageName = tree.perm.info.packageName;
12638                        bp.perm.info.name = bp.name;
12639                        bp.uid = tree.uid;
12640                    }
12641                }
12642            }
12643            if (bp.packageSetting == null) {
12644                // We may not yet have parsed the package, so just see if
12645                // we still know about its settings.
12646                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12647            }
12648            if (bp.packageSetting == null) {
12649                Slog.w(TAG, "Removing dangling permission: " + bp.name
12650                        + " from package " + bp.sourcePackage);
12651                it.remove();
12652            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12653                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12654                    Slog.i(TAG, "Removing old permission: " + bp.name
12655                            + " from package " + bp.sourcePackage);
12656                    flags |= UPDATE_PERMISSIONS_ALL;
12657                    it.remove();
12658                }
12659            }
12660        }
12661
12662        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12663        // Now update the permissions for all packages, in particular
12664        // replace the granted permissions of the system packages.
12665        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12666            for (PackageParser.Package pkg : mPackages.values()) {
12667                if (pkg != pkgInfo) {
12668                    // Only replace for packages on requested volume
12669                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12670                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12671                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12672                    grantPermissionsLPw(pkg, replace, changingPkg);
12673                }
12674            }
12675        }
12676
12677        if (pkgInfo != null) {
12678            // Only replace for packages on requested volume
12679            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12680            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12681                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12682            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12683        }
12684        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12685    }
12686
12687    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12688            String packageOfInterest) {
12689        // IMPORTANT: There are two types of permissions: install and runtime.
12690        // Install time permissions are granted when the app is installed to
12691        // all device users and users added in the future. Runtime permissions
12692        // are granted at runtime explicitly to specific users. Normal and signature
12693        // protected permissions are install time permissions. Dangerous permissions
12694        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12695        // otherwise they are runtime permissions. This function does not manage
12696        // runtime permissions except for the case an app targeting Lollipop MR1
12697        // being upgraded to target a newer SDK, in which case dangerous permissions
12698        // are transformed from install time to runtime ones.
12699
12700        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12701        if (ps == null) {
12702            return;
12703        }
12704
12705        PermissionsState permissionsState = ps.getPermissionsState();
12706        PermissionsState origPermissions = permissionsState;
12707
12708        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12709
12710        boolean runtimePermissionsRevoked = false;
12711        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12712
12713        boolean changedInstallPermission = false;
12714
12715        if (replace) {
12716            ps.installPermissionsFixed = false;
12717            if (!ps.isSharedUser()) {
12718                origPermissions = new PermissionsState(permissionsState);
12719                permissionsState.reset();
12720            } else {
12721                // We need to know only about runtime permission changes since the
12722                // calling code always writes the install permissions state but
12723                // the runtime ones are written only if changed. The only cases of
12724                // changed runtime permissions here are promotion of an install to
12725                // runtime and revocation of a runtime from a shared user.
12726                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12727                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12728                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12729                    runtimePermissionsRevoked = true;
12730                }
12731            }
12732        }
12733
12734        permissionsState.setGlobalGids(mGlobalGids);
12735
12736        final int N = pkg.requestedPermissions.size();
12737        for (int i=0; i<N; i++) {
12738            final String name = pkg.requestedPermissions.get(i);
12739            final BasePermission bp = mSettings.mPermissions.get(name);
12740            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12741                    >= Build.VERSION_CODES.M;
12742
12743            if (DEBUG_INSTALL) {
12744                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12745            }
12746
12747            if (bp == null || bp.packageSetting == null) {
12748                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12749                    if (DEBUG_PERMISSIONS) {
12750                        Slog.i(TAG, "Unknown permission " + name
12751                                + " in package " + pkg.packageName);
12752                    }
12753                }
12754                continue;
12755            }
12756
12757
12758            // Limit ephemeral apps to ephemeral allowed permissions.
12759            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12760                if (DEBUG_PERMISSIONS) {
12761                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12762                            + pkg.packageName);
12763                }
12764                continue;
12765            }
12766
12767            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12768                if (DEBUG_PERMISSIONS) {
12769                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12770                            + pkg.packageName);
12771                }
12772                continue;
12773            }
12774
12775            final String perm = bp.name;
12776            boolean allowedSig = false;
12777            int grant = GRANT_DENIED;
12778
12779            // Keep track of app op permissions.
12780            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12781                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12782                if (pkgs == null) {
12783                    pkgs = new ArraySet<>();
12784                    mAppOpPermissionPackages.put(bp.name, pkgs);
12785                }
12786                pkgs.add(pkg.packageName);
12787            }
12788
12789            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12790            switch (level) {
12791                case PermissionInfo.PROTECTION_NORMAL: {
12792                    // For all apps normal permissions are install time ones.
12793                    grant = GRANT_INSTALL;
12794                } break;
12795
12796                case PermissionInfo.PROTECTION_DANGEROUS: {
12797                    // If a permission review is required for legacy apps we represent
12798                    // their permissions as always granted runtime ones since we need
12799                    // to keep the review required permission flag per user while an
12800                    // install permission's state is shared across all users.
12801                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12802                        // For legacy apps dangerous permissions are install time ones.
12803                        grant = GRANT_INSTALL;
12804                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12805                        // For legacy apps that became modern, install becomes runtime.
12806                        grant = GRANT_UPGRADE;
12807                    } else if (mPromoteSystemApps
12808                            && isSystemApp(ps)
12809                            && mExistingSystemPackages.contains(ps.name)) {
12810                        // For legacy system apps, install becomes runtime.
12811                        // We cannot check hasInstallPermission() for system apps since those
12812                        // permissions were granted implicitly and not persisted pre-M.
12813                        grant = GRANT_UPGRADE;
12814                    } else {
12815                        // For modern apps keep runtime permissions unchanged.
12816                        grant = GRANT_RUNTIME;
12817                    }
12818                } break;
12819
12820                case PermissionInfo.PROTECTION_SIGNATURE: {
12821                    // For all apps signature permissions are install time ones.
12822                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12823                    if (allowedSig) {
12824                        grant = GRANT_INSTALL;
12825                    }
12826                } break;
12827            }
12828
12829            if (DEBUG_PERMISSIONS) {
12830                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12831            }
12832
12833            if (grant != GRANT_DENIED) {
12834                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12835                    // If this is an existing, non-system package, then
12836                    // we can't add any new permissions to it.
12837                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12838                        // Except...  if this is a permission that was added
12839                        // to the platform (note: need to only do this when
12840                        // updating the platform).
12841                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12842                            grant = GRANT_DENIED;
12843                        }
12844                    }
12845                }
12846
12847                switch (grant) {
12848                    case GRANT_INSTALL: {
12849                        // Revoke this as runtime permission to handle the case of
12850                        // a runtime permission being downgraded to an install one.
12851                        // Also in permission review mode we keep dangerous permissions
12852                        // for legacy apps
12853                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12854                            if (origPermissions.getRuntimePermissionState(
12855                                    bp.name, userId) != null) {
12856                                // Revoke the runtime permission and clear the flags.
12857                                origPermissions.revokeRuntimePermission(bp, userId);
12858                                origPermissions.updatePermissionFlags(bp, userId,
12859                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12860                                // If we revoked a permission permission, we have to write.
12861                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12862                                        changedRuntimePermissionUserIds, userId);
12863                            }
12864                        }
12865                        // Grant an install permission.
12866                        if (permissionsState.grantInstallPermission(bp) !=
12867                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12868                            changedInstallPermission = true;
12869                        }
12870                    } break;
12871
12872                    case GRANT_RUNTIME: {
12873                        // Grant previously granted runtime permissions.
12874                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12875                            PermissionState permissionState = origPermissions
12876                                    .getRuntimePermissionState(bp.name, userId);
12877                            int flags = permissionState != null
12878                                    ? permissionState.getFlags() : 0;
12879                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12880                                // Don't propagate the permission in a permission review mode if
12881                                // the former was revoked, i.e. marked to not propagate on upgrade.
12882                                // Note that in a permission review mode install permissions are
12883                                // represented as constantly granted runtime ones since we need to
12884                                // keep a per user state associated with the permission. Also the
12885                                // revoke on upgrade flag is no longer applicable and is reset.
12886                                final boolean revokeOnUpgrade = (flags & PackageManager
12887                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12888                                if (revokeOnUpgrade) {
12889                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12890                                    // Since we changed the flags, we have to write.
12891                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12892                                            changedRuntimePermissionUserIds, userId);
12893                                }
12894                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12895                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12896                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12897                                        // If we cannot put the permission as it was,
12898                                        // we have to write.
12899                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12900                                                changedRuntimePermissionUserIds, userId);
12901                                    }
12902                                }
12903
12904                                // If the app supports runtime permissions no need for a review.
12905                                if (mPermissionReviewRequired
12906                                        && appSupportsRuntimePermissions
12907                                        && (flags & PackageManager
12908                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12909                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12910                                    // Since we changed the flags, we have to write.
12911                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12912                                            changedRuntimePermissionUserIds, userId);
12913                                }
12914                            } else if (mPermissionReviewRequired
12915                                    && !appSupportsRuntimePermissions) {
12916                                // For legacy apps that need a permission review, every new
12917                                // runtime permission is granted but it is pending a review.
12918                                // We also need to review only platform defined runtime
12919                                // permissions as these are the only ones the platform knows
12920                                // how to disable the API to simulate revocation as legacy
12921                                // apps don't expect to run with revoked permissions.
12922                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12923                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12924                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12925                                        // We changed the flags, hence have to write.
12926                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12927                                                changedRuntimePermissionUserIds, userId);
12928                                    }
12929                                }
12930                                if (permissionsState.grantRuntimePermission(bp, userId)
12931                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12932                                    // We changed the permission, hence have to write.
12933                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12934                                            changedRuntimePermissionUserIds, userId);
12935                                }
12936                            }
12937                            // Propagate the permission flags.
12938                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12939                        }
12940                    } break;
12941
12942                    case GRANT_UPGRADE: {
12943                        // Grant runtime permissions for a previously held install permission.
12944                        PermissionState permissionState = origPermissions
12945                                .getInstallPermissionState(bp.name);
12946                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12947
12948                        if (origPermissions.revokeInstallPermission(bp)
12949                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12950                            // We will be transferring the permission flags, so clear them.
12951                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12952                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12953                            changedInstallPermission = true;
12954                        }
12955
12956                        // If the permission is not to be promoted to runtime we ignore it and
12957                        // also its other flags as they are not applicable to install permissions.
12958                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12959                            for (int userId : currentUserIds) {
12960                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12961                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12962                                    // Transfer the permission flags.
12963                                    permissionsState.updatePermissionFlags(bp, userId,
12964                                            flags, flags);
12965                                    // If we granted the permission, we have to write.
12966                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12967                                            changedRuntimePermissionUserIds, userId);
12968                                }
12969                            }
12970                        }
12971                    } break;
12972
12973                    default: {
12974                        if (packageOfInterest == null
12975                                || packageOfInterest.equals(pkg.packageName)) {
12976                            if (DEBUG_PERMISSIONS) {
12977                                Slog.i(TAG, "Not granting permission " + perm
12978                                        + " to package " + pkg.packageName
12979                                        + " because it was previously installed without");
12980                            }
12981                        }
12982                    } break;
12983                }
12984            } else {
12985                if (permissionsState.revokeInstallPermission(bp) !=
12986                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12987                    // Also drop the permission flags.
12988                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12989                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12990                    changedInstallPermission = true;
12991                    Slog.i(TAG, "Un-granting permission " + perm
12992                            + " from package " + pkg.packageName
12993                            + " (protectionLevel=" + bp.protectionLevel
12994                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12995                            + ")");
12996                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12997                    // Don't print warning for app op permissions, since it is fine for them
12998                    // not to be granted, there is a UI for the user to decide.
12999                    if (DEBUG_PERMISSIONS
13000                            && (packageOfInterest == null
13001                                    || packageOfInterest.equals(pkg.packageName))) {
13002                        Slog.i(TAG, "Not granting permission " + perm
13003                                + " to package " + pkg.packageName
13004                                + " (protectionLevel=" + bp.protectionLevel
13005                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13006                                + ")");
13007                    }
13008                }
13009            }
13010        }
13011
13012        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13013                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13014            // This is the first that we have heard about this package, so the
13015            // permissions we have now selected are fixed until explicitly
13016            // changed.
13017            ps.installPermissionsFixed = true;
13018        }
13019
13020        // Persist the runtime permissions state for users with changes. If permissions
13021        // were revoked because no app in the shared user declares them we have to
13022        // write synchronously to avoid losing runtime permissions state.
13023        for (int userId : changedRuntimePermissionUserIds) {
13024            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13025        }
13026    }
13027
13028    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13029        boolean allowed = false;
13030        final int NP = PackageParser.NEW_PERMISSIONS.length;
13031        for (int ip=0; ip<NP; ip++) {
13032            final PackageParser.NewPermissionInfo npi
13033                    = PackageParser.NEW_PERMISSIONS[ip];
13034            if (npi.name.equals(perm)
13035                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13036                allowed = true;
13037                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13038                        + pkg.packageName);
13039                break;
13040            }
13041        }
13042        return allowed;
13043    }
13044
13045    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13046            BasePermission bp, PermissionsState origPermissions) {
13047        boolean privilegedPermission = (bp.protectionLevel
13048                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13049        boolean privappPermissionsDisable =
13050                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13051        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13052        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13053        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13054                && !platformPackage && platformPermission) {
13055            ArraySet<String> wlPermissions = SystemConfig.getInstance()
13056                    .getPrivAppPermissions(pkg.packageName);
13057            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
13058            if (!whitelisted) {
13059                Slog.w(TAG, "Privileged permission " + perm + " for package "
13060                        + pkg.packageName + " - not in privapp-permissions whitelist");
13061                // Only report violations for apps on system image
13062                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13063                    if (mPrivappPermissionsViolations == null) {
13064                        mPrivappPermissionsViolations = new ArraySet<>();
13065                    }
13066                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13067                }
13068                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13069                    return false;
13070                }
13071            }
13072        }
13073        boolean allowed = (compareSignatures(
13074                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13075                        == PackageManager.SIGNATURE_MATCH)
13076                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13077                        == PackageManager.SIGNATURE_MATCH);
13078        if (!allowed && privilegedPermission) {
13079            if (isSystemApp(pkg)) {
13080                // For updated system applications, a system permission
13081                // is granted only if it had been defined by the original application.
13082                if (pkg.isUpdatedSystemApp()) {
13083                    final PackageSetting sysPs = mSettings
13084                            .getDisabledSystemPkgLPr(pkg.packageName);
13085                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13086                        // If the original was granted this permission, we take
13087                        // that grant decision as read and propagate it to the
13088                        // update.
13089                        if (sysPs.isPrivileged()) {
13090                            allowed = true;
13091                        }
13092                    } else {
13093                        // The system apk may have been updated with an older
13094                        // version of the one on the data partition, but which
13095                        // granted a new system permission that it didn't have
13096                        // before.  In this case we do want to allow the app to
13097                        // now get the new permission if the ancestral apk is
13098                        // privileged to get it.
13099                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13100                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13101                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13102                                    allowed = true;
13103                                    break;
13104                                }
13105                            }
13106                        }
13107                        // Also if a privileged parent package on the system image or any of
13108                        // its children requested a privileged permission, the updated child
13109                        // packages can also get the permission.
13110                        if (pkg.parentPackage != null) {
13111                            final PackageSetting disabledSysParentPs = mSettings
13112                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13113                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13114                                    && disabledSysParentPs.isPrivileged()) {
13115                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13116                                    allowed = true;
13117                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13118                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13119                                    for (int i = 0; i < count; i++) {
13120                                        PackageParser.Package disabledSysChildPkg =
13121                                                disabledSysParentPs.pkg.childPackages.get(i);
13122                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13123                                                perm)) {
13124                                            allowed = true;
13125                                            break;
13126                                        }
13127                                    }
13128                                }
13129                            }
13130                        }
13131                    }
13132                } else {
13133                    allowed = isPrivilegedApp(pkg);
13134                }
13135            }
13136        }
13137        if (!allowed) {
13138            if (!allowed && (bp.protectionLevel
13139                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13140                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13141                // If this was a previously normal/dangerous permission that got moved
13142                // to a system permission as part of the runtime permission redesign, then
13143                // we still want to blindly grant it to old apps.
13144                allowed = true;
13145            }
13146            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13147                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13148                // If this permission is to be granted to the system installer and
13149                // this app is an installer, then it gets the permission.
13150                allowed = true;
13151            }
13152            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13153                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13154                // If this permission is to be granted to the system verifier and
13155                // this app is a verifier, then it gets the permission.
13156                allowed = true;
13157            }
13158            if (!allowed && (bp.protectionLevel
13159                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13160                    && isSystemApp(pkg)) {
13161                // Any pre-installed system app is allowed to get this permission.
13162                allowed = true;
13163            }
13164            if (!allowed && (bp.protectionLevel
13165                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13166                // For development permissions, a development permission
13167                // is granted only if it was already granted.
13168                allowed = origPermissions.hasInstallPermission(perm);
13169            }
13170            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13171                    && pkg.packageName.equals(mSetupWizardPackage)) {
13172                // If this permission is to be granted to the system setup wizard and
13173                // this app is a setup wizard, then it gets the permission.
13174                allowed = true;
13175            }
13176        }
13177        return allowed;
13178    }
13179
13180    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13181        final int permCount = pkg.requestedPermissions.size();
13182        for (int j = 0; j < permCount; j++) {
13183            String requestedPermission = pkg.requestedPermissions.get(j);
13184            if (permission.equals(requestedPermission)) {
13185                return true;
13186            }
13187        }
13188        return false;
13189    }
13190
13191    final class ActivityIntentResolver
13192            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13193        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13194                boolean defaultOnly, int userId) {
13195            if (!sUserManager.exists(userId)) return null;
13196            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13197            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13198        }
13199
13200        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13201                int userId) {
13202            if (!sUserManager.exists(userId)) return null;
13203            mFlags = flags;
13204            return super.queryIntent(intent, resolvedType,
13205                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13206                    userId);
13207        }
13208
13209        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13210                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13211            if (!sUserManager.exists(userId)) return null;
13212            if (packageActivities == null) {
13213                return null;
13214            }
13215            mFlags = flags;
13216            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13217            final int N = packageActivities.size();
13218            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13219                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13220
13221            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13222            for (int i = 0; i < N; ++i) {
13223                intentFilters = packageActivities.get(i).intents;
13224                if (intentFilters != null && intentFilters.size() > 0) {
13225                    PackageParser.ActivityIntentInfo[] array =
13226                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13227                    intentFilters.toArray(array);
13228                    listCut.add(array);
13229                }
13230            }
13231            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13232        }
13233
13234        /**
13235         * Finds a privileged activity that matches the specified activity names.
13236         */
13237        private PackageParser.Activity findMatchingActivity(
13238                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13239            for (PackageParser.Activity sysActivity : activityList) {
13240                if (sysActivity.info.name.equals(activityInfo.name)) {
13241                    return sysActivity;
13242                }
13243                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13244                    return sysActivity;
13245                }
13246                if (sysActivity.info.targetActivity != null) {
13247                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13248                        return sysActivity;
13249                    }
13250                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13251                        return sysActivity;
13252                    }
13253                }
13254            }
13255            return null;
13256        }
13257
13258        public class IterGenerator<E> {
13259            public Iterator<E> generate(ActivityIntentInfo info) {
13260                return null;
13261            }
13262        }
13263
13264        public class ActionIterGenerator extends IterGenerator<String> {
13265            @Override
13266            public Iterator<String> generate(ActivityIntentInfo info) {
13267                return info.actionsIterator();
13268            }
13269        }
13270
13271        public class CategoriesIterGenerator extends IterGenerator<String> {
13272            @Override
13273            public Iterator<String> generate(ActivityIntentInfo info) {
13274                return info.categoriesIterator();
13275            }
13276        }
13277
13278        public class SchemesIterGenerator extends IterGenerator<String> {
13279            @Override
13280            public Iterator<String> generate(ActivityIntentInfo info) {
13281                return info.schemesIterator();
13282            }
13283        }
13284
13285        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13286            @Override
13287            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13288                return info.authoritiesIterator();
13289            }
13290        }
13291
13292        /**
13293         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13294         * MODIFIED. Do not pass in a list that should not be changed.
13295         */
13296        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13297                IterGenerator<T> generator, Iterator<T> searchIterator) {
13298            // loop through the set of actions; every one must be found in the intent filter
13299            while (searchIterator.hasNext()) {
13300                // we must have at least one filter in the list to consider a match
13301                if (intentList.size() == 0) {
13302                    break;
13303                }
13304
13305                final T searchAction = searchIterator.next();
13306
13307                // loop through the set of intent filters
13308                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13309                while (intentIter.hasNext()) {
13310                    final ActivityIntentInfo intentInfo = intentIter.next();
13311                    boolean selectionFound = false;
13312
13313                    // loop through the intent filter's selection criteria; at least one
13314                    // of them must match the searched criteria
13315                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13316                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13317                        final T intentSelection = intentSelectionIter.next();
13318                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13319                            selectionFound = true;
13320                            break;
13321                        }
13322                    }
13323
13324                    // the selection criteria wasn't found in this filter's set; this filter
13325                    // is not a potential match
13326                    if (!selectionFound) {
13327                        intentIter.remove();
13328                    }
13329                }
13330            }
13331        }
13332
13333        private boolean isProtectedAction(ActivityIntentInfo filter) {
13334            final Iterator<String> actionsIter = filter.actionsIterator();
13335            while (actionsIter != null && actionsIter.hasNext()) {
13336                final String filterAction = actionsIter.next();
13337                if (PROTECTED_ACTIONS.contains(filterAction)) {
13338                    return true;
13339                }
13340            }
13341            return false;
13342        }
13343
13344        /**
13345         * Adjusts the priority of the given intent filter according to policy.
13346         * <p>
13347         * <ul>
13348         * <li>The priority for non privileged applications is capped to '0'</li>
13349         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13350         * <li>The priority for unbundled updates to privileged applications is capped to the
13351         *      priority defined on the system partition</li>
13352         * </ul>
13353         * <p>
13354         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13355         * allowed to obtain any priority on any action.
13356         */
13357        private void adjustPriority(
13358                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13359            // nothing to do; priority is fine as-is
13360            if (intent.getPriority() <= 0) {
13361                return;
13362            }
13363
13364            final ActivityInfo activityInfo = intent.activity.info;
13365            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13366
13367            final boolean privilegedApp =
13368                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13369            if (!privilegedApp) {
13370                // non-privileged applications can never define a priority >0
13371                if (DEBUG_FILTERS) {
13372                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13373                            + " package: " + applicationInfo.packageName
13374                            + " activity: " + intent.activity.className
13375                            + " origPrio: " + intent.getPriority());
13376                }
13377                intent.setPriority(0);
13378                return;
13379            }
13380
13381            if (systemActivities == null) {
13382                // the system package is not disabled; we're parsing the system partition
13383                if (isProtectedAction(intent)) {
13384                    if (mDeferProtectedFilters) {
13385                        // We can't deal with these just yet. No component should ever obtain a
13386                        // >0 priority for a protected actions, with ONE exception -- the setup
13387                        // wizard. The setup wizard, however, cannot be known until we're able to
13388                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13389                        // until all intent filters have been processed. Chicken, meet egg.
13390                        // Let the filter temporarily have a high priority and rectify the
13391                        // priorities after all system packages have been scanned.
13392                        mProtectedFilters.add(intent);
13393                        if (DEBUG_FILTERS) {
13394                            Slog.i(TAG, "Protected action; save for later;"
13395                                    + " package: " + applicationInfo.packageName
13396                                    + " activity: " + intent.activity.className
13397                                    + " origPrio: " + intent.getPriority());
13398                        }
13399                        return;
13400                    } else {
13401                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13402                            Slog.i(TAG, "No setup wizard;"
13403                                + " All protected intents capped to priority 0");
13404                        }
13405                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13406                            if (DEBUG_FILTERS) {
13407                                Slog.i(TAG, "Found setup wizard;"
13408                                    + " allow priority " + intent.getPriority() + ";"
13409                                    + " package: " + intent.activity.info.packageName
13410                                    + " activity: " + intent.activity.className
13411                                    + " priority: " + intent.getPriority());
13412                            }
13413                            // setup wizard gets whatever it wants
13414                            return;
13415                        }
13416                        if (DEBUG_FILTERS) {
13417                            Slog.i(TAG, "Protected action; cap priority to 0;"
13418                                    + " package: " + intent.activity.info.packageName
13419                                    + " activity: " + intent.activity.className
13420                                    + " origPrio: " + intent.getPriority());
13421                        }
13422                        intent.setPriority(0);
13423                        return;
13424                    }
13425                }
13426                // privileged apps on the system image get whatever priority they request
13427                return;
13428            }
13429
13430            // privileged app unbundled update ... try to find the same activity
13431            final PackageParser.Activity foundActivity =
13432                    findMatchingActivity(systemActivities, activityInfo);
13433            if (foundActivity == null) {
13434                // this is a new activity; it cannot obtain >0 priority
13435                if (DEBUG_FILTERS) {
13436                    Slog.i(TAG, "New activity; cap priority to 0;"
13437                            + " package: " + applicationInfo.packageName
13438                            + " activity: " + intent.activity.className
13439                            + " origPrio: " + intent.getPriority());
13440                }
13441                intent.setPriority(0);
13442                return;
13443            }
13444
13445            // found activity, now check for filter equivalence
13446
13447            // a shallow copy is enough; we modify the list, not its contents
13448            final List<ActivityIntentInfo> intentListCopy =
13449                    new ArrayList<>(foundActivity.intents);
13450            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13451
13452            // find matching action subsets
13453            final Iterator<String> actionsIterator = intent.actionsIterator();
13454            if (actionsIterator != null) {
13455                getIntentListSubset(
13456                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13457                if (intentListCopy.size() == 0) {
13458                    // no more intents to match; we're not equivalent
13459                    if (DEBUG_FILTERS) {
13460                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13461                                + " package: " + applicationInfo.packageName
13462                                + " activity: " + intent.activity.className
13463                                + " origPrio: " + intent.getPriority());
13464                    }
13465                    intent.setPriority(0);
13466                    return;
13467                }
13468            }
13469
13470            // find matching category subsets
13471            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13472            if (categoriesIterator != null) {
13473                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13474                        categoriesIterator);
13475                if (intentListCopy.size() == 0) {
13476                    // no more intents to match; we're not equivalent
13477                    if (DEBUG_FILTERS) {
13478                        Slog.i(TAG, "Mismatched category; 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 schemes subsets
13489            final Iterator<String> schemesIterator = intent.schemesIterator();
13490            if (schemesIterator != null) {
13491                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13492                        schemesIterator);
13493                if (intentListCopy.size() == 0) {
13494                    // no more intents to match; we're not equivalent
13495                    if (DEBUG_FILTERS) {
13496                        Slog.i(TAG, "Mismatched scheme; 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 authorities subsets
13507            final Iterator<IntentFilter.AuthorityEntry>
13508                    authoritiesIterator = intent.authoritiesIterator();
13509            if (authoritiesIterator != null) {
13510                getIntentListSubset(intentListCopy,
13511                        new AuthoritiesIterGenerator(),
13512                        authoritiesIterator);
13513                if (intentListCopy.size() == 0) {
13514                    // no more intents to match; we're not equivalent
13515                    if (DEBUG_FILTERS) {
13516                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13517                                + " package: " + applicationInfo.packageName
13518                                + " activity: " + intent.activity.className
13519                                + " origPrio: " + intent.getPriority());
13520                    }
13521                    intent.setPriority(0);
13522                    return;
13523                }
13524            }
13525
13526            // we found matching filter(s); app gets the max priority of all intents
13527            int cappedPriority = 0;
13528            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13529                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13530            }
13531            if (intent.getPriority() > cappedPriority) {
13532                if (DEBUG_FILTERS) {
13533                    Slog.i(TAG, "Found matching filter(s);"
13534                            + " cap priority to " + cappedPriority + ";"
13535                            + " package: " + applicationInfo.packageName
13536                            + " activity: " + intent.activity.className
13537                            + " origPrio: " + intent.getPriority());
13538                }
13539                intent.setPriority(cappedPriority);
13540                return;
13541            }
13542            // all this for nothing; the requested priority was <= what was on the system
13543        }
13544
13545        public final void addActivity(PackageParser.Activity a, String type) {
13546            mActivities.put(a.getComponentName(), a);
13547            if (DEBUG_SHOW_INFO)
13548                Log.v(
13549                TAG, "  " + type + " " +
13550                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13551            if (DEBUG_SHOW_INFO)
13552                Log.v(TAG, "    Class=" + a.info.name);
13553            final int NI = a.intents.size();
13554            for (int j=0; j<NI; j++) {
13555                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13556                if ("activity".equals(type)) {
13557                    final PackageSetting ps =
13558                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13559                    final List<PackageParser.Activity> systemActivities =
13560                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13561                    adjustPriority(systemActivities, intent);
13562                }
13563                if (DEBUG_SHOW_INFO) {
13564                    Log.v(TAG, "    IntentFilter:");
13565                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13566                }
13567                if (!intent.debugCheck()) {
13568                    Log.w(TAG, "==> For Activity " + a.info.name);
13569                }
13570                addFilter(intent);
13571            }
13572        }
13573
13574        public final void removeActivity(PackageParser.Activity a, String type) {
13575            mActivities.remove(a.getComponentName());
13576            if (DEBUG_SHOW_INFO) {
13577                Log.v(TAG, "  " + type + " "
13578                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13579                                : a.info.name) + ":");
13580                Log.v(TAG, "    Class=" + a.info.name);
13581            }
13582            final int NI = a.intents.size();
13583            for (int j=0; j<NI; j++) {
13584                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13585                if (DEBUG_SHOW_INFO) {
13586                    Log.v(TAG, "    IntentFilter:");
13587                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13588                }
13589                removeFilter(intent);
13590            }
13591        }
13592
13593        @Override
13594        protected boolean allowFilterResult(
13595                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13596            ActivityInfo filterAi = filter.activity.info;
13597            for (int i=dest.size()-1; i>=0; i--) {
13598                ActivityInfo destAi = dest.get(i).activityInfo;
13599                if (destAi.name == filterAi.name
13600                        && destAi.packageName == filterAi.packageName) {
13601                    return false;
13602                }
13603            }
13604            return true;
13605        }
13606
13607        @Override
13608        protected ActivityIntentInfo[] newArray(int size) {
13609            return new ActivityIntentInfo[size];
13610        }
13611
13612        @Override
13613        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13614            if (!sUserManager.exists(userId)) return true;
13615            PackageParser.Package p = filter.activity.owner;
13616            if (p != null) {
13617                PackageSetting ps = (PackageSetting)p.mExtras;
13618                if (ps != null) {
13619                    // System apps are never considered stopped for purposes of
13620                    // filtering, because there may be no way for the user to
13621                    // actually re-launch them.
13622                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13623                            && ps.getStopped(userId);
13624                }
13625            }
13626            return false;
13627        }
13628
13629        @Override
13630        protected boolean isPackageForFilter(String packageName,
13631                PackageParser.ActivityIntentInfo info) {
13632            return packageName.equals(info.activity.owner.packageName);
13633        }
13634
13635        @Override
13636        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13637                int match, int userId) {
13638            if (!sUserManager.exists(userId)) return null;
13639            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13640                return null;
13641            }
13642            final PackageParser.Activity activity = info.activity;
13643            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13644            if (ps == null) {
13645                return null;
13646            }
13647            final PackageUserState userState = ps.readUserState(userId);
13648            ActivityInfo ai =
13649                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13650            if (ai == null) {
13651                return null;
13652            }
13653            final boolean matchExplicitlyVisibleOnly =
13654                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13655            final boolean matchVisibleToInstantApp =
13656                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13657            final boolean componentVisible =
13658                    matchVisibleToInstantApp
13659                    && info.isVisibleToInstantApp()
13660                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13661            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13662            // throw out filters that aren't visible to ephemeral apps
13663            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13664                return null;
13665            }
13666            // throw out instant app filters if we're not explicitly requesting them
13667            if (!matchInstantApp && userState.instantApp) {
13668                return null;
13669            }
13670            // throw out instant app filters if updates are available; will trigger
13671            // instant app resolution
13672            if (userState.instantApp && ps.isUpdateAvailable()) {
13673                return null;
13674            }
13675            final ResolveInfo res = new ResolveInfo();
13676            res.activityInfo = ai;
13677            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13678                res.filter = info;
13679            }
13680            if (info != null) {
13681                res.handleAllWebDataURI = info.handleAllWebDataURI();
13682            }
13683            res.priority = info.getPriority();
13684            res.preferredOrder = activity.owner.mPreferredOrder;
13685            //System.out.println("Result: " + res.activityInfo.className +
13686            //                   " = " + res.priority);
13687            res.match = match;
13688            res.isDefault = info.hasDefault;
13689            res.labelRes = info.labelRes;
13690            res.nonLocalizedLabel = info.nonLocalizedLabel;
13691            if (userNeedsBadging(userId)) {
13692                res.noResourceId = true;
13693            } else {
13694                res.icon = info.icon;
13695            }
13696            res.iconResourceId = info.icon;
13697            res.system = res.activityInfo.applicationInfo.isSystemApp();
13698            res.isInstantAppAvailable = userState.instantApp;
13699            return res;
13700        }
13701
13702        @Override
13703        protected void sortResults(List<ResolveInfo> results) {
13704            Collections.sort(results, mResolvePrioritySorter);
13705        }
13706
13707        @Override
13708        protected void dumpFilter(PrintWriter out, String prefix,
13709                PackageParser.ActivityIntentInfo filter) {
13710            out.print(prefix); out.print(
13711                    Integer.toHexString(System.identityHashCode(filter.activity)));
13712                    out.print(' ');
13713                    filter.activity.printComponentShortName(out);
13714                    out.print(" filter ");
13715                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13716        }
13717
13718        @Override
13719        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13720            return filter.activity;
13721        }
13722
13723        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13724            PackageParser.Activity activity = (PackageParser.Activity)label;
13725            out.print(prefix); out.print(
13726                    Integer.toHexString(System.identityHashCode(activity)));
13727                    out.print(' ');
13728                    activity.printComponentShortName(out);
13729            if (count > 1) {
13730                out.print(" ("); out.print(count); out.print(" filters)");
13731            }
13732            out.println();
13733        }
13734
13735        // Keys are String (activity class name), values are Activity.
13736        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13737                = new ArrayMap<ComponentName, PackageParser.Activity>();
13738        private int mFlags;
13739    }
13740
13741    private final class ServiceIntentResolver
13742            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13743        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13744                boolean defaultOnly, int userId) {
13745            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13746            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13747        }
13748
13749        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13750                int userId) {
13751            if (!sUserManager.exists(userId)) return null;
13752            mFlags = flags;
13753            return super.queryIntent(intent, resolvedType,
13754                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13755                    userId);
13756        }
13757
13758        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13759                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13760            if (!sUserManager.exists(userId)) return null;
13761            if (packageServices == null) {
13762                return null;
13763            }
13764            mFlags = flags;
13765            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13766            final int N = packageServices.size();
13767            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13768                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13769
13770            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13771            for (int i = 0; i < N; ++i) {
13772                intentFilters = packageServices.get(i).intents;
13773                if (intentFilters != null && intentFilters.size() > 0) {
13774                    PackageParser.ServiceIntentInfo[] array =
13775                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13776                    intentFilters.toArray(array);
13777                    listCut.add(array);
13778                }
13779            }
13780            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13781        }
13782
13783        public final void addService(PackageParser.Service s) {
13784            mServices.put(s.getComponentName(), s);
13785            if (DEBUG_SHOW_INFO) {
13786                Log.v(TAG, "  "
13787                        + (s.info.nonLocalizedLabel != null
13788                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13789                Log.v(TAG, "    Class=" + s.info.name);
13790            }
13791            final int NI = s.intents.size();
13792            int j;
13793            for (j=0; j<NI; j++) {
13794                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13795                if (DEBUG_SHOW_INFO) {
13796                    Log.v(TAG, "    IntentFilter:");
13797                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13798                }
13799                if (!intent.debugCheck()) {
13800                    Log.w(TAG, "==> For Service " + s.info.name);
13801                }
13802                addFilter(intent);
13803            }
13804        }
13805
13806        public final void removeService(PackageParser.Service s) {
13807            mServices.remove(s.getComponentName());
13808            if (DEBUG_SHOW_INFO) {
13809                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13810                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13811                Log.v(TAG, "    Class=" + s.info.name);
13812            }
13813            final int NI = s.intents.size();
13814            int j;
13815            for (j=0; j<NI; j++) {
13816                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13817                if (DEBUG_SHOW_INFO) {
13818                    Log.v(TAG, "    IntentFilter:");
13819                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13820                }
13821                removeFilter(intent);
13822            }
13823        }
13824
13825        @Override
13826        protected boolean allowFilterResult(
13827                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13828            ServiceInfo filterSi = filter.service.info;
13829            for (int i=dest.size()-1; i>=0; i--) {
13830                ServiceInfo destAi = dest.get(i).serviceInfo;
13831                if (destAi.name == filterSi.name
13832                        && destAi.packageName == filterSi.packageName) {
13833                    return false;
13834                }
13835            }
13836            return true;
13837        }
13838
13839        @Override
13840        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13841            return new PackageParser.ServiceIntentInfo[size];
13842        }
13843
13844        @Override
13845        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13846            if (!sUserManager.exists(userId)) return true;
13847            PackageParser.Package p = filter.service.owner;
13848            if (p != null) {
13849                PackageSetting ps = (PackageSetting)p.mExtras;
13850                if (ps != null) {
13851                    // System apps are never considered stopped for purposes of
13852                    // filtering, because there may be no way for the user to
13853                    // actually re-launch them.
13854                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13855                            && ps.getStopped(userId);
13856                }
13857            }
13858            return false;
13859        }
13860
13861        @Override
13862        protected boolean isPackageForFilter(String packageName,
13863                PackageParser.ServiceIntentInfo info) {
13864            return packageName.equals(info.service.owner.packageName);
13865        }
13866
13867        @Override
13868        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13869                int match, int userId) {
13870            if (!sUserManager.exists(userId)) return null;
13871            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13872            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13873                return null;
13874            }
13875            final PackageParser.Service service = info.service;
13876            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13877            if (ps == null) {
13878                return null;
13879            }
13880            final PackageUserState userState = ps.readUserState(userId);
13881            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13882                    userState, userId);
13883            if (si == null) {
13884                return null;
13885            }
13886            final boolean matchVisibleToInstantApp =
13887                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13888            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13889            // throw out filters that aren't visible to ephemeral apps
13890            if (matchVisibleToInstantApp
13891                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13892                return null;
13893            }
13894            // throw out ephemeral filters if we're not explicitly requesting them
13895            if (!isInstantApp && userState.instantApp) {
13896                return null;
13897            }
13898            // throw out instant app filters if updates are available; will trigger
13899            // instant app resolution
13900            if (userState.instantApp && ps.isUpdateAvailable()) {
13901                return null;
13902            }
13903            final ResolveInfo res = new ResolveInfo();
13904            res.serviceInfo = si;
13905            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13906                res.filter = filter;
13907            }
13908            res.priority = info.getPriority();
13909            res.preferredOrder = service.owner.mPreferredOrder;
13910            res.match = match;
13911            res.isDefault = info.hasDefault;
13912            res.labelRes = info.labelRes;
13913            res.nonLocalizedLabel = info.nonLocalizedLabel;
13914            res.icon = info.icon;
13915            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13916            return res;
13917        }
13918
13919        @Override
13920        protected void sortResults(List<ResolveInfo> results) {
13921            Collections.sort(results, mResolvePrioritySorter);
13922        }
13923
13924        @Override
13925        protected void dumpFilter(PrintWriter out, String prefix,
13926                PackageParser.ServiceIntentInfo filter) {
13927            out.print(prefix); out.print(
13928                    Integer.toHexString(System.identityHashCode(filter.service)));
13929                    out.print(' ');
13930                    filter.service.printComponentShortName(out);
13931                    out.print(" filter ");
13932                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13933        }
13934
13935        @Override
13936        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13937            return filter.service;
13938        }
13939
13940        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13941            PackageParser.Service service = (PackageParser.Service)label;
13942            out.print(prefix); out.print(
13943                    Integer.toHexString(System.identityHashCode(service)));
13944                    out.print(' ');
13945                    service.printComponentShortName(out);
13946            if (count > 1) {
13947                out.print(" ("); out.print(count); out.print(" filters)");
13948            }
13949            out.println();
13950        }
13951
13952//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13953//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13954//            final List<ResolveInfo> retList = Lists.newArrayList();
13955//            while (i.hasNext()) {
13956//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13957//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13958//                    retList.add(resolveInfo);
13959//                }
13960//            }
13961//            return retList;
13962//        }
13963
13964        // Keys are String (activity class name), values are Activity.
13965        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13966                = new ArrayMap<ComponentName, PackageParser.Service>();
13967        private int mFlags;
13968    }
13969
13970    private final class ProviderIntentResolver
13971            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13972        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13973                boolean defaultOnly, int userId) {
13974            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13975            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13976        }
13977
13978        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13979                int userId) {
13980            if (!sUserManager.exists(userId))
13981                return null;
13982            mFlags = flags;
13983            return super.queryIntent(intent, resolvedType,
13984                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13985                    userId);
13986        }
13987
13988        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13989                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13990            if (!sUserManager.exists(userId))
13991                return null;
13992            if (packageProviders == null) {
13993                return null;
13994            }
13995            mFlags = flags;
13996            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13997            final int N = packageProviders.size();
13998            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13999                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14000
14001            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14002            for (int i = 0; i < N; ++i) {
14003                intentFilters = packageProviders.get(i).intents;
14004                if (intentFilters != null && intentFilters.size() > 0) {
14005                    PackageParser.ProviderIntentInfo[] array =
14006                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14007                    intentFilters.toArray(array);
14008                    listCut.add(array);
14009                }
14010            }
14011            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14012        }
14013
14014        public final void addProvider(PackageParser.Provider p) {
14015            if (mProviders.containsKey(p.getComponentName())) {
14016                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14017                return;
14018            }
14019
14020            mProviders.put(p.getComponentName(), p);
14021            if (DEBUG_SHOW_INFO) {
14022                Log.v(TAG, "  "
14023                        + (p.info.nonLocalizedLabel != null
14024                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14025                Log.v(TAG, "    Class=" + p.info.name);
14026            }
14027            final int NI = p.intents.size();
14028            int j;
14029            for (j = 0; j < NI; j++) {
14030                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14031                if (DEBUG_SHOW_INFO) {
14032                    Log.v(TAG, "    IntentFilter:");
14033                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14034                }
14035                if (!intent.debugCheck()) {
14036                    Log.w(TAG, "==> For Provider " + p.info.name);
14037                }
14038                addFilter(intent);
14039            }
14040        }
14041
14042        public final void removeProvider(PackageParser.Provider p) {
14043            mProviders.remove(p.getComponentName());
14044            if (DEBUG_SHOW_INFO) {
14045                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14046                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14047                Log.v(TAG, "    Class=" + p.info.name);
14048            }
14049            final int NI = p.intents.size();
14050            int j;
14051            for (j = 0; j < NI; j++) {
14052                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14053                if (DEBUG_SHOW_INFO) {
14054                    Log.v(TAG, "    IntentFilter:");
14055                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14056                }
14057                removeFilter(intent);
14058            }
14059        }
14060
14061        @Override
14062        protected boolean allowFilterResult(
14063                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14064            ProviderInfo filterPi = filter.provider.info;
14065            for (int i = dest.size() - 1; i >= 0; i--) {
14066                ProviderInfo destPi = dest.get(i).providerInfo;
14067                if (destPi.name == filterPi.name
14068                        && destPi.packageName == filterPi.packageName) {
14069                    return false;
14070                }
14071            }
14072            return true;
14073        }
14074
14075        @Override
14076        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14077            return new PackageParser.ProviderIntentInfo[size];
14078        }
14079
14080        @Override
14081        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14082            if (!sUserManager.exists(userId))
14083                return true;
14084            PackageParser.Package p = filter.provider.owner;
14085            if (p != null) {
14086                PackageSetting ps = (PackageSetting) p.mExtras;
14087                if (ps != null) {
14088                    // System apps are never considered stopped for purposes of
14089                    // filtering, because there may be no way for the user to
14090                    // actually re-launch them.
14091                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14092                            && ps.getStopped(userId);
14093                }
14094            }
14095            return false;
14096        }
14097
14098        @Override
14099        protected boolean isPackageForFilter(String packageName,
14100                PackageParser.ProviderIntentInfo info) {
14101            return packageName.equals(info.provider.owner.packageName);
14102        }
14103
14104        @Override
14105        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14106                int match, int userId) {
14107            if (!sUserManager.exists(userId))
14108                return null;
14109            final PackageParser.ProviderIntentInfo info = filter;
14110            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14111                return null;
14112            }
14113            final PackageParser.Provider provider = info.provider;
14114            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14115            if (ps == null) {
14116                return null;
14117            }
14118            final PackageUserState userState = ps.readUserState(userId);
14119            final boolean matchVisibleToInstantApp =
14120                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14121            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14122            // throw out filters that aren't visible to instant applications
14123            if (matchVisibleToInstantApp
14124                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14125                return null;
14126            }
14127            // throw out instant application filters if we're not explicitly requesting them
14128            if (!isInstantApp && userState.instantApp) {
14129                return null;
14130            }
14131            // throw out instant application filters if updates are available; will trigger
14132            // instant application resolution
14133            if (userState.instantApp && ps.isUpdateAvailable()) {
14134                return null;
14135            }
14136            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14137                    userState, userId);
14138            if (pi == null) {
14139                return null;
14140            }
14141            final ResolveInfo res = new ResolveInfo();
14142            res.providerInfo = pi;
14143            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14144                res.filter = filter;
14145            }
14146            res.priority = info.getPriority();
14147            res.preferredOrder = provider.owner.mPreferredOrder;
14148            res.match = match;
14149            res.isDefault = info.hasDefault;
14150            res.labelRes = info.labelRes;
14151            res.nonLocalizedLabel = info.nonLocalizedLabel;
14152            res.icon = info.icon;
14153            res.system = res.providerInfo.applicationInfo.isSystemApp();
14154            return res;
14155        }
14156
14157        @Override
14158        protected void sortResults(List<ResolveInfo> results) {
14159            Collections.sort(results, mResolvePrioritySorter);
14160        }
14161
14162        @Override
14163        protected void dumpFilter(PrintWriter out, String prefix,
14164                PackageParser.ProviderIntentInfo filter) {
14165            out.print(prefix);
14166            out.print(
14167                    Integer.toHexString(System.identityHashCode(filter.provider)));
14168            out.print(' ');
14169            filter.provider.printComponentShortName(out);
14170            out.print(" filter ");
14171            out.println(Integer.toHexString(System.identityHashCode(filter)));
14172        }
14173
14174        @Override
14175        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14176            return filter.provider;
14177        }
14178
14179        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14180            PackageParser.Provider provider = (PackageParser.Provider)label;
14181            out.print(prefix); out.print(
14182                    Integer.toHexString(System.identityHashCode(provider)));
14183                    out.print(' ');
14184                    provider.printComponentShortName(out);
14185            if (count > 1) {
14186                out.print(" ("); out.print(count); out.print(" filters)");
14187            }
14188            out.println();
14189        }
14190
14191        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14192                = new ArrayMap<ComponentName, PackageParser.Provider>();
14193        private int mFlags;
14194    }
14195
14196    static final class EphemeralIntentResolver
14197            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14198        /**
14199         * The result that has the highest defined order. Ordering applies on a
14200         * per-package basis. Mapping is from package name to Pair of order and
14201         * EphemeralResolveInfo.
14202         * <p>
14203         * NOTE: This is implemented as a field variable for convenience and efficiency.
14204         * By having a field variable, we're able to track filter ordering as soon as
14205         * a non-zero order is defined. Otherwise, multiple loops across the result set
14206         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14207         * this needs to be contained entirely within {@link #filterResults}.
14208         */
14209        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14210
14211        @Override
14212        protected AuxiliaryResolveInfo[] newArray(int size) {
14213            return new AuxiliaryResolveInfo[size];
14214        }
14215
14216        @Override
14217        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14218            return true;
14219        }
14220
14221        @Override
14222        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14223                int userId) {
14224            if (!sUserManager.exists(userId)) {
14225                return null;
14226            }
14227            final String packageName = responseObj.resolveInfo.getPackageName();
14228            final Integer order = responseObj.getOrder();
14229            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14230                    mOrderResult.get(packageName);
14231            // ordering is enabled and this item's order isn't high enough
14232            if (lastOrderResult != null && lastOrderResult.first >= order) {
14233                return null;
14234            }
14235            final InstantAppResolveInfo res = responseObj.resolveInfo;
14236            if (order > 0) {
14237                // non-zero order, enable ordering
14238                mOrderResult.put(packageName, new Pair<>(order, res));
14239            }
14240            return responseObj;
14241        }
14242
14243        @Override
14244        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14245            // only do work if ordering is enabled [most of the time it won't be]
14246            if (mOrderResult.size() == 0) {
14247                return;
14248            }
14249            int resultSize = results.size();
14250            for (int i = 0; i < resultSize; i++) {
14251                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14252                final String packageName = info.getPackageName();
14253                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14254                if (savedInfo == null) {
14255                    // package doesn't having ordering
14256                    continue;
14257                }
14258                if (savedInfo.second == info) {
14259                    // circled back to the highest ordered item; remove from order list
14260                    mOrderResult.remove(savedInfo);
14261                    if (mOrderResult.size() == 0) {
14262                        // no more ordered items
14263                        break;
14264                    }
14265                    continue;
14266                }
14267                // item has a worse order, remove it from the result list
14268                results.remove(i);
14269                resultSize--;
14270                i--;
14271            }
14272        }
14273    }
14274
14275    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14276            new Comparator<ResolveInfo>() {
14277        public int compare(ResolveInfo r1, ResolveInfo r2) {
14278            int v1 = r1.priority;
14279            int v2 = r2.priority;
14280            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14281            if (v1 != v2) {
14282                return (v1 > v2) ? -1 : 1;
14283            }
14284            v1 = r1.preferredOrder;
14285            v2 = r2.preferredOrder;
14286            if (v1 != v2) {
14287                return (v1 > v2) ? -1 : 1;
14288            }
14289            if (r1.isDefault != r2.isDefault) {
14290                return r1.isDefault ? -1 : 1;
14291            }
14292            v1 = r1.match;
14293            v2 = r2.match;
14294            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14295            if (v1 != v2) {
14296                return (v1 > v2) ? -1 : 1;
14297            }
14298            if (r1.system != r2.system) {
14299                return r1.system ? -1 : 1;
14300            }
14301            if (r1.activityInfo != null) {
14302                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14303            }
14304            if (r1.serviceInfo != null) {
14305                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14306            }
14307            if (r1.providerInfo != null) {
14308                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14309            }
14310            return 0;
14311        }
14312    };
14313
14314    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14315            new Comparator<ProviderInfo>() {
14316        public int compare(ProviderInfo p1, ProviderInfo p2) {
14317            final int v1 = p1.initOrder;
14318            final int v2 = p2.initOrder;
14319            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14320        }
14321    };
14322
14323    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14324            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14325            final int[] userIds) {
14326        mHandler.post(new Runnable() {
14327            @Override
14328            public void run() {
14329                try {
14330                    final IActivityManager am = ActivityManager.getService();
14331                    if (am == null) return;
14332                    final int[] resolvedUserIds;
14333                    if (userIds == null) {
14334                        resolvedUserIds = am.getRunningUserIds();
14335                    } else {
14336                        resolvedUserIds = userIds;
14337                    }
14338                    for (int id : resolvedUserIds) {
14339                        final Intent intent = new Intent(action,
14340                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14341                        if (extras != null) {
14342                            intent.putExtras(extras);
14343                        }
14344                        if (targetPkg != null) {
14345                            intent.setPackage(targetPkg);
14346                        }
14347                        // Modify the UID when posting to other users
14348                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14349                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14350                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14351                            intent.putExtra(Intent.EXTRA_UID, uid);
14352                        }
14353                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14354                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14355                        if (DEBUG_BROADCASTS) {
14356                            RuntimeException here = new RuntimeException("here");
14357                            here.fillInStackTrace();
14358                            Slog.d(TAG, "Sending to user " + id + ": "
14359                                    + intent.toShortString(false, true, false, false)
14360                                    + " " + intent.getExtras(), here);
14361                        }
14362                        am.broadcastIntent(null, intent, null, finishedReceiver,
14363                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14364                                null, finishedReceiver != null, false, id);
14365                    }
14366                } catch (RemoteException ex) {
14367                }
14368            }
14369        });
14370    }
14371
14372    /**
14373     * Check if the external storage media is available. This is true if there
14374     * is a mounted external storage medium or if the external storage is
14375     * emulated.
14376     */
14377    private boolean isExternalMediaAvailable() {
14378        return mMediaMounted || Environment.isExternalStorageEmulated();
14379    }
14380
14381    @Override
14382    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14383        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14384            return null;
14385        }
14386        // writer
14387        synchronized (mPackages) {
14388            if (!isExternalMediaAvailable()) {
14389                // If the external storage is no longer mounted at this point,
14390                // the caller may not have been able to delete all of this
14391                // packages files and can not delete any more.  Bail.
14392                return null;
14393            }
14394            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14395            if (lastPackage != null) {
14396                pkgs.remove(lastPackage);
14397            }
14398            if (pkgs.size() > 0) {
14399                return pkgs.get(0);
14400            }
14401        }
14402        return null;
14403    }
14404
14405    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14406        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14407                userId, andCode ? 1 : 0, packageName);
14408        if (mSystemReady) {
14409            msg.sendToTarget();
14410        } else {
14411            if (mPostSystemReadyMessages == null) {
14412                mPostSystemReadyMessages = new ArrayList<>();
14413            }
14414            mPostSystemReadyMessages.add(msg);
14415        }
14416    }
14417
14418    void startCleaningPackages() {
14419        // reader
14420        if (!isExternalMediaAvailable()) {
14421            return;
14422        }
14423        synchronized (mPackages) {
14424            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14425                return;
14426            }
14427        }
14428        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14429        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14430        IActivityManager am = ActivityManager.getService();
14431        if (am != null) {
14432            int dcsUid = -1;
14433            synchronized (mPackages) {
14434                if (!mDefaultContainerWhitelisted) {
14435                    mDefaultContainerWhitelisted = true;
14436                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14437                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14438                }
14439            }
14440            try {
14441                if (dcsUid > 0) {
14442                    am.backgroundWhitelistUid(dcsUid);
14443                }
14444                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14445                        UserHandle.USER_SYSTEM);
14446            } catch (RemoteException e) {
14447            }
14448        }
14449    }
14450
14451    @Override
14452    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14453            int installFlags, String installerPackageName, int userId) {
14454        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14455
14456        final int callingUid = Binder.getCallingUid();
14457        enforceCrossUserPermission(callingUid, userId,
14458                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14459
14460        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14461            try {
14462                if (observer != null) {
14463                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14464                }
14465            } catch (RemoteException re) {
14466            }
14467            return;
14468        }
14469
14470        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14471            installFlags |= PackageManager.INSTALL_FROM_ADB;
14472
14473        } else {
14474            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14475            // about installerPackageName.
14476
14477            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14478            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14479        }
14480
14481        UserHandle user;
14482        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14483            user = UserHandle.ALL;
14484        } else {
14485            user = new UserHandle(userId);
14486        }
14487
14488        // Only system components can circumvent runtime permissions when installing.
14489        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14490                && mContext.checkCallingOrSelfPermission(Manifest.permission
14491                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14492            throw new SecurityException("You need the "
14493                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14494                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14495        }
14496
14497        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14498                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14499            throw new IllegalArgumentException(
14500                    "New installs into ASEC containers no longer supported");
14501        }
14502
14503        final File originFile = new File(originPath);
14504        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14505
14506        final Message msg = mHandler.obtainMessage(INIT_COPY);
14507        final VerificationInfo verificationInfo = new VerificationInfo(
14508                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14509        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14510                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14511                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14512                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14513        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14514        msg.obj = params;
14515
14516        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14517                System.identityHashCode(msg.obj));
14518        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14519                System.identityHashCode(msg.obj));
14520
14521        mHandler.sendMessage(msg);
14522    }
14523
14524
14525    /**
14526     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14527     * it is acting on behalf on an enterprise or the user).
14528     *
14529     * Note that the ordering of the conditionals in this method is important. The checks we perform
14530     * are as follows, in this order:
14531     *
14532     * 1) If the install is being performed by a system app, we can trust the app to have set the
14533     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14534     *    what it is.
14535     * 2) If the install is being performed by a device or profile owner app, the install reason
14536     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14537     *    set the install reason correctly. If the app targets an older SDK version where install
14538     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14539     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14540     * 3) In all other cases, the install is being performed by a regular app that is neither part
14541     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14542     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14543     *    set to enterprise policy and if so, change it to unknown instead.
14544     */
14545    private int fixUpInstallReason(String installerPackageName, int installerUid,
14546            int installReason) {
14547        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14548                == PERMISSION_GRANTED) {
14549            // If the install is being performed by a system app, we trust that app to have set the
14550            // install reason correctly.
14551            return installReason;
14552        }
14553
14554        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14555            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14556        if (dpm != null) {
14557            ComponentName owner = null;
14558            try {
14559                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14560                if (owner == null) {
14561                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14562                }
14563            } catch (RemoteException e) {
14564            }
14565            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14566                // If the install is being performed by a device or profile owner, the install
14567                // reason should be enterprise policy.
14568                return PackageManager.INSTALL_REASON_POLICY;
14569            }
14570        }
14571
14572        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14573            // If the install is being performed by a regular app (i.e. neither system app nor
14574            // device or profile owner), we have no reason to believe that the app is acting on
14575            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14576            // change it to unknown instead.
14577            return PackageManager.INSTALL_REASON_UNKNOWN;
14578        }
14579
14580        // If the install is being performed by a regular app and the install reason was set to any
14581        // value but enterprise policy, leave the install reason unchanged.
14582        return installReason;
14583    }
14584
14585    void installStage(String packageName, File stagedDir, String stagedCid,
14586            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14587            String installerPackageName, int installerUid, UserHandle user,
14588            Certificate[][] certificates) {
14589        if (DEBUG_EPHEMERAL) {
14590            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14591                Slog.d(TAG, "Ephemeral install of " + packageName);
14592            }
14593        }
14594        final VerificationInfo verificationInfo = new VerificationInfo(
14595                sessionParams.originatingUri, sessionParams.referrerUri,
14596                sessionParams.originatingUid, installerUid);
14597
14598        final OriginInfo origin;
14599        if (stagedDir != null) {
14600            origin = OriginInfo.fromStagedFile(stagedDir);
14601        } else {
14602            origin = OriginInfo.fromStagedContainer(stagedCid);
14603        }
14604
14605        final Message msg = mHandler.obtainMessage(INIT_COPY);
14606        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14607                sessionParams.installReason);
14608        final InstallParams params = new InstallParams(origin, null, observer,
14609                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14610                verificationInfo, user, sessionParams.abiOverride,
14611                sessionParams.grantedRuntimePermissions, certificates, installReason);
14612        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14613        msg.obj = params;
14614
14615        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14616                System.identityHashCode(msg.obj));
14617        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14618                System.identityHashCode(msg.obj));
14619
14620        mHandler.sendMessage(msg);
14621    }
14622
14623    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14624            int userId) {
14625        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14626        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14627                false /*startReceiver*/, pkgSetting.appId, userId);
14628
14629        // Send a session commit broadcast
14630        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14631        info.installReason = pkgSetting.getInstallReason(userId);
14632        info.appPackageName = packageName;
14633        sendSessionCommitBroadcast(info, userId);
14634    }
14635
14636    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14637            boolean includeStopped, int appId, int... userIds) {
14638        if (ArrayUtils.isEmpty(userIds)) {
14639            return;
14640        }
14641        Bundle extras = new Bundle(1);
14642        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14643        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14644
14645        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14646                packageName, extras, 0, null, null, userIds);
14647        if (sendBootCompleted) {
14648            mHandler.post(() -> {
14649                        for (int userId : userIds) {
14650                            sendBootCompletedBroadcastToSystemApp(
14651                                    packageName, includeStopped, userId);
14652                        }
14653                    }
14654            );
14655        }
14656    }
14657
14658    /**
14659     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14660     * automatically without needing an explicit launch.
14661     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14662     */
14663    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14664            int userId) {
14665        // If user is not running, the app didn't miss any broadcast
14666        if (!mUserManagerInternal.isUserRunning(userId)) {
14667            return;
14668        }
14669        final IActivityManager am = ActivityManager.getService();
14670        try {
14671            // Deliver LOCKED_BOOT_COMPLETED first
14672            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14673                    .setPackage(packageName);
14674            if (includeStopped) {
14675                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14676            }
14677            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14678            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14679                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14680
14681            // Deliver BOOT_COMPLETED only if user is unlocked
14682            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14683                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14684                if (includeStopped) {
14685                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14686                }
14687                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14688                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14689            }
14690        } catch (RemoteException e) {
14691            throw e.rethrowFromSystemServer();
14692        }
14693    }
14694
14695    @Override
14696    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14697            int userId) {
14698        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14699        PackageSetting pkgSetting;
14700        final int callingUid = Binder.getCallingUid();
14701        enforceCrossUserPermission(callingUid, userId,
14702                true /* requireFullPermission */, true /* checkShell */,
14703                "setApplicationHiddenSetting for user " + userId);
14704
14705        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14706            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14707            return false;
14708        }
14709
14710        long callingId = Binder.clearCallingIdentity();
14711        try {
14712            boolean sendAdded = false;
14713            boolean sendRemoved = false;
14714            // writer
14715            synchronized (mPackages) {
14716                pkgSetting = mSettings.mPackages.get(packageName);
14717                if (pkgSetting == null) {
14718                    return false;
14719                }
14720                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14721                    return false;
14722                }
14723                // Do not allow "android" is being disabled
14724                if ("android".equals(packageName)) {
14725                    Slog.w(TAG, "Cannot hide package: android");
14726                    return false;
14727                }
14728                // Cannot hide static shared libs as they are considered
14729                // a part of the using app (emulating static linking). Also
14730                // static libs are installed always on internal storage.
14731                PackageParser.Package pkg = mPackages.get(packageName);
14732                if (pkg != null && pkg.staticSharedLibName != null) {
14733                    Slog.w(TAG, "Cannot hide package: " + packageName
14734                            + " providing static shared library: "
14735                            + pkg.staticSharedLibName);
14736                    return false;
14737                }
14738                // Only allow protected packages to hide themselves.
14739                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14740                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14741                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14742                    return false;
14743                }
14744
14745                if (pkgSetting.getHidden(userId) != hidden) {
14746                    pkgSetting.setHidden(hidden, userId);
14747                    mSettings.writePackageRestrictionsLPr(userId);
14748                    if (hidden) {
14749                        sendRemoved = true;
14750                    } else {
14751                        sendAdded = true;
14752                    }
14753                }
14754            }
14755            if (sendAdded) {
14756                sendPackageAddedForUser(packageName, pkgSetting, userId);
14757                return true;
14758            }
14759            if (sendRemoved) {
14760                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14761                        "hiding pkg");
14762                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14763                return true;
14764            }
14765        } finally {
14766            Binder.restoreCallingIdentity(callingId);
14767        }
14768        return false;
14769    }
14770
14771    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14772            int userId) {
14773        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14774        info.removedPackage = packageName;
14775        info.installerPackageName = pkgSetting.installerPackageName;
14776        info.removedUsers = new int[] {userId};
14777        info.broadcastUsers = new int[] {userId};
14778        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14779        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14780    }
14781
14782    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14783        if (pkgList.length > 0) {
14784            Bundle extras = new Bundle(1);
14785            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14786
14787            sendPackageBroadcast(
14788                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14789                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14790                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14791                    new int[] {userId});
14792        }
14793    }
14794
14795    /**
14796     * Returns true if application is not found or there was an error. Otherwise it returns
14797     * the hidden state of the package for the given user.
14798     */
14799    @Override
14800    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14801        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14802        final int callingUid = Binder.getCallingUid();
14803        enforceCrossUserPermission(callingUid, userId,
14804                true /* requireFullPermission */, false /* checkShell */,
14805                "getApplicationHidden for user " + userId);
14806        PackageSetting ps;
14807        long callingId = Binder.clearCallingIdentity();
14808        try {
14809            // writer
14810            synchronized (mPackages) {
14811                ps = mSettings.mPackages.get(packageName);
14812                if (ps == null) {
14813                    return true;
14814                }
14815                if (filterAppAccessLPr(ps, callingUid, userId)) {
14816                    return true;
14817                }
14818                return ps.getHidden(userId);
14819            }
14820        } finally {
14821            Binder.restoreCallingIdentity(callingId);
14822        }
14823    }
14824
14825    /**
14826     * @hide
14827     */
14828    @Override
14829    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14830            int installReason) {
14831        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14832                null);
14833        PackageSetting pkgSetting;
14834        final int callingUid = Binder.getCallingUid();
14835        enforceCrossUserPermission(callingUid, userId,
14836                true /* requireFullPermission */, true /* checkShell */,
14837                "installExistingPackage for user " + userId);
14838        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14839            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14840        }
14841
14842        long callingId = Binder.clearCallingIdentity();
14843        try {
14844            boolean installed = false;
14845            final boolean instantApp =
14846                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14847            final boolean fullApp =
14848                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14849
14850            // writer
14851            synchronized (mPackages) {
14852                pkgSetting = mSettings.mPackages.get(packageName);
14853                if (pkgSetting == null) {
14854                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14855                }
14856                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14857                    // only allow the existing package to be used if it's installed as a full
14858                    // application for at least one user
14859                    boolean installAllowed = false;
14860                    for (int checkUserId : sUserManager.getUserIds()) {
14861                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14862                        if (installAllowed) {
14863                            break;
14864                        }
14865                    }
14866                    if (!installAllowed) {
14867                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14868                    }
14869                }
14870                if (!pkgSetting.getInstalled(userId)) {
14871                    pkgSetting.setInstalled(true, userId);
14872                    pkgSetting.setHidden(false, userId);
14873                    pkgSetting.setInstallReason(installReason, userId);
14874                    mSettings.writePackageRestrictionsLPr(userId);
14875                    mSettings.writeKernelMappingLPr(pkgSetting);
14876                    installed = true;
14877                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14878                    // upgrade app from instant to full; we don't allow app downgrade
14879                    installed = true;
14880                }
14881                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14882            }
14883
14884            if (installed) {
14885                if (pkgSetting.pkg != null) {
14886                    synchronized (mInstallLock) {
14887                        // We don't need to freeze for a brand new install
14888                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14889                    }
14890                }
14891                sendPackageAddedForUser(packageName, pkgSetting, userId);
14892                synchronized (mPackages) {
14893                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14894                }
14895            }
14896        } finally {
14897            Binder.restoreCallingIdentity(callingId);
14898        }
14899
14900        return PackageManager.INSTALL_SUCCEEDED;
14901    }
14902
14903    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14904            boolean instantApp, boolean fullApp) {
14905        // no state specified; do nothing
14906        if (!instantApp && !fullApp) {
14907            return;
14908        }
14909        if (userId != UserHandle.USER_ALL) {
14910            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14911                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14912            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14913                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14914            }
14915        } else {
14916            for (int currentUserId : sUserManager.getUserIds()) {
14917                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14918                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14919                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14920                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14921                }
14922            }
14923        }
14924    }
14925
14926    boolean isUserRestricted(int userId, String restrictionKey) {
14927        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14928        if (restrictions.getBoolean(restrictionKey, false)) {
14929            Log.w(TAG, "User is restricted: " + restrictionKey);
14930            return true;
14931        }
14932        return false;
14933    }
14934
14935    @Override
14936    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14937            int userId) {
14938        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14939        final int callingUid = Binder.getCallingUid();
14940        enforceCrossUserPermission(callingUid, userId,
14941                true /* requireFullPermission */, true /* checkShell */,
14942                "setPackagesSuspended for user " + userId);
14943
14944        if (ArrayUtils.isEmpty(packageNames)) {
14945            return packageNames;
14946        }
14947
14948        // List of package names for whom the suspended state has changed.
14949        List<String> changedPackages = new ArrayList<>(packageNames.length);
14950        // List of package names for whom the suspended state is not set as requested in this
14951        // method.
14952        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14953        long callingId = Binder.clearCallingIdentity();
14954        try {
14955            for (int i = 0; i < packageNames.length; i++) {
14956                String packageName = packageNames[i];
14957                boolean changed = false;
14958                final int appId;
14959                synchronized (mPackages) {
14960                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14961                    if (pkgSetting == null
14962                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14963                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14964                                + "\". Skipping suspending/un-suspending.");
14965                        unactionedPackages.add(packageName);
14966                        continue;
14967                    }
14968                    appId = pkgSetting.appId;
14969                    if (pkgSetting.getSuspended(userId) != suspended) {
14970                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14971                            unactionedPackages.add(packageName);
14972                            continue;
14973                        }
14974                        pkgSetting.setSuspended(suspended, userId);
14975                        mSettings.writePackageRestrictionsLPr(userId);
14976                        changed = true;
14977                        changedPackages.add(packageName);
14978                    }
14979                }
14980
14981                if (changed && suspended) {
14982                    killApplication(packageName, UserHandle.getUid(userId, appId),
14983                            "suspending package");
14984                }
14985            }
14986        } finally {
14987            Binder.restoreCallingIdentity(callingId);
14988        }
14989
14990        if (!changedPackages.isEmpty()) {
14991            sendPackagesSuspendedForUser(changedPackages.toArray(
14992                    new String[changedPackages.size()]), userId, suspended);
14993        }
14994
14995        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14996    }
14997
14998    @Override
14999    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15000        final int callingUid = Binder.getCallingUid();
15001        enforceCrossUserPermission(callingUid, userId,
15002                true /* requireFullPermission */, false /* checkShell */,
15003                "isPackageSuspendedForUser for user " + userId);
15004        synchronized (mPackages) {
15005            final PackageSetting ps = mSettings.mPackages.get(packageName);
15006            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15007                throw new IllegalArgumentException("Unknown target package: " + packageName);
15008            }
15009            return ps.getSuspended(userId);
15010        }
15011    }
15012
15013    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15014        if (isPackageDeviceAdmin(packageName, userId)) {
15015            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15016                    + "\": has an active device admin");
15017            return false;
15018        }
15019
15020        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15021        if (packageName.equals(activeLauncherPackageName)) {
15022            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15023                    + "\": contains the active launcher");
15024            return false;
15025        }
15026
15027        if (packageName.equals(mRequiredInstallerPackage)) {
15028            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15029                    + "\": required for package installation");
15030            return false;
15031        }
15032
15033        if (packageName.equals(mRequiredUninstallerPackage)) {
15034            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15035                    + "\": required for package uninstallation");
15036            return false;
15037        }
15038
15039        if (packageName.equals(mRequiredVerifierPackage)) {
15040            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15041                    + "\": required for package verification");
15042            return false;
15043        }
15044
15045        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15046            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15047                    + "\": is the default dialer");
15048            return false;
15049        }
15050
15051        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15052            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15053                    + "\": protected package");
15054            return false;
15055        }
15056
15057        // Cannot suspend static shared libs as they are considered
15058        // a part of the using app (emulating static linking). Also
15059        // static libs are installed always on internal storage.
15060        PackageParser.Package pkg = mPackages.get(packageName);
15061        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15062            Slog.w(TAG, "Cannot suspend package: " + packageName
15063                    + " providing static shared library: "
15064                    + pkg.staticSharedLibName);
15065            return false;
15066        }
15067
15068        return true;
15069    }
15070
15071    private String getActiveLauncherPackageName(int userId) {
15072        Intent intent = new Intent(Intent.ACTION_MAIN);
15073        intent.addCategory(Intent.CATEGORY_HOME);
15074        ResolveInfo resolveInfo = resolveIntent(
15075                intent,
15076                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15077                PackageManager.MATCH_DEFAULT_ONLY,
15078                userId);
15079
15080        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15081    }
15082
15083    private String getDefaultDialerPackageName(int userId) {
15084        synchronized (mPackages) {
15085            return mSettings.getDefaultDialerPackageNameLPw(userId);
15086        }
15087    }
15088
15089    @Override
15090    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15091        mContext.enforceCallingOrSelfPermission(
15092                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15093                "Only package verification agents can verify applications");
15094
15095        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15096        final PackageVerificationResponse response = new PackageVerificationResponse(
15097                verificationCode, Binder.getCallingUid());
15098        msg.arg1 = id;
15099        msg.obj = response;
15100        mHandler.sendMessage(msg);
15101    }
15102
15103    @Override
15104    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15105            long millisecondsToDelay) {
15106        mContext.enforceCallingOrSelfPermission(
15107                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15108                "Only package verification agents can extend verification timeouts");
15109
15110        final PackageVerificationState state = mPendingVerification.get(id);
15111        final PackageVerificationResponse response = new PackageVerificationResponse(
15112                verificationCodeAtTimeout, Binder.getCallingUid());
15113
15114        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15115            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15116        }
15117        if (millisecondsToDelay < 0) {
15118            millisecondsToDelay = 0;
15119        }
15120        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15121                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15122            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15123        }
15124
15125        if ((state != null) && !state.timeoutExtended()) {
15126            state.extendTimeout();
15127
15128            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15129            msg.arg1 = id;
15130            msg.obj = response;
15131            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15132        }
15133    }
15134
15135    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15136            int verificationCode, UserHandle user) {
15137        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15138        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15139        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15140        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15141        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15142
15143        mContext.sendBroadcastAsUser(intent, user,
15144                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15145    }
15146
15147    private ComponentName matchComponentForVerifier(String packageName,
15148            List<ResolveInfo> receivers) {
15149        ActivityInfo targetReceiver = null;
15150
15151        final int NR = receivers.size();
15152        for (int i = 0; i < NR; i++) {
15153            final ResolveInfo info = receivers.get(i);
15154            if (info.activityInfo == null) {
15155                continue;
15156            }
15157
15158            if (packageName.equals(info.activityInfo.packageName)) {
15159                targetReceiver = info.activityInfo;
15160                break;
15161            }
15162        }
15163
15164        if (targetReceiver == null) {
15165            return null;
15166        }
15167
15168        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15169    }
15170
15171    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15172            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15173        if (pkgInfo.verifiers.length == 0) {
15174            return null;
15175        }
15176
15177        final int N = pkgInfo.verifiers.length;
15178        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15179        for (int i = 0; i < N; i++) {
15180            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15181
15182            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15183                    receivers);
15184            if (comp == null) {
15185                continue;
15186            }
15187
15188            final int verifierUid = getUidForVerifier(verifierInfo);
15189            if (verifierUid == -1) {
15190                continue;
15191            }
15192
15193            if (DEBUG_VERIFY) {
15194                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15195                        + " with the correct signature");
15196            }
15197            sufficientVerifiers.add(comp);
15198            verificationState.addSufficientVerifier(verifierUid);
15199        }
15200
15201        return sufficientVerifiers;
15202    }
15203
15204    private int getUidForVerifier(VerifierInfo verifierInfo) {
15205        synchronized (mPackages) {
15206            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15207            if (pkg == null) {
15208                return -1;
15209            } else if (pkg.mSignatures.length != 1) {
15210                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15211                        + " has more than one signature; ignoring");
15212                return -1;
15213            }
15214
15215            /*
15216             * If the public key of the package's signature does not match
15217             * our expected public key, then this is a different package and
15218             * we should skip.
15219             */
15220
15221            final byte[] expectedPublicKey;
15222            try {
15223                final Signature verifierSig = pkg.mSignatures[0];
15224                final PublicKey publicKey = verifierSig.getPublicKey();
15225                expectedPublicKey = publicKey.getEncoded();
15226            } catch (CertificateException e) {
15227                return -1;
15228            }
15229
15230            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15231
15232            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15233                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15234                        + " does not have the expected public key; ignoring");
15235                return -1;
15236            }
15237
15238            return pkg.applicationInfo.uid;
15239        }
15240    }
15241
15242    @Override
15243    public void finishPackageInstall(int token, boolean didLaunch) {
15244        enforceSystemOrRoot("Only the system is allowed to finish installs");
15245
15246        if (DEBUG_INSTALL) {
15247            Slog.v(TAG, "BM finishing package install for " + token);
15248        }
15249        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15250
15251        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15252        mHandler.sendMessage(msg);
15253    }
15254
15255    /**
15256     * Get the verification agent timeout.  Used for both the APK verifier and the
15257     * intent filter verifier.
15258     *
15259     * @return verification timeout in milliseconds
15260     */
15261    private long getVerificationTimeout() {
15262        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15263                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15264                DEFAULT_VERIFICATION_TIMEOUT);
15265    }
15266
15267    /**
15268     * Get the default verification agent response code.
15269     *
15270     * @return default verification response code
15271     */
15272    private int getDefaultVerificationResponse(UserHandle user) {
15273        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15274            return PackageManager.VERIFICATION_REJECT;
15275        }
15276        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15277                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15278                DEFAULT_VERIFICATION_RESPONSE);
15279    }
15280
15281    /**
15282     * Check whether or not package verification has been enabled.
15283     *
15284     * @return true if verification should be performed
15285     */
15286    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15287        if (!DEFAULT_VERIFY_ENABLE) {
15288            return false;
15289        }
15290
15291        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15292
15293        // Check if installing from ADB
15294        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15295            // Do not run verification in a test harness environment
15296            if (ActivityManager.isRunningInTestHarness()) {
15297                return false;
15298            }
15299            if (ensureVerifyAppsEnabled) {
15300                return true;
15301            }
15302            // Check if the developer does not want package verification for ADB installs
15303            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15304                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15305                return false;
15306            }
15307        } else {
15308            // only when not installed from ADB, skip verification for instant apps when
15309            // the installer and verifier are the same.
15310            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15311                if (mInstantAppInstallerActivity != null
15312                        && mInstantAppInstallerActivity.packageName.equals(
15313                                mRequiredVerifierPackage)) {
15314                    try {
15315                        mContext.getSystemService(AppOpsManager.class)
15316                                .checkPackage(installerUid, mRequiredVerifierPackage);
15317                        if (DEBUG_VERIFY) {
15318                            Slog.i(TAG, "disable verification for instant app");
15319                        }
15320                        return false;
15321                    } catch (SecurityException ignore) { }
15322                }
15323            }
15324        }
15325
15326        if (ensureVerifyAppsEnabled) {
15327            return true;
15328        }
15329
15330        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15331                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15332    }
15333
15334    @Override
15335    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15336            throws RemoteException {
15337        mContext.enforceCallingOrSelfPermission(
15338                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15339                "Only intentfilter verification agents can verify applications");
15340
15341        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15342        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15343                Binder.getCallingUid(), verificationCode, failedDomains);
15344        msg.arg1 = id;
15345        msg.obj = response;
15346        mHandler.sendMessage(msg);
15347    }
15348
15349    @Override
15350    public int getIntentVerificationStatus(String packageName, int userId) {
15351        final int callingUid = Binder.getCallingUid();
15352        if (UserHandle.getUserId(callingUid) != userId) {
15353            mContext.enforceCallingOrSelfPermission(
15354                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15355                    "getIntentVerificationStatus" + userId);
15356        }
15357        if (getInstantAppPackageName(callingUid) != null) {
15358            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15359        }
15360        synchronized (mPackages) {
15361            final PackageSetting ps = mSettings.mPackages.get(packageName);
15362            if (ps == null
15363                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15364                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15365            }
15366            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15367        }
15368    }
15369
15370    @Override
15371    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15372        mContext.enforceCallingOrSelfPermission(
15373                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15374
15375        boolean result = false;
15376        synchronized (mPackages) {
15377            final PackageSetting ps = mSettings.mPackages.get(packageName);
15378            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15379                return false;
15380            }
15381            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15382        }
15383        if (result) {
15384            scheduleWritePackageRestrictionsLocked(userId);
15385        }
15386        return result;
15387    }
15388
15389    @Override
15390    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15391            String packageName) {
15392        final int callingUid = Binder.getCallingUid();
15393        if (getInstantAppPackageName(callingUid) != null) {
15394            return ParceledListSlice.emptyList();
15395        }
15396        synchronized (mPackages) {
15397            final PackageSetting ps = mSettings.mPackages.get(packageName);
15398            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15399                return ParceledListSlice.emptyList();
15400            }
15401            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15402        }
15403    }
15404
15405    @Override
15406    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15407        if (TextUtils.isEmpty(packageName)) {
15408            return ParceledListSlice.emptyList();
15409        }
15410        final int callingUid = Binder.getCallingUid();
15411        final int callingUserId = UserHandle.getUserId(callingUid);
15412        synchronized (mPackages) {
15413            PackageParser.Package pkg = mPackages.get(packageName);
15414            if (pkg == null || pkg.activities == null) {
15415                return ParceledListSlice.emptyList();
15416            }
15417            if (pkg.mExtras == null) {
15418                return ParceledListSlice.emptyList();
15419            }
15420            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15421            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15422                return ParceledListSlice.emptyList();
15423            }
15424            final int count = pkg.activities.size();
15425            ArrayList<IntentFilter> result = new ArrayList<>();
15426            for (int n=0; n<count; n++) {
15427                PackageParser.Activity activity = pkg.activities.get(n);
15428                if (activity.intents != null && activity.intents.size() > 0) {
15429                    result.addAll(activity.intents);
15430                }
15431            }
15432            return new ParceledListSlice<>(result);
15433        }
15434    }
15435
15436    @Override
15437    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15438        mContext.enforceCallingOrSelfPermission(
15439                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15440        if (UserHandle.getCallingUserId() != userId) {
15441            mContext.enforceCallingOrSelfPermission(
15442                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15443        }
15444
15445        synchronized (mPackages) {
15446            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15447            if (packageName != null) {
15448                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15449                        packageName, userId);
15450            }
15451            return result;
15452        }
15453    }
15454
15455    @Override
15456    public String getDefaultBrowserPackageName(int userId) {
15457        if (UserHandle.getCallingUserId() != userId) {
15458            mContext.enforceCallingOrSelfPermission(
15459                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15460        }
15461        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15462            return null;
15463        }
15464        synchronized (mPackages) {
15465            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15466        }
15467    }
15468
15469    /**
15470     * Get the "allow unknown sources" setting.
15471     *
15472     * @return the current "allow unknown sources" setting
15473     */
15474    private int getUnknownSourcesSettings() {
15475        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15476                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15477                -1);
15478    }
15479
15480    @Override
15481    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15482        final int callingUid = Binder.getCallingUid();
15483        if (getInstantAppPackageName(callingUid) != null) {
15484            return;
15485        }
15486        // writer
15487        synchronized (mPackages) {
15488            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15489            if (targetPackageSetting == null
15490                    || filterAppAccessLPr(
15491                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15492                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15493            }
15494
15495            PackageSetting installerPackageSetting;
15496            if (installerPackageName != null) {
15497                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15498                if (installerPackageSetting == null) {
15499                    throw new IllegalArgumentException("Unknown installer package: "
15500                            + installerPackageName);
15501                }
15502            } else {
15503                installerPackageSetting = null;
15504            }
15505
15506            Signature[] callerSignature;
15507            Object obj = mSettings.getUserIdLPr(callingUid);
15508            if (obj != null) {
15509                if (obj instanceof SharedUserSetting) {
15510                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15511                } else if (obj instanceof PackageSetting) {
15512                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15513                } else {
15514                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15515                }
15516            } else {
15517                throw new SecurityException("Unknown calling UID: " + callingUid);
15518            }
15519
15520            // Verify: can't set installerPackageName to a package that is
15521            // not signed with the same cert as the caller.
15522            if (installerPackageSetting != null) {
15523                if (compareSignatures(callerSignature,
15524                        installerPackageSetting.signatures.mSignatures)
15525                        != PackageManager.SIGNATURE_MATCH) {
15526                    throw new SecurityException(
15527                            "Caller does not have same cert as new installer package "
15528                            + installerPackageName);
15529                }
15530            }
15531
15532            // Verify: if target already has an installer package, it must
15533            // be signed with the same cert as the caller.
15534            if (targetPackageSetting.installerPackageName != null) {
15535                PackageSetting setting = mSettings.mPackages.get(
15536                        targetPackageSetting.installerPackageName);
15537                // If the currently set package isn't valid, then it's always
15538                // okay to change it.
15539                if (setting != null) {
15540                    if (compareSignatures(callerSignature,
15541                            setting.signatures.mSignatures)
15542                            != PackageManager.SIGNATURE_MATCH) {
15543                        throw new SecurityException(
15544                                "Caller does not have same cert as old installer package "
15545                                + targetPackageSetting.installerPackageName);
15546                    }
15547                }
15548            }
15549
15550            // Okay!
15551            targetPackageSetting.installerPackageName = installerPackageName;
15552            if (installerPackageName != null) {
15553                mSettings.mInstallerPackages.add(installerPackageName);
15554            }
15555            scheduleWriteSettingsLocked();
15556        }
15557    }
15558
15559    @Override
15560    public void setApplicationCategoryHint(String packageName, int categoryHint,
15561            String callerPackageName) {
15562        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15563            throw new SecurityException("Instant applications don't have access to this method");
15564        }
15565        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15566                callerPackageName);
15567        synchronized (mPackages) {
15568            PackageSetting ps = mSettings.mPackages.get(packageName);
15569            if (ps == null) {
15570                throw new IllegalArgumentException("Unknown target package " + packageName);
15571            }
15572            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15573                throw new IllegalArgumentException("Unknown target package " + packageName);
15574            }
15575            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15576                throw new IllegalArgumentException("Calling package " + callerPackageName
15577                        + " is not installer for " + packageName);
15578            }
15579
15580            if (ps.categoryHint != categoryHint) {
15581                ps.categoryHint = categoryHint;
15582                scheduleWriteSettingsLocked();
15583            }
15584        }
15585    }
15586
15587    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15588        // Queue up an async operation since the package installation may take a little while.
15589        mHandler.post(new Runnable() {
15590            public void run() {
15591                mHandler.removeCallbacks(this);
15592                 // Result object to be returned
15593                PackageInstalledInfo res = new PackageInstalledInfo();
15594                res.setReturnCode(currentStatus);
15595                res.uid = -1;
15596                res.pkg = null;
15597                res.removedInfo = null;
15598                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15599                    args.doPreInstall(res.returnCode);
15600                    synchronized (mInstallLock) {
15601                        installPackageTracedLI(args, res);
15602                    }
15603                    args.doPostInstall(res.returnCode, res.uid);
15604                }
15605
15606                // A restore should be performed at this point if (a) the install
15607                // succeeded, (b) the operation is not an update, and (c) the new
15608                // package has not opted out of backup participation.
15609                final boolean update = res.removedInfo != null
15610                        && res.removedInfo.removedPackage != null;
15611                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15612                boolean doRestore = !update
15613                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15614
15615                // Set up the post-install work request bookkeeping.  This will be used
15616                // and cleaned up by the post-install event handling regardless of whether
15617                // there's a restore pass performed.  Token values are >= 1.
15618                int token;
15619                if (mNextInstallToken < 0) mNextInstallToken = 1;
15620                token = mNextInstallToken++;
15621
15622                PostInstallData data = new PostInstallData(args, res);
15623                mRunningInstalls.put(token, data);
15624                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15625
15626                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15627                    // Pass responsibility to the Backup Manager.  It will perform a
15628                    // restore if appropriate, then pass responsibility back to the
15629                    // Package Manager to run the post-install observer callbacks
15630                    // and broadcasts.
15631                    IBackupManager bm = IBackupManager.Stub.asInterface(
15632                            ServiceManager.getService(Context.BACKUP_SERVICE));
15633                    if (bm != null) {
15634                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15635                                + " to BM for possible restore");
15636                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15637                        try {
15638                            // TODO: http://b/22388012
15639                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15640                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15641                            } else {
15642                                doRestore = false;
15643                            }
15644                        } catch (RemoteException e) {
15645                            // can't happen; the backup manager is local
15646                        } catch (Exception e) {
15647                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15648                            doRestore = false;
15649                        }
15650                    } else {
15651                        Slog.e(TAG, "Backup Manager not found!");
15652                        doRestore = false;
15653                    }
15654                }
15655
15656                if (!doRestore) {
15657                    // No restore possible, or the Backup Manager was mysteriously not
15658                    // available -- just fire the post-install work request directly.
15659                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15660
15661                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15662
15663                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15664                    mHandler.sendMessage(msg);
15665                }
15666            }
15667        });
15668    }
15669
15670    /**
15671     * Callback from PackageSettings whenever an app is first transitioned out of the
15672     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15673     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15674     * here whether the app is the target of an ongoing install, and only send the
15675     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15676     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15677     * handling.
15678     */
15679    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15680        // Serialize this with the rest of the install-process message chain.  In the
15681        // restore-at-install case, this Runnable will necessarily run before the
15682        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15683        // are coherent.  In the non-restore case, the app has already completed install
15684        // and been launched through some other means, so it is not in a problematic
15685        // state for observers to see the FIRST_LAUNCH signal.
15686        mHandler.post(new Runnable() {
15687            @Override
15688            public void run() {
15689                for (int i = 0; i < mRunningInstalls.size(); i++) {
15690                    final PostInstallData data = mRunningInstalls.valueAt(i);
15691                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15692                        continue;
15693                    }
15694                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15695                        // right package; but is it for the right user?
15696                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15697                            if (userId == data.res.newUsers[uIndex]) {
15698                                if (DEBUG_BACKUP) {
15699                                    Slog.i(TAG, "Package " + pkgName
15700                                            + " being restored so deferring FIRST_LAUNCH");
15701                                }
15702                                return;
15703                            }
15704                        }
15705                    }
15706                }
15707                // didn't find it, so not being restored
15708                if (DEBUG_BACKUP) {
15709                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15710                }
15711                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15712            }
15713        });
15714    }
15715
15716    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15717        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15718                installerPkg, null, userIds);
15719    }
15720
15721    private abstract class HandlerParams {
15722        private static final int MAX_RETRIES = 4;
15723
15724        /**
15725         * Number of times startCopy() has been attempted and had a non-fatal
15726         * error.
15727         */
15728        private int mRetries = 0;
15729
15730        /** User handle for the user requesting the information or installation. */
15731        private final UserHandle mUser;
15732        String traceMethod;
15733        int traceCookie;
15734
15735        HandlerParams(UserHandle user) {
15736            mUser = user;
15737        }
15738
15739        UserHandle getUser() {
15740            return mUser;
15741        }
15742
15743        HandlerParams setTraceMethod(String traceMethod) {
15744            this.traceMethod = traceMethod;
15745            return this;
15746        }
15747
15748        HandlerParams setTraceCookie(int traceCookie) {
15749            this.traceCookie = traceCookie;
15750            return this;
15751        }
15752
15753        final boolean startCopy() {
15754            boolean res;
15755            try {
15756                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15757
15758                if (++mRetries > MAX_RETRIES) {
15759                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15760                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15761                    handleServiceError();
15762                    return false;
15763                } else {
15764                    handleStartCopy();
15765                    res = true;
15766                }
15767            } catch (RemoteException e) {
15768                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15769                mHandler.sendEmptyMessage(MCS_RECONNECT);
15770                res = false;
15771            }
15772            handleReturnCode();
15773            return res;
15774        }
15775
15776        final void serviceError() {
15777            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15778            handleServiceError();
15779            handleReturnCode();
15780        }
15781
15782        abstract void handleStartCopy() throws RemoteException;
15783        abstract void handleServiceError();
15784        abstract void handleReturnCode();
15785    }
15786
15787    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15788        for (File path : paths) {
15789            try {
15790                mcs.clearDirectory(path.getAbsolutePath());
15791            } catch (RemoteException e) {
15792            }
15793        }
15794    }
15795
15796    static class OriginInfo {
15797        /**
15798         * Location where install is coming from, before it has been
15799         * copied/renamed into place. This could be a single monolithic APK
15800         * file, or a cluster directory. This location may be untrusted.
15801         */
15802        final File file;
15803        final String cid;
15804
15805        /**
15806         * Flag indicating that {@link #file} or {@link #cid} has already been
15807         * staged, meaning downstream users don't need to defensively copy the
15808         * contents.
15809         */
15810        final boolean staged;
15811
15812        /**
15813         * Flag indicating that {@link #file} or {@link #cid} is an already
15814         * installed app that is being moved.
15815         */
15816        final boolean existing;
15817
15818        final String resolvedPath;
15819        final File resolvedFile;
15820
15821        static OriginInfo fromNothing() {
15822            return new OriginInfo(null, null, false, false);
15823        }
15824
15825        static OriginInfo fromUntrustedFile(File file) {
15826            return new OriginInfo(file, null, false, false);
15827        }
15828
15829        static OriginInfo fromExistingFile(File file) {
15830            return new OriginInfo(file, null, false, true);
15831        }
15832
15833        static OriginInfo fromStagedFile(File file) {
15834            return new OriginInfo(file, null, true, false);
15835        }
15836
15837        static OriginInfo fromStagedContainer(String cid) {
15838            return new OriginInfo(null, cid, true, false);
15839        }
15840
15841        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15842            this.file = file;
15843            this.cid = cid;
15844            this.staged = staged;
15845            this.existing = existing;
15846
15847            if (cid != null) {
15848                resolvedPath = PackageHelper.getSdDir(cid);
15849                resolvedFile = new File(resolvedPath);
15850            } else if (file != null) {
15851                resolvedPath = file.getAbsolutePath();
15852                resolvedFile = file;
15853            } else {
15854                resolvedPath = null;
15855                resolvedFile = null;
15856            }
15857        }
15858    }
15859
15860    static class MoveInfo {
15861        final int moveId;
15862        final String fromUuid;
15863        final String toUuid;
15864        final String packageName;
15865        final String dataAppName;
15866        final int appId;
15867        final String seinfo;
15868        final int targetSdkVersion;
15869
15870        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15871                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15872            this.moveId = moveId;
15873            this.fromUuid = fromUuid;
15874            this.toUuid = toUuid;
15875            this.packageName = packageName;
15876            this.dataAppName = dataAppName;
15877            this.appId = appId;
15878            this.seinfo = seinfo;
15879            this.targetSdkVersion = targetSdkVersion;
15880        }
15881    }
15882
15883    static class VerificationInfo {
15884        /** A constant used to indicate that a uid value is not present. */
15885        public static final int NO_UID = -1;
15886
15887        /** URI referencing where the package was downloaded from. */
15888        final Uri originatingUri;
15889
15890        /** HTTP referrer URI associated with the originatingURI. */
15891        final Uri referrer;
15892
15893        /** UID of the application that the install request originated from. */
15894        final int originatingUid;
15895
15896        /** UID of application requesting the install */
15897        final int installerUid;
15898
15899        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15900            this.originatingUri = originatingUri;
15901            this.referrer = referrer;
15902            this.originatingUid = originatingUid;
15903            this.installerUid = installerUid;
15904        }
15905    }
15906
15907    class InstallParams extends HandlerParams {
15908        final OriginInfo origin;
15909        final MoveInfo move;
15910        final IPackageInstallObserver2 observer;
15911        int installFlags;
15912        final String installerPackageName;
15913        final String volumeUuid;
15914        private InstallArgs mArgs;
15915        private int mRet;
15916        final String packageAbiOverride;
15917        final String[] grantedRuntimePermissions;
15918        final VerificationInfo verificationInfo;
15919        final Certificate[][] certificates;
15920        final int installReason;
15921
15922        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15923                int installFlags, String installerPackageName, String volumeUuid,
15924                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15925                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15926            super(user);
15927            this.origin = origin;
15928            this.move = move;
15929            this.observer = observer;
15930            this.installFlags = installFlags;
15931            this.installerPackageName = installerPackageName;
15932            this.volumeUuid = volumeUuid;
15933            this.verificationInfo = verificationInfo;
15934            this.packageAbiOverride = packageAbiOverride;
15935            this.grantedRuntimePermissions = grantedPermissions;
15936            this.certificates = certificates;
15937            this.installReason = installReason;
15938        }
15939
15940        @Override
15941        public String toString() {
15942            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15943                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15944        }
15945
15946        private int installLocationPolicy(PackageInfoLite pkgLite) {
15947            String packageName = pkgLite.packageName;
15948            int installLocation = pkgLite.installLocation;
15949            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15950            // reader
15951            synchronized (mPackages) {
15952                // Currently installed package which the new package is attempting to replace or
15953                // null if no such package is installed.
15954                PackageParser.Package installedPkg = mPackages.get(packageName);
15955                // Package which currently owns the data which the new package will own if installed.
15956                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15957                // will be null whereas dataOwnerPkg will contain information about the package
15958                // which was uninstalled while keeping its data.
15959                PackageParser.Package dataOwnerPkg = installedPkg;
15960                if (dataOwnerPkg  == null) {
15961                    PackageSetting ps = mSettings.mPackages.get(packageName);
15962                    if (ps != null) {
15963                        dataOwnerPkg = ps.pkg;
15964                    }
15965                }
15966
15967                if (dataOwnerPkg != null) {
15968                    // If installed, the package will get access to data left on the device by its
15969                    // predecessor. As a security measure, this is permited only if this is not a
15970                    // version downgrade or if the predecessor package is marked as debuggable and
15971                    // a downgrade is explicitly requested.
15972                    //
15973                    // On debuggable platform builds, downgrades are permitted even for
15974                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15975                    // not offer security guarantees and thus it's OK to disable some security
15976                    // mechanisms to make debugging/testing easier on those builds. However, even on
15977                    // debuggable builds downgrades of packages are permitted only if requested via
15978                    // installFlags. This is because we aim to keep the behavior of debuggable
15979                    // platform builds as close as possible to the behavior of non-debuggable
15980                    // platform builds.
15981                    final boolean downgradeRequested =
15982                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15983                    final boolean packageDebuggable =
15984                                (dataOwnerPkg.applicationInfo.flags
15985                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15986                    final boolean downgradePermitted =
15987                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15988                    if (!downgradePermitted) {
15989                        try {
15990                            checkDowngrade(dataOwnerPkg, pkgLite);
15991                        } catch (PackageManagerException e) {
15992                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15993                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15994                        }
15995                    }
15996                }
15997
15998                if (installedPkg != null) {
15999                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16000                        // Check for updated system application.
16001                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16002                            if (onSd) {
16003                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16004                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16005                            }
16006                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16007                        } else {
16008                            if (onSd) {
16009                                // Install flag overrides everything.
16010                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16011                            }
16012                            // If current upgrade specifies particular preference
16013                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16014                                // Application explicitly specified internal.
16015                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16016                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16017                                // App explictly prefers external. Let policy decide
16018                            } else {
16019                                // Prefer previous location
16020                                if (isExternal(installedPkg)) {
16021                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16022                                }
16023                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16024                            }
16025                        }
16026                    } else {
16027                        // Invalid install. Return error code
16028                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16029                    }
16030                }
16031            }
16032            // All the special cases have been taken care of.
16033            // Return result based on recommended install location.
16034            if (onSd) {
16035                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16036            }
16037            return pkgLite.recommendedInstallLocation;
16038        }
16039
16040        /*
16041         * Invoke remote method to get package information and install
16042         * location values. Override install location based on default
16043         * policy if needed and then create install arguments based
16044         * on the install location.
16045         */
16046        public void handleStartCopy() throws RemoteException {
16047            int ret = PackageManager.INSTALL_SUCCEEDED;
16048
16049            // If we're already staged, we've firmly committed to an install location
16050            if (origin.staged) {
16051                if (origin.file != null) {
16052                    installFlags |= PackageManager.INSTALL_INTERNAL;
16053                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16054                } else if (origin.cid != null) {
16055                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16056                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16057                } else {
16058                    throw new IllegalStateException("Invalid stage location");
16059                }
16060            }
16061
16062            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16063            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16064            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16065            PackageInfoLite pkgLite = null;
16066
16067            if (onInt && onSd) {
16068                // Check if both bits are set.
16069                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16070                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16071            } else if (onSd && ephemeral) {
16072                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16073                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16074            } else {
16075                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16076                        packageAbiOverride);
16077
16078                if (DEBUG_EPHEMERAL && ephemeral) {
16079                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16080                }
16081
16082                /*
16083                 * If we have too little free space, try to free cache
16084                 * before giving up.
16085                 */
16086                if (!origin.staged && pkgLite.recommendedInstallLocation
16087                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16088                    // TODO: focus freeing disk space on the target device
16089                    final StorageManager storage = StorageManager.from(mContext);
16090                    final long lowThreshold = storage.getStorageLowBytes(
16091                            Environment.getDataDirectory());
16092
16093                    final long sizeBytes = mContainerService.calculateInstalledSize(
16094                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16095
16096                    try {
16097                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16098                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16099                                installFlags, packageAbiOverride);
16100                    } catch (InstallerException e) {
16101                        Slog.w(TAG, "Failed to free cache", e);
16102                    }
16103
16104                    /*
16105                     * The cache free must have deleted the file we
16106                     * downloaded to install.
16107                     *
16108                     * TODO: fix the "freeCache" call to not delete
16109                     *       the file we care about.
16110                     */
16111                    if (pkgLite.recommendedInstallLocation
16112                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16113                        pkgLite.recommendedInstallLocation
16114                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16115                    }
16116                }
16117            }
16118
16119            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16120                int loc = pkgLite.recommendedInstallLocation;
16121                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16122                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16123                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16124                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16125                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16126                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16127                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16128                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16129                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16130                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16131                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16132                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16133                } else {
16134                    // Override with defaults if needed.
16135                    loc = installLocationPolicy(pkgLite);
16136                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16137                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16138                    } else if (!onSd && !onInt) {
16139                        // Override install location with flags
16140                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16141                            // Set the flag to install on external media.
16142                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16143                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16144                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16145                            if (DEBUG_EPHEMERAL) {
16146                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16147                            }
16148                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16149                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16150                                    |PackageManager.INSTALL_INTERNAL);
16151                        } else {
16152                            // Make sure the flag for installing on external
16153                            // media is unset
16154                            installFlags |= PackageManager.INSTALL_INTERNAL;
16155                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16156                        }
16157                    }
16158                }
16159            }
16160
16161            final InstallArgs args = createInstallArgs(this);
16162            mArgs = args;
16163
16164            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16165                // TODO: http://b/22976637
16166                // Apps installed for "all" users use the device owner to verify the app
16167                UserHandle verifierUser = getUser();
16168                if (verifierUser == UserHandle.ALL) {
16169                    verifierUser = UserHandle.SYSTEM;
16170                }
16171
16172                /*
16173                 * Determine if we have any installed package verifiers. If we
16174                 * do, then we'll defer to them to verify the packages.
16175                 */
16176                final int requiredUid = mRequiredVerifierPackage == null ? -1
16177                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16178                                verifierUser.getIdentifier());
16179                final int installerUid =
16180                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16181                if (!origin.existing && requiredUid != -1
16182                        && isVerificationEnabled(
16183                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16184                    final Intent verification = new Intent(
16185                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16186                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16187                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16188                            PACKAGE_MIME_TYPE);
16189                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16190
16191                    // Query all live verifiers based on current user state
16192                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16193                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
16194
16195                    if (DEBUG_VERIFY) {
16196                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16197                                + verification.toString() + " with " + pkgLite.verifiers.length
16198                                + " optional verifiers");
16199                    }
16200
16201                    final int verificationId = mPendingVerificationToken++;
16202
16203                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16204
16205                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16206                            installerPackageName);
16207
16208                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16209                            installFlags);
16210
16211                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16212                            pkgLite.packageName);
16213
16214                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16215                            pkgLite.versionCode);
16216
16217                    if (verificationInfo != null) {
16218                        if (verificationInfo.originatingUri != null) {
16219                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16220                                    verificationInfo.originatingUri);
16221                        }
16222                        if (verificationInfo.referrer != null) {
16223                            verification.putExtra(Intent.EXTRA_REFERRER,
16224                                    verificationInfo.referrer);
16225                        }
16226                        if (verificationInfo.originatingUid >= 0) {
16227                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16228                                    verificationInfo.originatingUid);
16229                        }
16230                        if (verificationInfo.installerUid >= 0) {
16231                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16232                                    verificationInfo.installerUid);
16233                        }
16234                    }
16235
16236                    final PackageVerificationState verificationState = new PackageVerificationState(
16237                            requiredUid, args);
16238
16239                    mPendingVerification.append(verificationId, verificationState);
16240
16241                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16242                            receivers, verificationState);
16243
16244                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16245                    final long idleDuration = getVerificationTimeout();
16246
16247                    /*
16248                     * If any sufficient verifiers were listed in the package
16249                     * manifest, attempt to ask them.
16250                     */
16251                    if (sufficientVerifiers != null) {
16252                        final int N = sufficientVerifiers.size();
16253                        if (N == 0) {
16254                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16255                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16256                        } else {
16257                            for (int i = 0; i < N; i++) {
16258                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16259                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16260                                        verifierComponent.getPackageName(), idleDuration,
16261                                        verifierUser.getIdentifier(), false, "package verifier");
16262
16263                                final Intent sufficientIntent = new Intent(verification);
16264                                sufficientIntent.setComponent(verifierComponent);
16265                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16266                            }
16267                        }
16268                    }
16269
16270                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16271                            mRequiredVerifierPackage, receivers);
16272                    if (ret == PackageManager.INSTALL_SUCCEEDED
16273                            && mRequiredVerifierPackage != null) {
16274                        Trace.asyncTraceBegin(
16275                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16276                        /*
16277                         * Send the intent to the required verification agent,
16278                         * but only start the verification timeout after the
16279                         * target BroadcastReceivers have run.
16280                         */
16281                        verification.setComponent(requiredVerifierComponent);
16282                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16283                                mRequiredVerifierPackage, idleDuration,
16284                                verifierUser.getIdentifier(), false, "package verifier");
16285                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16286                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16287                                new BroadcastReceiver() {
16288                                    @Override
16289                                    public void onReceive(Context context, Intent intent) {
16290                                        final Message msg = mHandler
16291                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16292                                        msg.arg1 = verificationId;
16293                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16294                                    }
16295                                }, null, 0, null, null);
16296
16297                        /*
16298                         * We don't want the copy to proceed until verification
16299                         * succeeds, so null out this field.
16300                         */
16301                        mArgs = null;
16302                    }
16303                } else {
16304                    /*
16305                     * No package verification is enabled, so immediately start
16306                     * the remote call to initiate copy using temporary file.
16307                     */
16308                    ret = args.copyApk(mContainerService, true);
16309                }
16310            }
16311
16312            mRet = ret;
16313        }
16314
16315        @Override
16316        void handleReturnCode() {
16317            // If mArgs is null, then MCS couldn't be reached. When it
16318            // reconnects, it will try again to install. At that point, this
16319            // will succeed.
16320            if (mArgs != null) {
16321                processPendingInstall(mArgs, mRet);
16322            }
16323        }
16324
16325        @Override
16326        void handleServiceError() {
16327            mArgs = createInstallArgs(this);
16328            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16329        }
16330
16331        public boolean isForwardLocked() {
16332            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16333        }
16334    }
16335
16336    /**
16337     * Used during creation of InstallArgs
16338     *
16339     * @param installFlags package installation flags
16340     * @return true if should be installed on external storage
16341     */
16342    private static boolean installOnExternalAsec(int installFlags) {
16343        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16344            return false;
16345        }
16346        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16347            return true;
16348        }
16349        return false;
16350    }
16351
16352    /**
16353     * Used during creation of InstallArgs
16354     *
16355     * @param installFlags package installation flags
16356     * @return true if should be installed as forward locked
16357     */
16358    private static boolean installForwardLocked(int installFlags) {
16359        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16360    }
16361
16362    private InstallArgs createInstallArgs(InstallParams params) {
16363        if (params.move != null) {
16364            return new MoveInstallArgs(params);
16365        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16366            return new AsecInstallArgs(params);
16367        } else {
16368            return new FileInstallArgs(params);
16369        }
16370    }
16371
16372    /**
16373     * Create args that describe an existing installed package. Typically used
16374     * when cleaning up old installs, or used as a move source.
16375     */
16376    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16377            String resourcePath, String[] instructionSets) {
16378        final boolean isInAsec;
16379        if (installOnExternalAsec(installFlags)) {
16380            /* Apps on SD card are always in ASEC containers. */
16381            isInAsec = true;
16382        } else if (installForwardLocked(installFlags)
16383                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16384            /*
16385             * Forward-locked apps are only in ASEC containers if they're the
16386             * new style
16387             */
16388            isInAsec = true;
16389        } else {
16390            isInAsec = false;
16391        }
16392
16393        if (isInAsec) {
16394            return new AsecInstallArgs(codePath, instructionSets,
16395                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16396        } else {
16397            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16398        }
16399    }
16400
16401    static abstract class InstallArgs {
16402        /** @see InstallParams#origin */
16403        final OriginInfo origin;
16404        /** @see InstallParams#move */
16405        final MoveInfo move;
16406
16407        final IPackageInstallObserver2 observer;
16408        // Always refers to PackageManager flags only
16409        final int installFlags;
16410        final String installerPackageName;
16411        final String volumeUuid;
16412        final UserHandle user;
16413        final String abiOverride;
16414        final String[] installGrantPermissions;
16415        /** If non-null, drop an async trace when the install completes */
16416        final String traceMethod;
16417        final int traceCookie;
16418        final Certificate[][] certificates;
16419        final int installReason;
16420
16421        // The list of instruction sets supported by this app. This is currently
16422        // only used during the rmdex() phase to clean up resources. We can get rid of this
16423        // if we move dex files under the common app path.
16424        /* nullable */ String[] instructionSets;
16425
16426        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16427                int installFlags, String installerPackageName, String volumeUuid,
16428                UserHandle user, String[] instructionSets,
16429                String abiOverride, String[] installGrantPermissions,
16430                String traceMethod, int traceCookie, Certificate[][] certificates,
16431                int installReason) {
16432            this.origin = origin;
16433            this.move = move;
16434            this.installFlags = installFlags;
16435            this.observer = observer;
16436            this.installerPackageName = installerPackageName;
16437            this.volumeUuid = volumeUuid;
16438            this.user = user;
16439            this.instructionSets = instructionSets;
16440            this.abiOverride = abiOverride;
16441            this.installGrantPermissions = installGrantPermissions;
16442            this.traceMethod = traceMethod;
16443            this.traceCookie = traceCookie;
16444            this.certificates = certificates;
16445            this.installReason = installReason;
16446        }
16447
16448        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16449        abstract int doPreInstall(int status);
16450
16451        /**
16452         * Rename package into final resting place. All paths on the given
16453         * scanned package should be updated to reflect the rename.
16454         */
16455        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16456        abstract int doPostInstall(int status, int uid);
16457
16458        /** @see PackageSettingBase#codePathString */
16459        abstract String getCodePath();
16460        /** @see PackageSettingBase#resourcePathString */
16461        abstract String getResourcePath();
16462
16463        // Need installer lock especially for dex file removal.
16464        abstract void cleanUpResourcesLI();
16465        abstract boolean doPostDeleteLI(boolean delete);
16466
16467        /**
16468         * Called before the source arguments are copied. This is used mostly
16469         * for MoveParams when it needs to read the source file to put it in the
16470         * destination.
16471         */
16472        int doPreCopy() {
16473            return PackageManager.INSTALL_SUCCEEDED;
16474        }
16475
16476        /**
16477         * Called after the source arguments are copied. This is used mostly for
16478         * MoveParams when it needs to read the source file to put it in the
16479         * destination.
16480         */
16481        int doPostCopy(int uid) {
16482            return PackageManager.INSTALL_SUCCEEDED;
16483        }
16484
16485        protected boolean isFwdLocked() {
16486            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16487        }
16488
16489        protected boolean isExternalAsec() {
16490            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16491        }
16492
16493        protected boolean isEphemeral() {
16494            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16495        }
16496
16497        UserHandle getUser() {
16498            return user;
16499        }
16500    }
16501
16502    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16503        if (!allCodePaths.isEmpty()) {
16504            if (instructionSets == null) {
16505                throw new IllegalStateException("instructionSet == null");
16506            }
16507            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16508            for (String codePath : allCodePaths) {
16509                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16510                    try {
16511                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16512                    } catch (InstallerException ignored) {
16513                    }
16514                }
16515            }
16516        }
16517    }
16518
16519    /**
16520     * Logic to handle installation of non-ASEC applications, including copying
16521     * and renaming logic.
16522     */
16523    class FileInstallArgs extends InstallArgs {
16524        private File codeFile;
16525        private File resourceFile;
16526
16527        // Example topology:
16528        // /data/app/com.example/base.apk
16529        // /data/app/com.example/split_foo.apk
16530        // /data/app/com.example/lib/arm/libfoo.so
16531        // /data/app/com.example/lib/arm64/libfoo.so
16532        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16533
16534        /** New install */
16535        FileInstallArgs(InstallParams params) {
16536            super(params.origin, params.move, params.observer, params.installFlags,
16537                    params.installerPackageName, params.volumeUuid,
16538                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16539                    params.grantedRuntimePermissions,
16540                    params.traceMethod, params.traceCookie, params.certificates,
16541                    params.installReason);
16542            if (isFwdLocked()) {
16543                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16544            }
16545        }
16546
16547        /** Existing install */
16548        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16549            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16550                    null, null, null, 0, null /*certificates*/,
16551                    PackageManager.INSTALL_REASON_UNKNOWN);
16552            this.codeFile = (codePath != null) ? new File(codePath) : null;
16553            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16554        }
16555
16556        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16557            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16558            try {
16559                return doCopyApk(imcs, temp);
16560            } finally {
16561                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16562            }
16563        }
16564
16565        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16566            if (origin.staged) {
16567                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16568                codeFile = origin.file;
16569                resourceFile = origin.file;
16570                return PackageManager.INSTALL_SUCCEEDED;
16571            }
16572
16573            try {
16574                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16575                final File tempDir =
16576                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16577                codeFile = tempDir;
16578                resourceFile = tempDir;
16579            } catch (IOException e) {
16580                Slog.w(TAG, "Failed to create copy file: " + e);
16581                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16582            }
16583
16584            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16585                @Override
16586                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16587                    if (!FileUtils.isValidExtFilename(name)) {
16588                        throw new IllegalArgumentException("Invalid filename: " + name);
16589                    }
16590                    try {
16591                        final File file = new File(codeFile, name);
16592                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16593                                O_RDWR | O_CREAT, 0644);
16594                        Os.chmod(file.getAbsolutePath(), 0644);
16595                        return new ParcelFileDescriptor(fd);
16596                    } catch (ErrnoException e) {
16597                        throw new RemoteException("Failed to open: " + e.getMessage());
16598                    }
16599                }
16600            };
16601
16602            int ret = PackageManager.INSTALL_SUCCEEDED;
16603            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16604            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16605                Slog.e(TAG, "Failed to copy package");
16606                return ret;
16607            }
16608
16609            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16610            NativeLibraryHelper.Handle handle = null;
16611            try {
16612                handle = NativeLibraryHelper.Handle.create(codeFile);
16613                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16614                        abiOverride);
16615            } catch (IOException e) {
16616                Slog.e(TAG, "Copying native libraries failed", e);
16617                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16618            } finally {
16619                IoUtils.closeQuietly(handle);
16620            }
16621
16622            return ret;
16623        }
16624
16625        int doPreInstall(int status) {
16626            if (status != PackageManager.INSTALL_SUCCEEDED) {
16627                cleanUp();
16628            }
16629            return status;
16630        }
16631
16632        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16633            if (status != PackageManager.INSTALL_SUCCEEDED) {
16634                cleanUp();
16635                return false;
16636            }
16637
16638            final File targetDir = codeFile.getParentFile();
16639            final File beforeCodeFile = codeFile;
16640            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16641
16642            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16643            try {
16644                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16645            } catch (ErrnoException e) {
16646                Slog.w(TAG, "Failed to rename", e);
16647                return false;
16648            }
16649
16650            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16651                Slog.w(TAG, "Failed to restorecon");
16652                return false;
16653            }
16654
16655            // Reflect the rename internally
16656            codeFile = afterCodeFile;
16657            resourceFile = afterCodeFile;
16658
16659            // Reflect the rename in scanned details
16660            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16661            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16662                    afterCodeFile, pkg.baseCodePath));
16663            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16664                    afterCodeFile, pkg.splitCodePaths));
16665
16666            // Reflect the rename in app info
16667            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16668            pkg.setApplicationInfoCodePath(pkg.codePath);
16669            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16670            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16671            pkg.setApplicationInfoResourcePath(pkg.codePath);
16672            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16673            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16674
16675            return true;
16676        }
16677
16678        int doPostInstall(int status, int uid) {
16679            if (status != PackageManager.INSTALL_SUCCEEDED) {
16680                cleanUp();
16681            }
16682            return status;
16683        }
16684
16685        @Override
16686        String getCodePath() {
16687            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16688        }
16689
16690        @Override
16691        String getResourcePath() {
16692            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16693        }
16694
16695        private boolean cleanUp() {
16696            if (codeFile == null || !codeFile.exists()) {
16697                return false;
16698            }
16699
16700            removeCodePathLI(codeFile);
16701
16702            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16703                resourceFile.delete();
16704            }
16705
16706            return true;
16707        }
16708
16709        void cleanUpResourcesLI() {
16710            // Try enumerating all code paths before deleting
16711            List<String> allCodePaths = Collections.EMPTY_LIST;
16712            if (codeFile != null && codeFile.exists()) {
16713                try {
16714                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16715                    allCodePaths = pkg.getAllCodePaths();
16716                } catch (PackageParserException e) {
16717                    // Ignored; we tried our best
16718                }
16719            }
16720
16721            cleanUp();
16722            removeDexFiles(allCodePaths, instructionSets);
16723        }
16724
16725        boolean doPostDeleteLI(boolean delete) {
16726            // XXX err, shouldn't we respect the delete flag?
16727            cleanUpResourcesLI();
16728            return true;
16729        }
16730    }
16731
16732    private boolean isAsecExternal(String cid) {
16733        final String asecPath = PackageHelper.getSdFilesystem(cid);
16734        return !asecPath.startsWith(mAsecInternalPath);
16735    }
16736
16737    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16738            PackageManagerException {
16739        if (copyRet < 0) {
16740            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16741                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16742                throw new PackageManagerException(copyRet, message);
16743            }
16744        }
16745    }
16746
16747    /**
16748     * Extract the StorageManagerService "container ID" from the full code path of an
16749     * .apk.
16750     */
16751    static String cidFromCodePath(String fullCodePath) {
16752        int eidx = fullCodePath.lastIndexOf("/");
16753        String subStr1 = fullCodePath.substring(0, eidx);
16754        int sidx = subStr1.lastIndexOf("/");
16755        return subStr1.substring(sidx+1, eidx);
16756    }
16757
16758    /**
16759     * Logic to handle installation of ASEC applications, including copying and
16760     * renaming logic.
16761     */
16762    class AsecInstallArgs extends InstallArgs {
16763        static final String RES_FILE_NAME = "pkg.apk";
16764        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16765
16766        String cid;
16767        String packagePath;
16768        String resourcePath;
16769
16770        /** New install */
16771        AsecInstallArgs(InstallParams params) {
16772            super(params.origin, params.move, params.observer, params.installFlags,
16773                    params.installerPackageName, params.volumeUuid,
16774                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16775                    params.grantedRuntimePermissions,
16776                    params.traceMethod, params.traceCookie, params.certificates,
16777                    params.installReason);
16778        }
16779
16780        /** Existing install */
16781        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16782                        boolean isExternal, boolean isForwardLocked) {
16783            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16784                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16785                    instructionSets, null, null, null, 0, null /*certificates*/,
16786                    PackageManager.INSTALL_REASON_UNKNOWN);
16787            // Hackily pretend we're still looking at a full code path
16788            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16789                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16790            }
16791
16792            // Extract cid from fullCodePath
16793            int eidx = fullCodePath.lastIndexOf("/");
16794            String subStr1 = fullCodePath.substring(0, eidx);
16795            int sidx = subStr1.lastIndexOf("/");
16796            cid = subStr1.substring(sidx+1, eidx);
16797            setMountPath(subStr1);
16798        }
16799
16800        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16801            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? 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            this.cid = cid;
16806            setMountPath(PackageHelper.getSdDir(cid));
16807        }
16808
16809        void createCopyFile() {
16810            cid = mInstallerService.allocateExternalStageCidLegacy();
16811        }
16812
16813        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16814            if (origin.staged && origin.cid != null) {
16815                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16816                cid = origin.cid;
16817                setMountPath(PackageHelper.getSdDir(cid));
16818                return PackageManager.INSTALL_SUCCEEDED;
16819            }
16820
16821            if (temp) {
16822                createCopyFile();
16823            } else {
16824                /*
16825                 * Pre-emptively destroy the container since it's destroyed if
16826                 * copying fails due to it existing anyway.
16827                 */
16828                PackageHelper.destroySdDir(cid);
16829            }
16830
16831            final String newMountPath = imcs.copyPackageToContainer(
16832                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16833                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16834
16835            if (newMountPath != null) {
16836                setMountPath(newMountPath);
16837                return PackageManager.INSTALL_SUCCEEDED;
16838            } else {
16839                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16840            }
16841        }
16842
16843        @Override
16844        String getCodePath() {
16845            return packagePath;
16846        }
16847
16848        @Override
16849        String getResourcePath() {
16850            return resourcePath;
16851        }
16852
16853        int doPreInstall(int status) {
16854            if (status != PackageManager.INSTALL_SUCCEEDED) {
16855                // Destroy container
16856                PackageHelper.destroySdDir(cid);
16857            } else {
16858                boolean mounted = PackageHelper.isContainerMounted(cid);
16859                if (!mounted) {
16860                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16861                            Process.SYSTEM_UID);
16862                    if (newMountPath != null) {
16863                        setMountPath(newMountPath);
16864                    } else {
16865                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16866                    }
16867                }
16868            }
16869            return status;
16870        }
16871
16872        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16873            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16874            String newMountPath = null;
16875            if (PackageHelper.isContainerMounted(cid)) {
16876                // Unmount the container
16877                if (!PackageHelper.unMountSdDir(cid)) {
16878                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16879                    return false;
16880                }
16881            }
16882            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16883                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16884                        " which might be stale. Will try to clean up.");
16885                // Clean up the stale container and proceed to recreate.
16886                if (!PackageHelper.destroySdDir(newCacheId)) {
16887                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16888                    return false;
16889                }
16890                // Successfully cleaned up stale container. Try to rename again.
16891                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16892                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16893                            + " inspite of cleaning it up.");
16894                    return false;
16895                }
16896            }
16897            if (!PackageHelper.isContainerMounted(newCacheId)) {
16898                Slog.w(TAG, "Mounting container " + newCacheId);
16899                newMountPath = PackageHelper.mountSdDir(newCacheId,
16900                        getEncryptKey(), Process.SYSTEM_UID);
16901            } else {
16902                newMountPath = PackageHelper.getSdDir(newCacheId);
16903            }
16904            if (newMountPath == null) {
16905                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16906                return false;
16907            }
16908            Log.i(TAG, "Succesfully renamed " + cid +
16909                    " to " + newCacheId +
16910                    " at new path: " + newMountPath);
16911            cid = newCacheId;
16912
16913            final File beforeCodeFile = new File(packagePath);
16914            setMountPath(newMountPath);
16915            final File afterCodeFile = new File(packagePath);
16916
16917            // Reflect the rename in scanned details
16918            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16919            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16920                    afterCodeFile, pkg.baseCodePath));
16921            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16922                    afterCodeFile, pkg.splitCodePaths));
16923
16924            // Reflect the rename in app info
16925            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16926            pkg.setApplicationInfoCodePath(pkg.codePath);
16927            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16928            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16929            pkg.setApplicationInfoResourcePath(pkg.codePath);
16930            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16931            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16932
16933            return true;
16934        }
16935
16936        private void setMountPath(String mountPath) {
16937            final File mountFile = new File(mountPath);
16938
16939            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16940            if (monolithicFile.exists()) {
16941                packagePath = monolithicFile.getAbsolutePath();
16942                if (isFwdLocked()) {
16943                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16944                } else {
16945                    resourcePath = packagePath;
16946                }
16947            } else {
16948                packagePath = mountFile.getAbsolutePath();
16949                resourcePath = packagePath;
16950            }
16951        }
16952
16953        int doPostInstall(int status, int uid) {
16954            if (status != PackageManager.INSTALL_SUCCEEDED) {
16955                cleanUp();
16956            } else {
16957                final int groupOwner;
16958                final String protectedFile;
16959                if (isFwdLocked()) {
16960                    groupOwner = UserHandle.getSharedAppGid(uid);
16961                    protectedFile = RES_FILE_NAME;
16962                } else {
16963                    groupOwner = -1;
16964                    protectedFile = null;
16965                }
16966
16967                if (uid < Process.FIRST_APPLICATION_UID
16968                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16969                    Slog.e(TAG, "Failed to finalize " + cid);
16970                    PackageHelper.destroySdDir(cid);
16971                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16972                }
16973
16974                boolean mounted = PackageHelper.isContainerMounted(cid);
16975                if (!mounted) {
16976                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16977                }
16978            }
16979            return status;
16980        }
16981
16982        private void cleanUp() {
16983            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16984
16985            // Destroy secure container
16986            PackageHelper.destroySdDir(cid);
16987        }
16988
16989        private List<String> getAllCodePaths() {
16990            final File codeFile = new File(getCodePath());
16991            if (codeFile != null && codeFile.exists()) {
16992                try {
16993                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16994                    return pkg.getAllCodePaths();
16995                } catch (PackageParserException e) {
16996                    // Ignored; we tried our best
16997                }
16998            }
16999            return Collections.EMPTY_LIST;
17000        }
17001
17002        void cleanUpResourcesLI() {
17003            // Enumerate all code paths before deleting
17004            cleanUpResourcesLI(getAllCodePaths());
17005        }
17006
17007        private void cleanUpResourcesLI(List<String> allCodePaths) {
17008            cleanUp();
17009            removeDexFiles(allCodePaths, instructionSets);
17010        }
17011
17012        String getPackageName() {
17013            return getAsecPackageName(cid);
17014        }
17015
17016        boolean doPostDeleteLI(boolean delete) {
17017            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17018            final List<String> allCodePaths = getAllCodePaths();
17019            boolean mounted = PackageHelper.isContainerMounted(cid);
17020            if (mounted) {
17021                // Unmount first
17022                if (PackageHelper.unMountSdDir(cid)) {
17023                    mounted = false;
17024                }
17025            }
17026            if (!mounted && delete) {
17027                cleanUpResourcesLI(allCodePaths);
17028            }
17029            return !mounted;
17030        }
17031
17032        @Override
17033        int doPreCopy() {
17034            if (isFwdLocked()) {
17035                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17036                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17037                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17038                }
17039            }
17040
17041            return PackageManager.INSTALL_SUCCEEDED;
17042        }
17043
17044        @Override
17045        int doPostCopy(int uid) {
17046            if (isFwdLocked()) {
17047                if (uid < Process.FIRST_APPLICATION_UID
17048                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17049                                RES_FILE_NAME)) {
17050                    Slog.e(TAG, "Failed to finalize " + cid);
17051                    PackageHelper.destroySdDir(cid);
17052                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17053                }
17054            }
17055
17056            return PackageManager.INSTALL_SUCCEEDED;
17057        }
17058    }
17059
17060    /**
17061     * Logic to handle movement of existing installed applications.
17062     */
17063    class MoveInstallArgs extends InstallArgs {
17064        private File codeFile;
17065        private File resourceFile;
17066
17067        /** New install */
17068        MoveInstallArgs(InstallParams params) {
17069            super(params.origin, params.move, params.observer, params.installFlags,
17070                    params.installerPackageName, params.volumeUuid,
17071                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17072                    params.grantedRuntimePermissions,
17073                    params.traceMethod, params.traceCookie, params.certificates,
17074                    params.installReason);
17075        }
17076
17077        int copyApk(IMediaContainerService imcs, boolean temp) {
17078            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17079                    + move.fromUuid + " to " + move.toUuid);
17080            synchronized (mInstaller) {
17081                try {
17082                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17083                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17084                } catch (InstallerException e) {
17085                    Slog.w(TAG, "Failed to move app", e);
17086                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17087                }
17088            }
17089
17090            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17091            resourceFile = codeFile;
17092            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17093
17094            return PackageManager.INSTALL_SUCCEEDED;
17095        }
17096
17097        int doPreInstall(int status) {
17098            if (status != PackageManager.INSTALL_SUCCEEDED) {
17099                cleanUp(move.toUuid);
17100            }
17101            return status;
17102        }
17103
17104        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17105            if (status != PackageManager.INSTALL_SUCCEEDED) {
17106                cleanUp(move.toUuid);
17107                return false;
17108            }
17109
17110            // Reflect the move in app info
17111            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17112            pkg.setApplicationInfoCodePath(pkg.codePath);
17113            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17114            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17115            pkg.setApplicationInfoResourcePath(pkg.codePath);
17116            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17117            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17118
17119            return true;
17120        }
17121
17122        int doPostInstall(int status, int uid) {
17123            if (status == PackageManager.INSTALL_SUCCEEDED) {
17124                cleanUp(move.fromUuid);
17125            } else {
17126                cleanUp(move.toUuid);
17127            }
17128            return status;
17129        }
17130
17131        @Override
17132        String getCodePath() {
17133            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17134        }
17135
17136        @Override
17137        String getResourcePath() {
17138            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17139        }
17140
17141        private boolean cleanUp(String volumeUuid) {
17142            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17143                    move.dataAppName);
17144            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17145            final int[] userIds = sUserManager.getUserIds();
17146            synchronized (mInstallLock) {
17147                // Clean up both app data and code
17148                // All package moves are frozen until finished
17149                for (int userId : userIds) {
17150                    try {
17151                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17152                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17153                    } catch (InstallerException e) {
17154                        Slog.w(TAG, String.valueOf(e));
17155                    }
17156                }
17157                removeCodePathLI(codeFile);
17158            }
17159            return true;
17160        }
17161
17162        void cleanUpResourcesLI() {
17163            throw new UnsupportedOperationException();
17164        }
17165
17166        boolean doPostDeleteLI(boolean delete) {
17167            throw new UnsupportedOperationException();
17168        }
17169    }
17170
17171    static String getAsecPackageName(String packageCid) {
17172        int idx = packageCid.lastIndexOf("-");
17173        if (idx == -1) {
17174            return packageCid;
17175        }
17176        return packageCid.substring(0, idx);
17177    }
17178
17179    // Utility method used to create code paths based on package name and available index.
17180    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17181        String idxStr = "";
17182        int idx = 1;
17183        // Fall back to default value of idx=1 if prefix is not
17184        // part of oldCodePath
17185        if (oldCodePath != null) {
17186            String subStr = oldCodePath;
17187            // Drop the suffix right away
17188            if (suffix != null && subStr.endsWith(suffix)) {
17189                subStr = subStr.substring(0, subStr.length() - suffix.length());
17190            }
17191            // If oldCodePath already contains prefix find out the
17192            // ending index to either increment or decrement.
17193            int sidx = subStr.lastIndexOf(prefix);
17194            if (sidx != -1) {
17195                subStr = subStr.substring(sidx + prefix.length());
17196                if (subStr != null) {
17197                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17198                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17199                    }
17200                    try {
17201                        idx = Integer.parseInt(subStr);
17202                        if (idx <= 1) {
17203                            idx++;
17204                        } else {
17205                            idx--;
17206                        }
17207                    } catch(NumberFormatException e) {
17208                    }
17209                }
17210            }
17211        }
17212        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17213        return prefix + idxStr;
17214    }
17215
17216    private File getNextCodePath(File targetDir, String packageName) {
17217        File result;
17218        SecureRandom random = new SecureRandom();
17219        byte[] bytes = new byte[16];
17220        do {
17221            random.nextBytes(bytes);
17222            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17223            result = new File(targetDir, packageName + "-" + suffix);
17224        } while (result.exists());
17225        return result;
17226    }
17227
17228    // Utility method that returns the relative package path with respect
17229    // to the installation directory. Like say for /data/data/com.test-1.apk
17230    // string com.test-1 is returned.
17231    static String deriveCodePathName(String codePath) {
17232        if (codePath == null) {
17233            return null;
17234        }
17235        final File codeFile = new File(codePath);
17236        final String name = codeFile.getName();
17237        if (codeFile.isDirectory()) {
17238            return name;
17239        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17240            final int lastDot = name.lastIndexOf('.');
17241            return name.substring(0, lastDot);
17242        } else {
17243            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17244            return null;
17245        }
17246    }
17247
17248    static class PackageInstalledInfo {
17249        String name;
17250        int uid;
17251        // The set of users that originally had this package installed.
17252        int[] origUsers;
17253        // The set of users that now have this package installed.
17254        int[] newUsers;
17255        PackageParser.Package pkg;
17256        int returnCode;
17257        String returnMsg;
17258        PackageRemovedInfo removedInfo;
17259        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17260
17261        public void setError(int code, String msg) {
17262            setReturnCode(code);
17263            setReturnMessage(msg);
17264            Slog.w(TAG, msg);
17265        }
17266
17267        public void setError(String msg, PackageParserException e) {
17268            setReturnCode(e.error);
17269            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17270            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17271            for (int i = 0; i < childCount; i++) {
17272                addedChildPackages.valueAt(i).setError(msg, e);
17273            }
17274            Slog.w(TAG, msg, e);
17275        }
17276
17277        public void setError(String msg, PackageManagerException e) {
17278            returnCode = e.error;
17279            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17280            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17281            for (int i = 0; i < childCount; i++) {
17282                addedChildPackages.valueAt(i).setError(msg, e);
17283            }
17284            Slog.w(TAG, msg, e);
17285        }
17286
17287        public void setReturnCode(int returnCode) {
17288            this.returnCode = returnCode;
17289            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17290            for (int i = 0; i < childCount; i++) {
17291                addedChildPackages.valueAt(i).returnCode = returnCode;
17292            }
17293        }
17294
17295        private void setReturnMessage(String returnMsg) {
17296            this.returnMsg = returnMsg;
17297            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17298            for (int i = 0; i < childCount; i++) {
17299                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17300            }
17301        }
17302
17303        // In some error cases we want to convey more info back to the observer
17304        String origPackage;
17305        String origPermission;
17306    }
17307
17308    /*
17309     * Install a non-existing package.
17310     */
17311    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17312            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17313            PackageInstalledInfo res, int installReason) {
17314        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17315
17316        // Remember this for later, in case we need to rollback this install
17317        String pkgName = pkg.packageName;
17318
17319        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17320
17321        synchronized(mPackages) {
17322            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17323            if (renamedPackage != null) {
17324                // A package with the same name is already installed, though
17325                // it has been renamed to an older name.  The package we
17326                // are trying to install should be installed as an update to
17327                // the existing one, but that has not been requested, so bail.
17328                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17329                        + " without first uninstalling package running as "
17330                        + renamedPackage);
17331                return;
17332            }
17333            if (mPackages.containsKey(pkgName)) {
17334                // Don't allow installation over an existing package with the same name.
17335                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17336                        + " without first uninstalling.");
17337                return;
17338            }
17339        }
17340
17341        try {
17342            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17343                    System.currentTimeMillis(), user);
17344
17345            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17346
17347            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17348                prepareAppDataAfterInstallLIF(newPackage);
17349
17350            } else {
17351                // Remove package from internal structures, but keep around any
17352                // data that might have already existed
17353                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17354                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17355            }
17356        } catch (PackageManagerException e) {
17357            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17358        }
17359
17360        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17361    }
17362
17363    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17364        // Can't rotate keys during boot or if sharedUser.
17365        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17366                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17367            return false;
17368        }
17369        // app is using upgradeKeySets; make sure all are valid
17370        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17371        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17372        for (int i = 0; i < upgradeKeySets.length; i++) {
17373            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17374                Slog.wtf(TAG, "Package "
17375                         + (oldPs.name != null ? oldPs.name : "<null>")
17376                         + " contains upgrade-key-set reference to unknown key-set: "
17377                         + upgradeKeySets[i]
17378                         + " reverting to signatures check.");
17379                return false;
17380            }
17381        }
17382        return true;
17383    }
17384
17385    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17386        // Upgrade keysets are being used.  Determine if new package has a superset of the
17387        // required keys.
17388        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17389        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17390        for (int i = 0; i < upgradeKeySets.length; i++) {
17391            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17392            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17393                return true;
17394            }
17395        }
17396        return false;
17397    }
17398
17399    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17400        try (DigestInputStream digestStream =
17401                new DigestInputStream(new FileInputStream(file), digest)) {
17402            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17403        }
17404    }
17405
17406    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17407            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17408            int installReason) {
17409        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17410
17411        final PackageParser.Package oldPackage;
17412        final PackageSetting ps;
17413        final String pkgName = pkg.packageName;
17414        final int[] allUsers;
17415        final int[] installedUsers;
17416
17417        synchronized(mPackages) {
17418            oldPackage = mPackages.get(pkgName);
17419            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17420
17421            // don't allow upgrade to target a release SDK from a pre-release SDK
17422            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17423                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17424            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17425                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17426            if (oldTargetsPreRelease
17427                    && !newTargetsPreRelease
17428                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17429                Slog.w(TAG, "Can't install package targeting released sdk");
17430                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17431                return;
17432            }
17433
17434            ps = mSettings.mPackages.get(pkgName);
17435
17436            // verify signatures are valid
17437            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17438                if (!checkUpgradeKeySetLP(ps, pkg)) {
17439                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17440                            "New package not signed by keys specified by upgrade-keysets: "
17441                                    + pkgName);
17442                    return;
17443                }
17444            } else {
17445                // default to original signature matching
17446                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17447                        != PackageManager.SIGNATURE_MATCH) {
17448                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17449                            "New package has a different signature: " + pkgName);
17450                    return;
17451                }
17452            }
17453
17454            // don't allow a system upgrade unless the upgrade hash matches
17455            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17456                byte[] digestBytes = null;
17457                try {
17458                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17459                    updateDigest(digest, new File(pkg.baseCodePath));
17460                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17461                        for (String path : pkg.splitCodePaths) {
17462                            updateDigest(digest, new File(path));
17463                        }
17464                    }
17465                    digestBytes = digest.digest();
17466                } catch (NoSuchAlgorithmException | IOException e) {
17467                    res.setError(INSTALL_FAILED_INVALID_APK,
17468                            "Could not compute hash: " + pkgName);
17469                    return;
17470                }
17471                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17472                    res.setError(INSTALL_FAILED_INVALID_APK,
17473                            "New package fails restrict-update check: " + pkgName);
17474                    return;
17475                }
17476                // retain upgrade restriction
17477                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17478            }
17479
17480            // Check for shared user id changes
17481            String invalidPackageName =
17482                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17483            if (invalidPackageName != null) {
17484                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17485                        "Package " + invalidPackageName + " tried to change user "
17486                                + oldPackage.mSharedUserId);
17487                return;
17488            }
17489
17490            // In case of rollback, remember per-user/profile install state
17491            allUsers = sUserManager.getUserIds();
17492            installedUsers = ps.queryInstalledUsers(allUsers, true);
17493
17494            // don't allow an upgrade from full to ephemeral
17495            if (isInstantApp) {
17496                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17497                    for (int currentUser : allUsers) {
17498                        if (!ps.getInstantApp(currentUser)) {
17499                            // can't downgrade from full to instant
17500                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17501                                    + " for user: " + currentUser);
17502                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17503                            return;
17504                        }
17505                    }
17506                } else if (!ps.getInstantApp(user.getIdentifier())) {
17507                    // can't downgrade from full to instant
17508                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17509                            + " for user: " + user.getIdentifier());
17510                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17511                    return;
17512                }
17513            }
17514        }
17515
17516        // Update what is removed
17517        res.removedInfo = new PackageRemovedInfo(this);
17518        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17519        res.removedInfo.removedPackage = oldPackage.packageName;
17520        res.removedInfo.installerPackageName = ps.installerPackageName;
17521        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17522        res.removedInfo.isUpdate = true;
17523        res.removedInfo.origUsers = installedUsers;
17524        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17525        for (int i = 0; i < installedUsers.length; i++) {
17526            final int userId = installedUsers[i];
17527            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17528        }
17529
17530        final int childCount = (oldPackage.childPackages != null)
17531                ? oldPackage.childPackages.size() : 0;
17532        for (int i = 0; i < childCount; i++) {
17533            boolean childPackageUpdated = false;
17534            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17535            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17536            if (res.addedChildPackages != null) {
17537                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17538                if (childRes != null) {
17539                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17540                    childRes.removedInfo.removedPackage = childPkg.packageName;
17541                    if (childPs != null) {
17542                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17543                    }
17544                    childRes.removedInfo.isUpdate = true;
17545                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17546                    childPackageUpdated = true;
17547                }
17548            }
17549            if (!childPackageUpdated) {
17550                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17551                childRemovedRes.removedPackage = childPkg.packageName;
17552                if (childPs != null) {
17553                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17554                }
17555                childRemovedRes.isUpdate = false;
17556                childRemovedRes.dataRemoved = true;
17557                synchronized (mPackages) {
17558                    if (childPs != null) {
17559                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17560                    }
17561                }
17562                if (res.removedInfo.removedChildPackages == null) {
17563                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17564                }
17565                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17566            }
17567        }
17568
17569        boolean sysPkg = (isSystemApp(oldPackage));
17570        if (sysPkg) {
17571            // Set the system/privileged flags as needed
17572            final boolean privileged =
17573                    (oldPackage.applicationInfo.privateFlags
17574                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17575            final int systemPolicyFlags = policyFlags
17576                    | PackageParser.PARSE_IS_SYSTEM
17577                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17578
17579            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17580                    user, allUsers, installerPackageName, res, installReason);
17581        } else {
17582            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17583                    user, allUsers, installerPackageName, res, installReason);
17584        }
17585    }
17586
17587    @Override
17588    public List<String> getPreviousCodePaths(String packageName) {
17589        final int callingUid = Binder.getCallingUid();
17590        final List<String> result = new ArrayList<>();
17591        if (getInstantAppPackageName(callingUid) != null) {
17592            return result;
17593        }
17594        final PackageSetting ps = mSettings.mPackages.get(packageName);
17595        if (ps != null
17596                && ps.oldCodePaths != null
17597                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17598            result.addAll(ps.oldCodePaths);
17599        }
17600        return result;
17601    }
17602
17603    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17604            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17605            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17606            int installReason) {
17607        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17608                + deletedPackage);
17609
17610        String pkgName = deletedPackage.packageName;
17611        boolean deletedPkg = true;
17612        boolean addedPkg = false;
17613        boolean updatedSettings = false;
17614        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17615        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17616                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17617
17618        final long origUpdateTime = (pkg.mExtras != null)
17619                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17620
17621        // First delete the existing package while retaining the data directory
17622        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17623                res.removedInfo, true, pkg)) {
17624            // If the existing package wasn't successfully deleted
17625            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17626            deletedPkg = false;
17627        } else {
17628            // Successfully deleted the old package; proceed with replace.
17629
17630            // If deleted package lived in a container, give users a chance to
17631            // relinquish resources before killing.
17632            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17633                if (DEBUG_INSTALL) {
17634                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17635                }
17636                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17637                final ArrayList<String> pkgList = new ArrayList<String>(1);
17638                pkgList.add(deletedPackage.applicationInfo.packageName);
17639                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17640            }
17641
17642            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17643                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17644            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17645
17646            try {
17647                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17648                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17649                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17650                        installReason);
17651
17652                // Update the in-memory copy of the previous code paths.
17653                PackageSetting ps = mSettings.mPackages.get(pkgName);
17654                if (!killApp) {
17655                    if (ps.oldCodePaths == null) {
17656                        ps.oldCodePaths = new ArraySet<>();
17657                    }
17658                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17659                    if (deletedPackage.splitCodePaths != null) {
17660                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17661                    }
17662                } else {
17663                    ps.oldCodePaths = null;
17664                }
17665                if (ps.childPackageNames != null) {
17666                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17667                        final String childPkgName = ps.childPackageNames.get(i);
17668                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17669                        childPs.oldCodePaths = ps.oldCodePaths;
17670                    }
17671                }
17672                // set instant app status, but, only if it's explicitly specified
17673                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17674                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17675                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17676                prepareAppDataAfterInstallLIF(newPackage);
17677                addedPkg = true;
17678                mDexManager.notifyPackageUpdated(newPackage.packageName,
17679                        newPackage.baseCodePath, newPackage.splitCodePaths);
17680            } catch (PackageManagerException e) {
17681                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17682            }
17683        }
17684
17685        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17686            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17687
17688            // Revert all internal state mutations and added folders for the failed install
17689            if (addedPkg) {
17690                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17691                        res.removedInfo, true, null);
17692            }
17693
17694            // Restore the old package
17695            if (deletedPkg) {
17696                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17697                File restoreFile = new File(deletedPackage.codePath);
17698                // Parse old package
17699                boolean oldExternal = isExternal(deletedPackage);
17700                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17701                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17702                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17703                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17704                try {
17705                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17706                            null);
17707                } catch (PackageManagerException e) {
17708                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17709                            + e.getMessage());
17710                    return;
17711                }
17712
17713                synchronized (mPackages) {
17714                    // Ensure the installer package name up to date
17715                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17716
17717                    // Update permissions for restored package
17718                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17719
17720                    mSettings.writeLPr();
17721                }
17722
17723                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17724            }
17725        } else {
17726            synchronized (mPackages) {
17727                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17728                if (ps != null) {
17729                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17730                    if (res.removedInfo.removedChildPackages != null) {
17731                        final int childCount = res.removedInfo.removedChildPackages.size();
17732                        // Iterate in reverse as we may modify the collection
17733                        for (int i = childCount - 1; i >= 0; i--) {
17734                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17735                            if (res.addedChildPackages.containsKey(childPackageName)) {
17736                                res.removedInfo.removedChildPackages.removeAt(i);
17737                            } else {
17738                                PackageRemovedInfo childInfo = res.removedInfo
17739                                        .removedChildPackages.valueAt(i);
17740                                childInfo.removedForAllUsers = mPackages.get(
17741                                        childInfo.removedPackage) == null;
17742                            }
17743                        }
17744                    }
17745                }
17746            }
17747        }
17748    }
17749
17750    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17751            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17752            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17753            int installReason) {
17754        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17755                + ", old=" + deletedPackage);
17756
17757        final boolean disabledSystem;
17758
17759        // Remove existing system package
17760        removePackageLI(deletedPackage, true);
17761
17762        synchronized (mPackages) {
17763            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17764        }
17765        if (!disabledSystem) {
17766            // We didn't need to disable the .apk as a current system package,
17767            // which means we are replacing another update that is already
17768            // installed.  We need to make sure to delete the older one's .apk.
17769            res.removedInfo.args = createInstallArgsForExisting(0,
17770                    deletedPackage.applicationInfo.getCodePath(),
17771                    deletedPackage.applicationInfo.getResourcePath(),
17772                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17773        } else {
17774            res.removedInfo.args = null;
17775        }
17776
17777        // Successfully disabled the old package. Now proceed with re-installation
17778        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17779                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17780        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17781
17782        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17783        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17784                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17785
17786        PackageParser.Package newPackage = null;
17787        try {
17788            // Add the package to the internal data structures
17789            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17790
17791            // Set the update and install times
17792            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17793            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17794                    System.currentTimeMillis());
17795
17796            // Update the package dynamic state if succeeded
17797            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17798                // Now that the install succeeded make sure we remove data
17799                // directories for any child package the update removed.
17800                final int deletedChildCount = (deletedPackage.childPackages != null)
17801                        ? deletedPackage.childPackages.size() : 0;
17802                final int newChildCount = (newPackage.childPackages != null)
17803                        ? newPackage.childPackages.size() : 0;
17804                for (int i = 0; i < deletedChildCount; i++) {
17805                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17806                    boolean childPackageDeleted = true;
17807                    for (int j = 0; j < newChildCount; j++) {
17808                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17809                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17810                            childPackageDeleted = false;
17811                            break;
17812                        }
17813                    }
17814                    if (childPackageDeleted) {
17815                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17816                                deletedChildPkg.packageName);
17817                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17818                            PackageRemovedInfo removedChildRes = res.removedInfo
17819                                    .removedChildPackages.get(deletedChildPkg.packageName);
17820                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17821                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17822                        }
17823                    }
17824                }
17825
17826                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17827                        installReason);
17828                prepareAppDataAfterInstallLIF(newPackage);
17829
17830                mDexManager.notifyPackageUpdated(newPackage.packageName,
17831                            newPackage.baseCodePath, newPackage.splitCodePaths);
17832            }
17833        } catch (PackageManagerException e) {
17834            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17835            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17836        }
17837
17838        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17839            // Re installation failed. Restore old information
17840            // Remove new pkg information
17841            if (newPackage != null) {
17842                removeInstalledPackageLI(newPackage, true);
17843            }
17844            // Add back the old system package
17845            try {
17846                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17847            } catch (PackageManagerException e) {
17848                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17849            }
17850
17851            synchronized (mPackages) {
17852                if (disabledSystem) {
17853                    enableSystemPackageLPw(deletedPackage);
17854                }
17855
17856                // Ensure the installer package name up to date
17857                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17858
17859                // Update permissions for restored package
17860                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17861
17862                mSettings.writeLPr();
17863            }
17864
17865            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17866                    + " after failed upgrade");
17867        }
17868    }
17869
17870    /**
17871     * Checks whether the parent or any of the child packages have a change shared
17872     * user. For a package to be a valid update the shred users of the parent and
17873     * the children should match. We may later support changing child shared users.
17874     * @param oldPkg The updated package.
17875     * @param newPkg The update package.
17876     * @return The shared user that change between the versions.
17877     */
17878    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17879            PackageParser.Package newPkg) {
17880        // Check parent shared user
17881        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17882            return newPkg.packageName;
17883        }
17884        // Check child shared users
17885        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17886        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17887        for (int i = 0; i < newChildCount; i++) {
17888            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17889            // If this child was present, did it have the same shared user?
17890            for (int j = 0; j < oldChildCount; j++) {
17891                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17892                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17893                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17894                    return newChildPkg.packageName;
17895                }
17896            }
17897        }
17898        return null;
17899    }
17900
17901    private void removeNativeBinariesLI(PackageSetting ps) {
17902        // Remove the lib path for the parent package
17903        if (ps != null) {
17904            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17905            // Remove the lib path for the child packages
17906            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17907            for (int i = 0; i < childCount; i++) {
17908                PackageSetting childPs = null;
17909                synchronized (mPackages) {
17910                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17911                }
17912                if (childPs != null) {
17913                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17914                            .legacyNativeLibraryPathString);
17915                }
17916            }
17917        }
17918    }
17919
17920    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17921        // Enable the parent package
17922        mSettings.enableSystemPackageLPw(pkg.packageName);
17923        // Enable the child packages
17924        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17925        for (int i = 0; i < childCount; i++) {
17926            PackageParser.Package childPkg = pkg.childPackages.get(i);
17927            mSettings.enableSystemPackageLPw(childPkg.packageName);
17928        }
17929    }
17930
17931    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17932            PackageParser.Package newPkg) {
17933        // Disable the parent package (parent always replaced)
17934        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17935        // Disable the child packages
17936        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17937        for (int i = 0; i < childCount; i++) {
17938            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17939            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17940            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17941        }
17942        return disabled;
17943    }
17944
17945    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17946            String installerPackageName) {
17947        // Enable the parent package
17948        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17949        // Enable the child packages
17950        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17951        for (int i = 0; i < childCount; i++) {
17952            PackageParser.Package childPkg = pkg.childPackages.get(i);
17953            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17954        }
17955    }
17956
17957    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17958        // Collect all used permissions in the UID
17959        ArraySet<String> usedPermissions = new ArraySet<>();
17960        final int packageCount = su.packages.size();
17961        for (int i = 0; i < packageCount; i++) {
17962            PackageSetting ps = su.packages.valueAt(i);
17963            if (ps.pkg == null) {
17964                continue;
17965            }
17966            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17967            for (int j = 0; j < requestedPermCount; j++) {
17968                String permission = ps.pkg.requestedPermissions.get(j);
17969                BasePermission bp = mSettings.mPermissions.get(permission);
17970                if (bp != null) {
17971                    usedPermissions.add(permission);
17972                }
17973            }
17974        }
17975
17976        PermissionsState permissionsState = su.getPermissionsState();
17977        // Prune install permissions
17978        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17979        final int installPermCount = installPermStates.size();
17980        for (int i = installPermCount - 1; i >= 0;  i--) {
17981            PermissionState permissionState = installPermStates.get(i);
17982            if (!usedPermissions.contains(permissionState.getName())) {
17983                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17984                if (bp != null) {
17985                    permissionsState.revokeInstallPermission(bp);
17986                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17987                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17988                }
17989            }
17990        }
17991
17992        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17993
17994        // Prune runtime permissions
17995        for (int userId : allUserIds) {
17996            List<PermissionState> runtimePermStates = permissionsState
17997                    .getRuntimePermissionStates(userId);
17998            final int runtimePermCount = runtimePermStates.size();
17999            for (int i = runtimePermCount - 1; i >= 0; i--) {
18000                PermissionState permissionState = runtimePermStates.get(i);
18001                if (!usedPermissions.contains(permissionState.getName())) {
18002                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18003                    if (bp != null) {
18004                        permissionsState.revokeRuntimePermission(bp, userId);
18005                        permissionsState.updatePermissionFlags(bp, userId,
18006                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18007                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18008                                runtimePermissionChangedUserIds, userId);
18009                    }
18010                }
18011            }
18012        }
18013
18014        return runtimePermissionChangedUserIds;
18015    }
18016
18017    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18018            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18019        // Update the parent package setting
18020        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18021                res, user, installReason);
18022        // Update the child packages setting
18023        final int childCount = (newPackage.childPackages != null)
18024                ? newPackage.childPackages.size() : 0;
18025        for (int i = 0; i < childCount; i++) {
18026            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18027            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18028            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18029                    childRes.origUsers, childRes, user, installReason);
18030        }
18031    }
18032
18033    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18034            String installerPackageName, int[] allUsers, int[] installedForUsers,
18035            PackageInstalledInfo res, UserHandle user, int installReason) {
18036        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18037
18038        String pkgName = newPackage.packageName;
18039        synchronized (mPackages) {
18040            //write settings. the installStatus will be incomplete at this stage.
18041            //note that the new package setting would have already been
18042            //added to mPackages. It hasn't been persisted yet.
18043            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18044            // TODO: Remove this write? It's also written at the end of this method
18045            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18046            mSettings.writeLPr();
18047            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18048        }
18049
18050        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18051        synchronized (mPackages) {
18052            updatePermissionsLPw(newPackage.packageName, newPackage,
18053                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18054                            ? UPDATE_PERMISSIONS_ALL : 0));
18055            // For system-bundled packages, we assume that installing an upgraded version
18056            // of the package implies that the user actually wants to run that new code,
18057            // so we enable the package.
18058            PackageSetting ps = mSettings.mPackages.get(pkgName);
18059            final int userId = user.getIdentifier();
18060            if (ps != null) {
18061                if (isSystemApp(newPackage)) {
18062                    if (DEBUG_INSTALL) {
18063                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18064                    }
18065                    // Enable system package for requested users
18066                    if (res.origUsers != null) {
18067                        for (int origUserId : res.origUsers) {
18068                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18069                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18070                                        origUserId, installerPackageName);
18071                            }
18072                        }
18073                    }
18074                    // Also convey the prior install/uninstall state
18075                    if (allUsers != null && installedForUsers != null) {
18076                        for (int currentUserId : allUsers) {
18077                            final boolean installed = ArrayUtils.contains(
18078                                    installedForUsers, currentUserId);
18079                            if (DEBUG_INSTALL) {
18080                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18081                            }
18082                            ps.setInstalled(installed, currentUserId);
18083                        }
18084                        // these install state changes will be persisted in the
18085                        // upcoming call to mSettings.writeLPr().
18086                    }
18087                }
18088                // It's implied that when a user requests installation, they want the app to be
18089                // installed and enabled.
18090                if (userId != UserHandle.USER_ALL) {
18091                    ps.setInstalled(true, userId);
18092                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18093                }
18094
18095                // When replacing an existing package, preserve the original install reason for all
18096                // users that had the package installed before.
18097                final Set<Integer> previousUserIds = new ArraySet<>();
18098                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18099                    final int installReasonCount = res.removedInfo.installReasons.size();
18100                    for (int i = 0; i < installReasonCount; i++) {
18101                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18102                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18103                        ps.setInstallReason(previousInstallReason, previousUserId);
18104                        previousUserIds.add(previousUserId);
18105                    }
18106                }
18107
18108                // Set install reason for users that are having the package newly installed.
18109                if (userId == UserHandle.USER_ALL) {
18110                    for (int currentUserId : sUserManager.getUserIds()) {
18111                        if (!previousUserIds.contains(currentUserId)) {
18112                            ps.setInstallReason(installReason, currentUserId);
18113                        }
18114                    }
18115                } else if (!previousUserIds.contains(userId)) {
18116                    ps.setInstallReason(installReason, userId);
18117                }
18118                mSettings.writeKernelMappingLPr(ps);
18119            }
18120            res.name = pkgName;
18121            res.uid = newPackage.applicationInfo.uid;
18122            res.pkg = newPackage;
18123            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18124            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18125            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18126            //to update install status
18127            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18128            mSettings.writeLPr();
18129            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18130        }
18131
18132        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18133    }
18134
18135    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18136        try {
18137            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18138            installPackageLI(args, res);
18139        } finally {
18140            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18141        }
18142    }
18143
18144    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18145        final int installFlags = args.installFlags;
18146        final String installerPackageName = args.installerPackageName;
18147        final String volumeUuid = args.volumeUuid;
18148        final File tmpPackageFile = new File(args.getCodePath());
18149        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18150        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18151                || (args.volumeUuid != null));
18152        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18153        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18154        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18155        boolean replace = false;
18156        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18157        if (args.move != null) {
18158            // moving a complete application; perform an initial scan on the new install location
18159            scanFlags |= SCAN_INITIAL;
18160        }
18161        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18162            scanFlags |= SCAN_DONT_KILL_APP;
18163        }
18164        if (instantApp) {
18165            scanFlags |= SCAN_AS_INSTANT_APP;
18166        }
18167        if (fullApp) {
18168            scanFlags |= SCAN_AS_FULL_APP;
18169        }
18170
18171        // Result object to be returned
18172        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18173
18174        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18175
18176        // Sanity check
18177        if (instantApp && (forwardLocked || onExternal)) {
18178            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18179                    + " external=" + onExternal);
18180            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18181            return;
18182        }
18183
18184        // Retrieve PackageSettings and parse package
18185        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18186                | PackageParser.PARSE_ENFORCE_CODE
18187                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18188                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18189                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18190                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18191        PackageParser pp = new PackageParser();
18192        pp.setSeparateProcesses(mSeparateProcesses);
18193        pp.setDisplayMetrics(mMetrics);
18194        pp.setCallback(mPackageParserCallback);
18195
18196        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18197        final PackageParser.Package pkg;
18198        try {
18199            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18200        } catch (PackageParserException e) {
18201            res.setError("Failed parse during installPackageLI", e);
18202            return;
18203        } finally {
18204            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18205        }
18206
18207        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18208        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18209            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18210            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18211                    "Instant app package must target O");
18212            return;
18213        }
18214        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18215            Slog.w(TAG, "Instant app package " + pkg.packageName
18216                    + " does not target targetSandboxVersion 2");
18217            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18218                    "Instant app package must use targetSanboxVersion 2");
18219            return;
18220        }
18221
18222        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18223            // Static shared libraries have synthetic package names
18224            renameStaticSharedLibraryPackage(pkg);
18225
18226            // No static shared libs on external storage
18227            if (onExternal) {
18228                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18229                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18230                        "Packages declaring static-shared libs cannot be updated");
18231                return;
18232            }
18233        }
18234
18235        // If we are installing a clustered package add results for the children
18236        if (pkg.childPackages != null) {
18237            synchronized (mPackages) {
18238                final int childCount = pkg.childPackages.size();
18239                for (int i = 0; i < childCount; i++) {
18240                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18241                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18242                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18243                    childRes.pkg = childPkg;
18244                    childRes.name = childPkg.packageName;
18245                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18246                    if (childPs != null) {
18247                        childRes.origUsers = childPs.queryInstalledUsers(
18248                                sUserManager.getUserIds(), true);
18249                    }
18250                    if ((mPackages.containsKey(childPkg.packageName))) {
18251                        childRes.removedInfo = new PackageRemovedInfo(this);
18252                        childRes.removedInfo.removedPackage = childPkg.packageName;
18253                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18254                    }
18255                    if (res.addedChildPackages == null) {
18256                        res.addedChildPackages = new ArrayMap<>();
18257                    }
18258                    res.addedChildPackages.put(childPkg.packageName, childRes);
18259                }
18260            }
18261        }
18262
18263        // If package doesn't declare API override, mark that we have an install
18264        // time CPU ABI override.
18265        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18266            pkg.cpuAbiOverride = args.abiOverride;
18267        }
18268
18269        String pkgName = res.name = pkg.packageName;
18270        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18271            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18272                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18273                return;
18274            }
18275        }
18276
18277        try {
18278            // either use what we've been given or parse directly from the APK
18279            if (args.certificates != null) {
18280                try {
18281                    PackageParser.populateCertificates(pkg, args.certificates);
18282                } catch (PackageParserException e) {
18283                    // there was something wrong with the certificates we were given;
18284                    // try to pull them from the APK
18285                    PackageParser.collectCertificates(pkg, parseFlags);
18286                }
18287            } else {
18288                PackageParser.collectCertificates(pkg, parseFlags);
18289            }
18290        } catch (PackageParserException e) {
18291            res.setError("Failed collect during installPackageLI", e);
18292            return;
18293        }
18294
18295        // Get rid of all references to package scan path via parser.
18296        pp = null;
18297        String oldCodePath = null;
18298        boolean systemApp = false;
18299        synchronized (mPackages) {
18300            // Check if installing already existing package
18301            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18302                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18303                if (pkg.mOriginalPackages != null
18304                        && pkg.mOriginalPackages.contains(oldName)
18305                        && mPackages.containsKey(oldName)) {
18306                    // This package is derived from an original package,
18307                    // and this device has been updating from that original
18308                    // name.  We must continue using the original name, so
18309                    // rename the new package here.
18310                    pkg.setPackageName(oldName);
18311                    pkgName = pkg.packageName;
18312                    replace = true;
18313                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18314                            + oldName + " pkgName=" + pkgName);
18315                } else if (mPackages.containsKey(pkgName)) {
18316                    // This package, under its official name, already exists
18317                    // on the device; we should replace it.
18318                    replace = true;
18319                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18320                }
18321
18322                // Child packages are installed through the parent package
18323                if (pkg.parentPackage != null) {
18324                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18325                            "Package " + pkg.packageName + " is child of package "
18326                                    + pkg.parentPackage.parentPackage + ". Child packages "
18327                                    + "can be updated only through the parent package.");
18328                    return;
18329                }
18330
18331                if (replace) {
18332                    // Prevent apps opting out from runtime permissions
18333                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18334                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18335                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18336                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18337                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18338                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18339                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18340                                        + " doesn't support runtime permissions but the old"
18341                                        + " target SDK " + oldTargetSdk + " does.");
18342                        return;
18343                    }
18344                    // Prevent apps from downgrading their targetSandbox.
18345                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18346                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18347                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18348                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18349                                "Package " + pkg.packageName + " new target sandbox "
18350                                + newTargetSandbox + " is incompatible with the previous value of"
18351                                + oldTargetSandbox + ".");
18352                        return;
18353                    }
18354
18355                    // Prevent installing of child packages
18356                    if (oldPackage.parentPackage != null) {
18357                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18358                                "Package " + pkg.packageName + " is child of package "
18359                                        + oldPackage.parentPackage + ". Child packages "
18360                                        + "can be updated only through the parent package.");
18361                        return;
18362                    }
18363                }
18364            }
18365
18366            PackageSetting ps = mSettings.mPackages.get(pkgName);
18367            if (ps != null) {
18368                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18369
18370                // Static shared libs have same package with different versions where
18371                // we internally use a synthetic package name to allow multiple versions
18372                // of the same package, therefore we need to compare signatures against
18373                // the package setting for the latest library version.
18374                PackageSetting signatureCheckPs = ps;
18375                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18376                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18377                    if (libraryEntry != null) {
18378                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18379                    }
18380                }
18381
18382                // Quick sanity check that we're signed correctly if updating;
18383                // we'll check this again later when scanning, but we want to
18384                // bail early here before tripping over redefined permissions.
18385                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18386                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18387                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18388                                + pkg.packageName + " upgrade keys do not match the "
18389                                + "previously installed version");
18390                        return;
18391                    }
18392                } else {
18393                    try {
18394                        verifySignaturesLP(signatureCheckPs, pkg);
18395                    } catch (PackageManagerException e) {
18396                        res.setError(e.error, e.getMessage());
18397                        return;
18398                    }
18399                }
18400
18401                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18402                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18403                    systemApp = (ps.pkg.applicationInfo.flags &
18404                            ApplicationInfo.FLAG_SYSTEM) != 0;
18405                }
18406                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18407            }
18408
18409            int N = pkg.permissions.size();
18410            for (int i = N-1; i >= 0; i--) {
18411                PackageParser.Permission perm = pkg.permissions.get(i);
18412                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18413
18414                // Don't allow anyone but the system to define ephemeral permissions.
18415                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18416                        && !systemApp) {
18417                    Slog.w(TAG, "Non-System package " + pkg.packageName
18418                            + " attempting to delcare ephemeral permission "
18419                            + perm.info.name + "; Removing ephemeral.");
18420                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18421                }
18422                // Check whether the newly-scanned package wants to define an already-defined perm
18423                if (bp != null) {
18424                    // If the defining package is signed with our cert, it's okay.  This
18425                    // also includes the "updating the same package" case, of course.
18426                    // "updating same package" could also involve key-rotation.
18427                    final boolean sigsOk;
18428                    if (bp.sourcePackage.equals(pkg.packageName)
18429                            && (bp.packageSetting instanceof PackageSetting)
18430                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18431                                    scanFlags))) {
18432                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18433                    } else {
18434                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18435                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18436                    }
18437                    if (!sigsOk) {
18438                        // If the owning package is the system itself, we log but allow
18439                        // install to proceed; we fail the install on all other permission
18440                        // redefinitions.
18441                        if (!bp.sourcePackage.equals("android")) {
18442                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18443                                    + pkg.packageName + " attempting to redeclare permission "
18444                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18445                            res.origPermission = perm.info.name;
18446                            res.origPackage = bp.sourcePackage;
18447                            return;
18448                        } else {
18449                            Slog.w(TAG, "Package " + pkg.packageName
18450                                    + " attempting to redeclare system permission "
18451                                    + perm.info.name + "; ignoring new declaration");
18452                            pkg.permissions.remove(i);
18453                        }
18454                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18455                        // Prevent apps to change protection level to dangerous from any other
18456                        // type as this would allow a privilege escalation where an app adds a
18457                        // normal/signature permission in other app's group and later redefines
18458                        // it as dangerous leading to the group auto-grant.
18459                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18460                                == PermissionInfo.PROTECTION_DANGEROUS) {
18461                            if (bp != null && !bp.isRuntime()) {
18462                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18463                                        + "non-runtime permission " + perm.info.name
18464                                        + " to runtime; keeping old protection level");
18465                                perm.info.protectionLevel = bp.protectionLevel;
18466                            }
18467                        }
18468                    }
18469                }
18470            }
18471        }
18472
18473        if (systemApp) {
18474            if (onExternal) {
18475                // Abort update; system app can't be replaced with app on sdcard
18476                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18477                        "Cannot install updates to system apps on sdcard");
18478                return;
18479            } else if (instantApp) {
18480                // Abort update; system app can't be replaced with an instant app
18481                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18482                        "Cannot update a system app with an instant app");
18483                return;
18484            }
18485        }
18486
18487        if (args.move != null) {
18488            // We did an in-place move, so dex is ready to roll
18489            scanFlags |= SCAN_NO_DEX;
18490            scanFlags |= SCAN_MOVE;
18491
18492            synchronized (mPackages) {
18493                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18494                if (ps == null) {
18495                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18496                            "Missing settings for moved package " + pkgName);
18497                }
18498
18499                // We moved the entire application as-is, so bring over the
18500                // previously derived ABI information.
18501                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18502                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18503            }
18504
18505        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18506            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18507            scanFlags |= SCAN_NO_DEX;
18508
18509            try {
18510                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18511                    args.abiOverride : pkg.cpuAbiOverride);
18512                final boolean extractNativeLibs = !pkg.isLibrary();
18513                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18514                        extractNativeLibs, mAppLib32InstallDir);
18515            } catch (PackageManagerException pme) {
18516                Slog.e(TAG, "Error deriving application ABI", pme);
18517                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18518                return;
18519            }
18520
18521            // Shared libraries for the package need to be updated.
18522            synchronized (mPackages) {
18523                try {
18524                    updateSharedLibrariesLPr(pkg, null);
18525                } catch (PackageManagerException e) {
18526                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18527                }
18528            }
18529
18530            // dexopt can take some time to complete, so, for instant apps, we skip this
18531            // step during installation. Instead, we'll take extra time the first time the
18532            // instant app starts. It's preferred to do it this way to provide continuous
18533            // progress to the user instead of mysteriously blocking somewhere in the
18534            // middle of running an instant app. The default behaviour can be overridden
18535            // via gservices.
18536            if (!instantApp || Global.getInt(
18537                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18538                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18539                // Do not run PackageDexOptimizer through the local performDexOpt
18540                // method because `pkg` may not be in `mPackages` yet.
18541                //
18542                // Also, don't fail application installs if the dexopt step fails.
18543                DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18544                        REASON_INSTALL,
18545                        DexoptOptions.DEXOPT_BOOT_COMPLETE);
18546                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18547                        null /* instructionSets */,
18548                        getOrCreateCompilerPackageStats(pkg),
18549                        mDexManager.isUsedByOtherApps(pkg.packageName),
18550                        dexoptOptions);
18551                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18552            }
18553
18554            // Notify BackgroundDexOptService that the package has been changed.
18555            // If this is an update of a package which used to fail to compile,
18556            // BDOS will remove it from its blacklist.
18557            // TODO: Layering violation
18558            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18559        }
18560
18561        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18562            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18563            return;
18564        }
18565
18566        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18567
18568        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18569                "installPackageLI")) {
18570            if (replace) {
18571                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18572                    // Static libs have a synthetic package name containing the version
18573                    // and cannot be updated as an update would get a new package name,
18574                    // unless this is the exact same version code which is useful for
18575                    // development.
18576                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18577                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18578                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18579                                + "static-shared libs cannot be updated");
18580                        return;
18581                    }
18582                }
18583                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18584                        installerPackageName, res, args.installReason);
18585            } else {
18586                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18587                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18588            }
18589        }
18590
18591        synchronized (mPackages) {
18592            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18593            if (ps != null) {
18594                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18595                ps.setUpdateAvailable(false /*updateAvailable*/);
18596            }
18597
18598            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18599            for (int i = 0; i < childCount; i++) {
18600                PackageParser.Package childPkg = pkg.childPackages.get(i);
18601                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18602                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18603                if (childPs != null) {
18604                    childRes.newUsers = childPs.queryInstalledUsers(
18605                            sUserManager.getUserIds(), true);
18606                }
18607            }
18608
18609            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18610                updateSequenceNumberLP(ps, res.newUsers);
18611                updateInstantAppInstallerLocked(pkgName);
18612            }
18613        }
18614    }
18615
18616    private void startIntentFilterVerifications(int userId, boolean replacing,
18617            PackageParser.Package pkg) {
18618        if (mIntentFilterVerifierComponent == null) {
18619            Slog.w(TAG, "No IntentFilter verification will not be done as "
18620                    + "there is no IntentFilterVerifier available!");
18621            return;
18622        }
18623
18624        final int verifierUid = getPackageUid(
18625                mIntentFilterVerifierComponent.getPackageName(),
18626                MATCH_DEBUG_TRIAGED_MISSING,
18627                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18628
18629        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18630        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18631        mHandler.sendMessage(msg);
18632
18633        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18634        for (int i = 0; i < childCount; i++) {
18635            PackageParser.Package childPkg = pkg.childPackages.get(i);
18636            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18637            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18638            mHandler.sendMessage(msg);
18639        }
18640    }
18641
18642    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18643            PackageParser.Package pkg) {
18644        int size = pkg.activities.size();
18645        if (size == 0) {
18646            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18647                    "No activity, so no need to verify any IntentFilter!");
18648            return;
18649        }
18650
18651        final boolean hasDomainURLs = hasDomainURLs(pkg);
18652        if (!hasDomainURLs) {
18653            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18654                    "No domain URLs, so no need to verify any IntentFilter!");
18655            return;
18656        }
18657
18658        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18659                + " if any IntentFilter from the " + size
18660                + " Activities needs verification ...");
18661
18662        int count = 0;
18663        final String packageName = pkg.packageName;
18664
18665        synchronized (mPackages) {
18666            // If this is a new install and we see that we've already run verification for this
18667            // package, we have nothing to do: it means the state was restored from backup.
18668            if (!replacing) {
18669                IntentFilterVerificationInfo ivi =
18670                        mSettings.getIntentFilterVerificationLPr(packageName);
18671                if (ivi != null) {
18672                    if (DEBUG_DOMAIN_VERIFICATION) {
18673                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18674                                + ivi.getStatusString());
18675                    }
18676                    return;
18677                }
18678            }
18679
18680            // If any filters need to be verified, then all need to be.
18681            boolean needToVerify = false;
18682            for (PackageParser.Activity a : pkg.activities) {
18683                for (ActivityIntentInfo filter : a.intents) {
18684                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18685                        if (DEBUG_DOMAIN_VERIFICATION) {
18686                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18687                        }
18688                        needToVerify = true;
18689                        break;
18690                    }
18691                }
18692            }
18693
18694            if (needToVerify) {
18695                final int verificationId = mIntentFilterVerificationToken++;
18696                for (PackageParser.Activity a : pkg.activities) {
18697                    for (ActivityIntentInfo filter : a.intents) {
18698                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18699                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18700                                    "Verification needed for IntentFilter:" + filter.toString());
18701                            mIntentFilterVerifier.addOneIntentFilterVerification(
18702                                    verifierUid, userId, verificationId, filter, packageName);
18703                            count++;
18704                        }
18705                    }
18706                }
18707            }
18708        }
18709
18710        if (count > 0) {
18711            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18712                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18713                    +  " for userId:" + userId);
18714            mIntentFilterVerifier.startVerifications(userId);
18715        } else {
18716            if (DEBUG_DOMAIN_VERIFICATION) {
18717                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18718            }
18719        }
18720    }
18721
18722    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18723        final ComponentName cn  = filter.activity.getComponentName();
18724        final String packageName = cn.getPackageName();
18725
18726        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18727                packageName);
18728        if (ivi == null) {
18729            return true;
18730        }
18731        int status = ivi.getStatus();
18732        switch (status) {
18733            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18734            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18735                return true;
18736
18737            default:
18738                // Nothing to do
18739                return false;
18740        }
18741    }
18742
18743    private static boolean isMultiArch(ApplicationInfo info) {
18744        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18745    }
18746
18747    private static boolean isExternal(PackageParser.Package pkg) {
18748        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18749    }
18750
18751    private static boolean isExternal(PackageSetting ps) {
18752        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18753    }
18754
18755    private static boolean isSystemApp(PackageParser.Package pkg) {
18756        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18757    }
18758
18759    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18760        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18761    }
18762
18763    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18764        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18765    }
18766
18767    private static boolean isSystemApp(PackageSetting ps) {
18768        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18769    }
18770
18771    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18772        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18773    }
18774
18775    private int packageFlagsToInstallFlags(PackageSetting ps) {
18776        int installFlags = 0;
18777        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18778            // This existing package was an external ASEC install when we have
18779            // the external flag without a UUID
18780            installFlags |= PackageManager.INSTALL_EXTERNAL;
18781        }
18782        if (ps.isForwardLocked()) {
18783            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18784        }
18785        return installFlags;
18786    }
18787
18788    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18789        if (isExternal(pkg)) {
18790            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18791                return StorageManager.UUID_PRIMARY_PHYSICAL;
18792            } else {
18793                return pkg.volumeUuid;
18794            }
18795        } else {
18796            return StorageManager.UUID_PRIVATE_INTERNAL;
18797        }
18798    }
18799
18800    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18801        if (isExternal(pkg)) {
18802            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18803                return mSettings.getExternalVersion();
18804            } else {
18805                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18806            }
18807        } else {
18808            return mSettings.getInternalVersion();
18809        }
18810    }
18811
18812    private void deleteTempPackageFiles() {
18813        final FilenameFilter filter = new FilenameFilter() {
18814            public boolean accept(File dir, String name) {
18815                return name.startsWith("vmdl") && name.endsWith(".tmp");
18816            }
18817        };
18818        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18819            file.delete();
18820        }
18821    }
18822
18823    @Override
18824    public void deletePackageAsUser(String packageName, int versionCode,
18825            IPackageDeleteObserver observer, int userId, int flags) {
18826        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18827                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18828    }
18829
18830    @Override
18831    public void deletePackageVersioned(VersionedPackage versionedPackage,
18832            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18833        final int callingUid = Binder.getCallingUid();
18834        mContext.enforceCallingOrSelfPermission(
18835                android.Manifest.permission.DELETE_PACKAGES, null);
18836        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18837        Preconditions.checkNotNull(versionedPackage);
18838        Preconditions.checkNotNull(observer);
18839        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18840                PackageManager.VERSION_CODE_HIGHEST,
18841                Integer.MAX_VALUE, "versionCode must be >= -1");
18842
18843        final String packageName = versionedPackage.getPackageName();
18844        final int versionCode = versionedPackage.getVersionCode();
18845        final String internalPackageName;
18846        synchronized (mPackages) {
18847            // Normalize package name to handle renamed packages and static libs
18848            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18849                    versionedPackage.getVersionCode());
18850        }
18851
18852        final int uid = Binder.getCallingUid();
18853        if (!isOrphaned(internalPackageName)
18854                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18855            try {
18856                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18857                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18858                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18859                observer.onUserActionRequired(intent);
18860            } catch (RemoteException re) {
18861            }
18862            return;
18863        }
18864        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18865        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18866        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18867            mContext.enforceCallingOrSelfPermission(
18868                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18869                    "deletePackage for user " + userId);
18870        }
18871
18872        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18873            try {
18874                observer.onPackageDeleted(packageName,
18875                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18876            } catch (RemoteException re) {
18877            }
18878            return;
18879        }
18880
18881        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18882            try {
18883                observer.onPackageDeleted(packageName,
18884                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18885            } catch (RemoteException re) {
18886            }
18887            return;
18888        }
18889
18890        if (DEBUG_REMOVE) {
18891            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18892                    + " deleteAllUsers: " + deleteAllUsers + " version="
18893                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18894                    ? "VERSION_CODE_HIGHEST" : versionCode));
18895        }
18896        // Queue up an async operation since the package deletion may take a little while.
18897        mHandler.post(new Runnable() {
18898            public void run() {
18899                mHandler.removeCallbacks(this);
18900                int returnCode;
18901                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18902                boolean doDeletePackage = true;
18903                if (ps != null) {
18904                    final boolean targetIsInstantApp =
18905                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18906                    doDeletePackage = !targetIsInstantApp
18907                            || canViewInstantApps;
18908                }
18909                if (doDeletePackage) {
18910                    if (!deleteAllUsers) {
18911                        returnCode = deletePackageX(internalPackageName, versionCode,
18912                                userId, deleteFlags);
18913                    } else {
18914                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18915                                internalPackageName, users);
18916                        // If nobody is blocking uninstall, proceed with delete for all users
18917                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18918                            returnCode = deletePackageX(internalPackageName, versionCode,
18919                                    userId, deleteFlags);
18920                        } else {
18921                            // Otherwise uninstall individually for users with blockUninstalls=false
18922                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18923                            for (int userId : users) {
18924                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18925                                    returnCode = deletePackageX(internalPackageName, versionCode,
18926                                            userId, userFlags);
18927                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18928                                        Slog.w(TAG, "Package delete failed for user " + userId
18929                                                + ", returnCode " + returnCode);
18930                                    }
18931                                }
18932                            }
18933                            // The app has only been marked uninstalled for certain users.
18934                            // We still need to report that delete was blocked
18935                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18936                        }
18937                    }
18938                } else {
18939                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18940                }
18941                try {
18942                    observer.onPackageDeleted(packageName, returnCode, null);
18943                } catch (RemoteException e) {
18944                    Log.i(TAG, "Observer no longer exists.");
18945                } //end catch
18946            } //end run
18947        });
18948    }
18949
18950    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18951        if (pkg.staticSharedLibName != null) {
18952            return pkg.manifestPackageName;
18953        }
18954        return pkg.packageName;
18955    }
18956
18957    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18958        // Handle renamed packages
18959        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18960        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18961
18962        // Is this a static library?
18963        SparseArray<SharedLibraryEntry> versionedLib =
18964                mStaticLibsByDeclaringPackage.get(packageName);
18965        if (versionedLib == null || versionedLib.size() <= 0) {
18966            return packageName;
18967        }
18968
18969        // Figure out which lib versions the caller can see
18970        SparseIntArray versionsCallerCanSee = null;
18971        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18972        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18973                && callingAppId != Process.ROOT_UID) {
18974            versionsCallerCanSee = new SparseIntArray();
18975            String libName = versionedLib.valueAt(0).info.getName();
18976            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18977            if (uidPackages != null) {
18978                for (String uidPackage : uidPackages) {
18979                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18980                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18981                    if (libIdx >= 0) {
18982                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18983                        versionsCallerCanSee.append(libVersion, libVersion);
18984                    }
18985                }
18986            }
18987        }
18988
18989        // Caller can see nothing - done
18990        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18991            return packageName;
18992        }
18993
18994        // Find the version the caller can see and the app version code
18995        SharedLibraryEntry highestVersion = null;
18996        final int versionCount = versionedLib.size();
18997        for (int i = 0; i < versionCount; i++) {
18998            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18999            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19000                    libEntry.info.getVersion()) < 0) {
19001                continue;
19002            }
19003            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19004            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19005                if (libVersionCode == versionCode) {
19006                    return libEntry.apk;
19007                }
19008            } else if (highestVersion == null) {
19009                highestVersion = libEntry;
19010            } else if (libVersionCode  > highestVersion.info
19011                    .getDeclaringPackage().getVersionCode()) {
19012                highestVersion = libEntry;
19013            }
19014        }
19015
19016        if (highestVersion != null) {
19017            return highestVersion.apk;
19018        }
19019
19020        return packageName;
19021    }
19022
19023    boolean isCallerVerifier(int callingUid) {
19024        final int callingUserId = UserHandle.getUserId(callingUid);
19025        return mRequiredVerifierPackage != null &&
19026                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19027    }
19028
19029    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19030        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19031              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19032            return true;
19033        }
19034        final int callingUserId = UserHandle.getUserId(callingUid);
19035        // If the caller installed the pkgName, then allow it to silently uninstall.
19036        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19037            return true;
19038        }
19039
19040        // Allow package verifier to silently uninstall.
19041        if (mRequiredVerifierPackage != null &&
19042                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19043            return true;
19044        }
19045
19046        // Allow package uninstaller to silently uninstall.
19047        if (mRequiredUninstallerPackage != null &&
19048                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19049            return true;
19050        }
19051
19052        // Allow storage manager to silently uninstall.
19053        if (mStorageManagerPackage != null &&
19054                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19055            return true;
19056        }
19057
19058        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19059        // uninstall for device owner provisioning.
19060        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19061                == PERMISSION_GRANTED) {
19062            return true;
19063        }
19064
19065        return false;
19066    }
19067
19068    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19069        int[] result = EMPTY_INT_ARRAY;
19070        for (int userId : userIds) {
19071            if (getBlockUninstallForUser(packageName, userId)) {
19072                result = ArrayUtils.appendInt(result, userId);
19073            }
19074        }
19075        return result;
19076    }
19077
19078    @Override
19079    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19080        final int callingUid = Binder.getCallingUid();
19081        if (getInstantAppPackageName(callingUid) != null
19082                && !isCallerSameApp(packageName, callingUid)) {
19083            return false;
19084        }
19085        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19086    }
19087
19088    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19089        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19090                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19091        try {
19092            if (dpm != null) {
19093                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19094                        /* callingUserOnly =*/ false);
19095                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19096                        : deviceOwnerComponentName.getPackageName();
19097                // Does the package contains the device owner?
19098                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19099                // this check is probably not needed, since DO should be registered as a device
19100                // admin on some user too. (Original bug for this: b/17657954)
19101                if (packageName.equals(deviceOwnerPackageName)) {
19102                    return true;
19103                }
19104                // Does it contain a device admin for any user?
19105                int[] users;
19106                if (userId == UserHandle.USER_ALL) {
19107                    users = sUserManager.getUserIds();
19108                } else {
19109                    users = new int[]{userId};
19110                }
19111                for (int i = 0; i < users.length; ++i) {
19112                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19113                        return true;
19114                    }
19115                }
19116            }
19117        } catch (RemoteException e) {
19118        }
19119        return false;
19120    }
19121
19122    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19123        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19124    }
19125
19126    /**
19127     *  This method is an internal method that could be get invoked either
19128     *  to delete an installed package or to clean up a failed installation.
19129     *  After deleting an installed package, a broadcast is sent to notify any
19130     *  listeners that the package has been removed. For cleaning up a failed
19131     *  installation, the broadcast is not necessary since the package's
19132     *  installation wouldn't have sent the initial broadcast either
19133     *  The key steps in deleting a package are
19134     *  deleting the package information in internal structures like mPackages,
19135     *  deleting the packages base directories through installd
19136     *  updating mSettings to reflect current status
19137     *  persisting settings for later use
19138     *  sending a broadcast if necessary
19139     */
19140    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19141        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19142        final boolean res;
19143
19144        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19145                ? UserHandle.USER_ALL : userId;
19146
19147        if (isPackageDeviceAdmin(packageName, removeUser)) {
19148            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19149            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19150        }
19151
19152        PackageSetting uninstalledPs = null;
19153        PackageParser.Package pkg = null;
19154
19155        // for the uninstall-updates case and restricted profiles, remember the per-
19156        // user handle installed state
19157        int[] allUsers;
19158        synchronized (mPackages) {
19159            uninstalledPs = mSettings.mPackages.get(packageName);
19160            if (uninstalledPs == null) {
19161                Slog.w(TAG, "Not removing non-existent package " + packageName);
19162                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19163            }
19164
19165            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19166                    && uninstalledPs.versionCode != versionCode) {
19167                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19168                        + uninstalledPs.versionCode + " != " + versionCode);
19169                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19170            }
19171
19172            // Static shared libs can be declared by any package, so let us not
19173            // allow removing a package if it provides a lib others depend on.
19174            pkg = mPackages.get(packageName);
19175
19176            allUsers = sUserManager.getUserIds();
19177
19178            if (pkg != null && pkg.staticSharedLibName != null) {
19179                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19180                        pkg.staticSharedLibVersion);
19181                if (libEntry != null) {
19182                    for (int currUserId : allUsers) {
19183                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19184                            continue;
19185                        }
19186                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19187                                libEntry.info, 0, currUserId);
19188                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19189                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19190                                    + " hosting lib " + libEntry.info.getName() + " version "
19191                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19192                                    + " for user " + currUserId);
19193                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19194                        }
19195                    }
19196                }
19197            }
19198
19199            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19200        }
19201
19202        final int freezeUser;
19203        if (isUpdatedSystemApp(uninstalledPs)
19204                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19205            // We're downgrading a system app, which will apply to all users, so
19206            // freeze them all during the downgrade
19207            freezeUser = UserHandle.USER_ALL;
19208        } else {
19209            freezeUser = removeUser;
19210        }
19211
19212        synchronized (mInstallLock) {
19213            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19214            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19215                    deleteFlags, "deletePackageX")) {
19216                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19217                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19218            }
19219            synchronized (mPackages) {
19220                if (res) {
19221                    if (pkg != null) {
19222                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19223                    }
19224                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19225                    updateInstantAppInstallerLocked(packageName);
19226                }
19227            }
19228        }
19229
19230        if (res) {
19231            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19232            info.sendPackageRemovedBroadcasts(killApp);
19233            info.sendSystemPackageUpdatedBroadcasts();
19234            info.sendSystemPackageAppearedBroadcasts();
19235        }
19236        // Force a gc here.
19237        Runtime.getRuntime().gc();
19238        // Delete the resources here after sending the broadcast to let
19239        // other processes clean up before deleting resources.
19240        if (info.args != null) {
19241            synchronized (mInstallLock) {
19242                info.args.doPostDeleteLI(true);
19243            }
19244        }
19245
19246        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19247    }
19248
19249    static class PackageRemovedInfo {
19250        final PackageSender packageSender;
19251        String removedPackage;
19252        String installerPackageName;
19253        int uid = -1;
19254        int removedAppId = -1;
19255        int[] origUsers;
19256        int[] removedUsers = null;
19257        int[] broadcastUsers = null;
19258        SparseArray<Integer> installReasons;
19259        boolean isRemovedPackageSystemUpdate = false;
19260        boolean isUpdate;
19261        boolean dataRemoved;
19262        boolean removedForAllUsers;
19263        boolean isStaticSharedLib;
19264        // Clean up resources deleted packages.
19265        InstallArgs args = null;
19266        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19267        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19268
19269        PackageRemovedInfo(PackageSender packageSender) {
19270            this.packageSender = packageSender;
19271        }
19272
19273        void sendPackageRemovedBroadcasts(boolean killApp) {
19274            sendPackageRemovedBroadcastInternal(killApp);
19275            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19276            for (int i = 0; i < childCount; i++) {
19277                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19278                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19279            }
19280        }
19281
19282        void sendSystemPackageUpdatedBroadcasts() {
19283            if (isRemovedPackageSystemUpdate) {
19284                sendSystemPackageUpdatedBroadcastsInternal();
19285                final int childCount = (removedChildPackages != null)
19286                        ? removedChildPackages.size() : 0;
19287                for (int i = 0; i < childCount; i++) {
19288                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19289                    if (childInfo.isRemovedPackageSystemUpdate) {
19290                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19291                    }
19292                }
19293            }
19294        }
19295
19296        void sendSystemPackageAppearedBroadcasts() {
19297            final int packageCount = (appearedChildPackages != null)
19298                    ? appearedChildPackages.size() : 0;
19299            for (int i = 0; i < packageCount; i++) {
19300                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19301                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19302                    true /*sendBootCompleted*/, false /*startReceiver*/,
19303                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19304            }
19305        }
19306
19307        private void sendSystemPackageUpdatedBroadcastsInternal() {
19308            Bundle extras = new Bundle(2);
19309            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19310            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19311            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19312                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19313            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19314                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19315            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19316                null, null, 0, removedPackage, null, null);
19317            if (installerPackageName != null) {
19318                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19319                        removedPackage, extras, 0 /*flags*/,
19320                        installerPackageName, null, null);
19321                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19322                        removedPackage, extras, 0 /*flags*/,
19323                        installerPackageName, null, null);
19324            }
19325        }
19326
19327        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19328            // Don't send static shared library removal broadcasts as these
19329            // libs are visible only the the apps that depend on them an one
19330            // cannot remove the library if it has a dependency.
19331            if (isStaticSharedLib) {
19332                return;
19333            }
19334            Bundle extras = new Bundle(2);
19335            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19336            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19337            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19338            if (isUpdate || isRemovedPackageSystemUpdate) {
19339                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19340            }
19341            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19342            if (removedPackage != null) {
19343                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19344                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19345                if (installerPackageName != null) {
19346                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19347                            removedPackage, extras, 0 /*flags*/,
19348                            installerPackageName, null, broadcastUsers);
19349                }
19350                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19351                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19352                        removedPackage, extras,
19353                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19354                        null, null, broadcastUsers);
19355                }
19356            }
19357            if (removedAppId >= 0) {
19358                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19359                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19360                    null, null, broadcastUsers);
19361            }
19362        }
19363
19364        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19365            removedUsers = userIds;
19366            if (removedUsers == null) {
19367                broadcastUsers = null;
19368                return;
19369            }
19370
19371            broadcastUsers = EMPTY_INT_ARRAY;
19372            for (int i = userIds.length - 1; i >= 0; --i) {
19373                final int userId = userIds[i];
19374                if (deletedPackageSetting.getInstantApp(userId)) {
19375                    continue;
19376                }
19377                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19378            }
19379        }
19380    }
19381
19382    /*
19383     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19384     * flag is not set, the data directory is removed as well.
19385     * make sure this flag is set for partially installed apps. If not its meaningless to
19386     * delete a partially installed application.
19387     */
19388    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19389            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19390        String packageName = ps.name;
19391        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19392        // Retrieve object to delete permissions for shared user later on
19393        final PackageParser.Package deletedPkg;
19394        final PackageSetting deletedPs;
19395        // reader
19396        synchronized (mPackages) {
19397            deletedPkg = mPackages.get(packageName);
19398            deletedPs = mSettings.mPackages.get(packageName);
19399            if (outInfo != null) {
19400                outInfo.removedPackage = packageName;
19401                outInfo.installerPackageName = ps.installerPackageName;
19402                outInfo.isStaticSharedLib = deletedPkg != null
19403                        && deletedPkg.staticSharedLibName != null;
19404                outInfo.populateUsers(deletedPs == null ? null
19405                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19406            }
19407        }
19408
19409        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19410
19411        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19412            final PackageParser.Package resolvedPkg;
19413            if (deletedPkg != null) {
19414                resolvedPkg = deletedPkg;
19415            } else {
19416                // We don't have a parsed package when it lives on an ejected
19417                // adopted storage device, so fake something together
19418                resolvedPkg = new PackageParser.Package(ps.name);
19419                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19420            }
19421            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19422                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19423            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19424            if (outInfo != null) {
19425                outInfo.dataRemoved = true;
19426            }
19427            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19428        }
19429
19430        int removedAppId = -1;
19431
19432        // writer
19433        synchronized (mPackages) {
19434            boolean installedStateChanged = false;
19435            if (deletedPs != null) {
19436                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19437                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19438                    clearDefaultBrowserIfNeeded(packageName);
19439                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19440                    removedAppId = mSettings.removePackageLPw(packageName);
19441                    if (outInfo != null) {
19442                        outInfo.removedAppId = removedAppId;
19443                    }
19444                    updatePermissionsLPw(deletedPs.name, null, 0);
19445                    if (deletedPs.sharedUser != null) {
19446                        // Remove permissions associated with package. Since runtime
19447                        // permissions are per user we have to kill the removed package
19448                        // or packages running under the shared user of the removed
19449                        // package if revoking the permissions requested only by the removed
19450                        // package is successful and this causes a change in gids.
19451                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19452                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19453                                    userId);
19454                            if (userIdToKill == UserHandle.USER_ALL
19455                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19456                                // If gids changed for this user, kill all affected packages.
19457                                mHandler.post(new Runnable() {
19458                                    @Override
19459                                    public void run() {
19460                                        // This has to happen with no lock held.
19461                                        killApplication(deletedPs.name, deletedPs.appId,
19462                                                KILL_APP_REASON_GIDS_CHANGED);
19463                                    }
19464                                });
19465                                break;
19466                            }
19467                        }
19468                    }
19469                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19470                }
19471                // make sure to preserve per-user disabled state if this removal was just
19472                // a downgrade of a system app to the factory package
19473                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19474                    if (DEBUG_REMOVE) {
19475                        Slog.d(TAG, "Propagating install state across downgrade");
19476                    }
19477                    for (int userId : allUserHandles) {
19478                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19479                        if (DEBUG_REMOVE) {
19480                            Slog.d(TAG, "    user " + userId + " => " + installed);
19481                        }
19482                        if (installed != ps.getInstalled(userId)) {
19483                            installedStateChanged = true;
19484                        }
19485                        ps.setInstalled(installed, userId);
19486                    }
19487                }
19488            }
19489            // can downgrade to reader
19490            if (writeSettings) {
19491                // Save settings now
19492                mSettings.writeLPr();
19493            }
19494            if (installedStateChanged) {
19495                mSettings.writeKernelMappingLPr(ps);
19496            }
19497        }
19498        if (removedAppId != -1) {
19499            // A user ID was deleted here. Go through all users and remove it
19500            // from KeyStore.
19501            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19502        }
19503    }
19504
19505    static boolean locationIsPrivileged(File path) {
19506        try {
19507            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19508                    .getCanonicalPath();
19509            return path.getCanonicalPath().startsWith(privilegedAppDir);
19510        } catch (IOException e) {
19511            Slog.e(TAG, "Unable to access code path " + path);
19512        }
19513        return false;
19514    }
19515
19516    /*
19517     * Tries to delete system package.
19518     */
19519    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19520            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19521            boolean writeSettings) {
19522        if (deletedPs.parentPackageName != null) {
19523            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19524            return false;
19525        }
19526
19527        final boolean applyUserRestrictions
19528                = (allUserHandles != null) && (outInfo.origUsers != null);
19529        final PackageSetting disabledPs;
19530        // Confirm if the system package has been updated
19531        // An updated system app can be deleted. This will also have to restore
19532        // the system pkg from system partition
19533        // reader
19534        synchronized (mPackages) {
19535            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19536        }
19537
19538        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19539                + " disabledPs=" + disabledPs);
19540
19541        if (disabledPs == null) {
19542            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19543            return false;
19544        } else if (DEBUG_REMOVE) {
19545            Slog.d(TAG, "Deleting system pkg from data partition");
19546        }
19547
19548        if (DEBUG_REMOVE) {
19549            if (applyUserRestrictions) {
19550                Slog.d(TAG, "Remembering install states:");
19551                for (int userId : allUserHandles) {
19552                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19553                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19554                }
19555            }
19556        }
19557
19558        // Delete the updated package
19559        outInfo.isRemovedPackageSystemUpdate = true;
19560        if (outInfo.removedChildPackages != null) {
19561            final int childCount = (deletedPs.childPackageNames != null)
19562                    ? deletedPs.childPackageNames.size() : 0;
19563            for (int i = 0; i < childCount; i++) {
19564                String childPackageName = deletedPs.childPackageNames.get(i);
19565                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19566                        .contains(childPackageName)) {
19567                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19568                            childPackageName);
19569                    if (childInfo != null) {
19570                        childInfo.isRemovedPackageSystemUpdate = true;
19571                    }
19572                }
19573            }
19574        }
19575
19576        if (disabledPs.versionCode < deletedPs.versionCode) {
19577            // Delete data for downgrades
19578            flags &= ~PackageManager.DELETE_KEEP_DATA;
19579        } else {
19580            // Preserve data by setting flag
19581            flags |= PackageManager.DELETE_KEEP_DATA;
19582        }
19583
19584        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19585                outInfo, writeSettings, disabledPs.pkg);
19586        if (!ret) {
19587            return false;
19588        }
19589
19590        // writer
19591        synchronized (mPackages) {
19592            // Reinstate the old system package
19593            enableSystemPackageLPw(disabledPs.pkg);
19594            // Remove any native libraries from the upgraded package.
19595            removeNativeBinariesLI(deletedPs);
19596        }
19597
19598        // Install the system package
19599        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19600        int parseFlags = mDefParseFlags
19601                | PackageParser.PARSE_MUST_BE_APK
19602                | PackageParser.PARSE_IS_SYSTEM
19603                | PackageParser.PARSE_IS_SYSTEM_DIR;
19604        if (locationIsPrivileged(disabledPs.codePath)) {
19605            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19606        }
19607
19608        final PackageParser.Package newPkg;
19609        try {
19610            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19611                0 /* currentTime */, null);
19612        } catch (PackageManagerException e) {
19613            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19614                    + e.getMessage());
19615            return false;
19616        }
19617
19618        try {
19619            // update shared libraries for the newly re-installed system package
19620            updateSharedLibrariesLPr(newPkg, null);
19621        } catch (PackageManagerException e) {
19622            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19623        }
19624
19625        prepareAppDataAfterInstallLIF(newPkg);
19626
19627        // writer
19628        synchronized (mPackages) {
19629            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19630
19631            // Propagate the permissions state as we do not want to drop on the floor
19632            // runtime permissions. The update permissions method below will take
19633            // care of removing obsolete permissions and grant install permissions.
19634            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19635            updatePermissionsLPw(newPkg.packageName, newPkg,
19636                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19637
19638            if (applyUserRestrictions) {
19639                boolean installedStateChanged = false;
19640                if (DEBUG_REMOVE) {
19641                    Slog.d(TAG, "Propagating install state across reinstall");
19642                }
19643                for (int userId : allUserHandles) {
19644                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19645                    if (DEBUG_REMOVE) {
19646                        Slog.d(TAG, "    user " + userId + " => " + installed);
19647                    }
19648                    if (installed != ps.getInstalled(userId)) {
19649                        installedStateChanged = true;
19650                    }
19651                    ps.setInstalled(installed, userId);
19652
19653                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19654                }
19655                // Regardless of writeSettings we need to ensure that this restriction
19656                // state propagation is persisted
19657                mSettings.writeAllUsersPackageRestrictionsLPr();
19658                if (installedStateChanged) {
19659                    mSettings.writeKernelMappingLPr(ps);
19660                }
19661            }
19662            // can downgrade to reader here
19663            if (writeSettings) {
19664                mSettings.writeLPr();
19665            }
19666        }
19667        return true;
19668    }
19669
19670    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19671            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19672            PackageRemovedInfo outInfo, boolean writeSettings,
19673            PackageParser.Package replacingPackage) {
19674        synchronized (mPackages) {
19675            if (outInfo != null) {
19676                outInfo.uid = ps.appId;
19677            }
19678
19679            if (outInfo != null && outInfo.removedChildPackages != null) {
19680                final int childCount = (ps.childPackageNames != null)
19681                        ? ps.childPackageNames.size() : 0;
19682                for (int i = 0; i < childCount; i++) {
19683                    String childPackageName = ps.childPackageNames.get(i);
19684                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19685                    if (childPs == null) {
19686                        return false;
19687                    }
19688                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19689                            childPackageName);
19690                    if (childInfo != null) {
19691                        childInfo.uid = childPs.appId;
19692                    }
19693                }
19694            }
19695        }
19696
19697        // Delete package data from internal structures and also remove data if flag is set
19698        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19699
19700        // Delete the child packages data
19701        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19702        for (int i = 0; i < childCount; i++) {
19703            PackageSetting childPs;
19704            synchronized (mPackages) {
19705                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19706            }
19707            if (childPs != null) {
19708                PackageRemovedInfo childOutInfo = (outInfo != null
19709                        && outInfo.removedChildPackages != null)
19710                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19711                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19712                        && (replacingPackage != null
19713                        && !replacingPackage.hasChildPackage(childPs.name))
19714                        ? flags & ~DELETE_KEEP_DATA : flags;
19715                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19716                        deleteFlags, writeSettings);
19717            }
19718        }
19719
19720        // Delete application code and resources only for parent packages
19721        if (ps.parentPackageName == null) {
19722            if (deleteCodeAndResources && (outInfo != null)) {
19723                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19724                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19725                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19726            }
19727        }
19728
19729        return true;
19730    }
19731
19732    @Override
19733    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19734            int userId) {
19735        mContext.enforceCallingOrSelfPermission(
19736                android.Manifest.permission.DELETE_PACKAGES, null);
19737        synchronized (mPackages) {
19738            // Cannot block uninstall of static shared libs as they are
19739            // considered a part of the using app (emulating static linking).
19740            // Also static libs are installed always on internal storage.
19741            PackageParser.Package pkg = mPackages.get(packageName);
19742            if (pkg != null && pkg.staticSharedLibName != null) {
19743                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19744                        + " providing static shared library: " + pkg.staticSharedLibName);
19745                return false;
19746            }
19747            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19748            mSettings.writePackageRestrictionsLPr(userId);
19749        }
19750        return true;
19751    }
19752
19753    @Override
19754    public boolean getBlockUninstallForUser(String packageName, int userId) {
19755        synchronized (mPackages) {
19756            final PackageSetting ps = mSettings.mPackages.get(packageName);
19757            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19758                return false;
19759            }
19760            return mSettings.getBlockUninstallLPr(userId, packageName);
19761        }
19762    }
19763
19764    @Override
19765    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19766        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19767        synchronized (mPackages) {
19768            PackageSetting ps = mSettings.mPackages.get(packageName);
19769            if (ps == null) {
19770                Log.w(TAG, "Package doesn't exist: " + packageName);
19771                return false;
19772            }
19773            if (systemUserApp) {
19774                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19775            } else {
19776                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19777            }
19778            mSettings.writeLPr();
19779        }
19780        return true;
19781    }
19782
19783    /*
19784     * This method handles package deletion in general
19785     */
19786    private boolean deletePackageLIF(String packageName, UserHandle user,
19787            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19788            PackageRemovedInfo outInfo, boolean writeSettings,
19789            PackageParser.Package replacingPackage) {
19790        if (packageName == null) {
19791            Slog.w(TAG, "Attempt to delete null packageName.");
19792            return false;
19793        }
19794
19795        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19796
19797        PackageSetting ps;
19798        synchronized (mPackages) {
19799            ps = mSettings.mPackages.get(packageName);
19800            if (ps == null) {
19801                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19802                return false;
19803            }
19804
19805            if (ps.parentPackageName != null && (!isSystemApp(ps)
19806                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19807                if (DEBUG_REMOVE) {
19808                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19809                            + ((user == null) ? UserHandle.USER_ALL : user));
19810                }
19811                final int removedUserId = (user != null) ? user.getIdentifier()
19812                        : UserHandle.USER_ALL;
19813                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19814                    return false;
19815                }
19816                markPackageUninstalledForUserLPw(ps, user);
19817                scheduleWritePackageRestrictionsLocked(user);
19818                return true;
19819            }
19820        }
19821
19822        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19823                && user.getIdentifier() != UserHandle.USER_ALL)) {
19824            // The caller is asking that the package only be deleted for a single
19825            // user.  To do this, we just mark its uninstalled state and delete
19826            // its data. If this is a system app, we only allow this to happen if
19827            // they have set the special DELETE_SYSTEM_APP which requests different
19828            // semantics than normal for uninstalling system apps.
19829            markPackageUninstalledForUserLPw(ps, user);
19830
19831            if (!isSystemApp(ps)) {
19832                // Do not uninstall the APK if an app should be cached
19833                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19834                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19835                    // Other user still have this package installed, so all
19836                    // we need to do is clear this user's data and save that
19837                    // it is uninstalled.
19838                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19839                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19840                        return false;
19841                    }
19842                    scheduleWritePackageRestrictionsLocked(user);
19843                    return true;
19844                } else {
19845                    // We need to set it back to 'installed' so the uninstall
19846                    // broadcasts will be sent correctly.
19847                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19848                    ps.setInstalled(true, user.getIdentifier());
19849                    mSettings.writeKernelMappingLPr(ps);
19850                }
19851            } else {
19852                // This is a system app, so we assume that the
19853                // other users 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, "Deleting system app");
19857                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19858                    return false;
19859                }
19860                scheduleWritePackageRestrictionsLocked(user);
19861                return true;
19862            }
19863        }
19864
19865        // If we are deleting a composite package for all users, keep track
19866        // of result for each child.
19867        if (ps.childPackageNames != null && outInfo != null) {
19868            synchronized (mPackages) {
19869                final int childCount = ps.childPackageNames.size();
19870                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19871                for (int i = 0; i < childCount; i++) {
19872                    String childPackageName = ps.childPackageNames.get(i);
19873                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19874                    childInfo.removedPackage = childPackageName;
19875                    childInfo.installerPackageName = ps.installerPackageName;
19876                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19877                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19878                    if (childPs != null) {
19879                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19880                    }
19881                }
19882            }
19883        }
19884
19885        boolean ret = false;
19886        if (isSystemApp(ps)) {
19887            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19888            // When an updated system application is deleted we delete the existing resources
19889            // as well and fall back to existing code in system partition
19890            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19891        } else {
19892            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19893            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19894                    outInfo, writeSettings, replacingPackage);
19895        }
19896
19897        // Take a note whether we deleted the package for all users
19898        if (outInfo != null) {
19899            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19900            if (outInfo.removedChildPackages != null) {
19901                synchronized (mPackages) {
19902                    final int childCount = outInfo.removedChildPackages.size();
19903                    for (int i = 0; i < childCount; i++) {
19904                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19905                        if (childInfo != null) {
19906                            childInfo.removedForAllUsers = mPackages.get(
19907                                    childInfo.removedPackage) == null;
19908                        }
19909                    }
19910                }
19911            }
19912            // If we uninstalled an update to a system app there may be some
19913            // child packages that appeared as they are declared in the system
19914            // app but were not declared in the update.
19915            if (isSystemApp(ps)) {
19916                synchronized (mPackages) {
19917                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19918                    final int childCount = (updatedPs.childPackageNames != null)
19919                            ? updatedPs.childPackageNames.size() : 0;
19920                    for (int i = 0; i < childCount; i++) {
19921                        String childPackageName = updatedPs.childPackageNames.get(i);
19922                        if (outInfo.removedChildPackages == null
19923                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19924                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19925                            if (childPs == null) {
19926                                continue;
19927                            }
19928                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19929                            installRes.name = childPackageName;
19930                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19931                            installRes.pkg = mPackages.get(childPackageName);
19932                            installRes.uid = childPs.pkg.applicationInfo.uid;
19933                            if (outInfo.appearedChildPackages == null) {
19934                                outInfo.appearedChildPackages = new ArrayMap<>();
19935                            }
19936                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19937                        }
19938                    }
19939                }
19940            }
19941        }
19942
19943        return ret;
19944    }
19945
19946    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19947        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19948                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19949        for (int nextUserId : userIds) {
19950            if (DEBUG_REMOVE) {
19951                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19952            }
19953            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19954                    false /*installed*/,
19955                    true /*stopped*/,
19956                    true /*notLaunched*/,
19957                    false /*hidden*/,
19958                    false /*suspended*/,
19959                    false /*instantApp*/,
19960                    null /*lastDisableAppCaller*/,
19961                    null /*enabledComponents*/,
19962                    null /*disabledComponents*/,
19963                    ps.readUserState(nextUserId).domainVerificationStatus,
19964                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19965        }
19966        mSettings.writeKernelMappingLPr(ps);
19967    }
19968
19969    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19970            PackageRemovedInfo outInfo) {
19971        final PackageParser.Package pkg;
19972        synchronized (mPackages) {
19973            pkg = mPackages.get(ps.name);
19974        }
19975
19976        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19977                : new int[] {userId};
19978        for (int nextUserId : userIds) {
19979            if (DEBUG_REMOVE) {
19980                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19981                        + nextUserId);
19982            }
19983
19984            destroyAppDataLIF(pkg, userId,
19985                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19986            destroyAppProfilesLIF(pkg, userId);
19987            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19988            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19989            schedulePackageCleaning(ps.name, nextUserId, false);
19990            synchronized (mPackages) {
19991                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19992                    scheduleWritePackageRestrictionsLocked(nextUserId);
19993                }
19994                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19995            }
19996        }
19997
19998        if (outInfo != null) {
19999            outInfo.removedPackage = ps.name;
20000            outInfo.installerPackageName = ps.installerPackageName;
20001            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20002            outInfo.removedAppId = ps.appId;
20003            outInfo.removedUsers = userIds;
20004            outInfo.broadcastUsers = userIds;
20005        }
20006
20007        return true;
20008    }
20009
20010    private final class ClearStorageConnection implements ServiceConnection {
20011        IMediaContainerService mContainerService;
20012
20013        @Override
20014        public void onServiceConnected(ComponentName name, IBinder service) {
20015            synchronized (this) {
20016                mContainerService = IMediaContainerService.Stub
20017                        .asInterface(Binder.allowBlocking(service));
20018                notifyAll();
20019            }
20020        }
20021
20022        @Override
20023        public void onServiceDisconnected(ComponentName name) {
20024        }
20025    }
20026
20027    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20028        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20029
20030        final boolean mounted;
20031        if (Environment.isExternalStorageEmulated()) {
20032            mounted = true;
20033        } else {
20034            final String status = Environment.getExternalStorageState();
20035
20036            mounted = status.equals(Environment.MEDIA_MOUNTED)
20037                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20038        }
20039
20040        if (!mounted) {
20041            return;
20042        }
20043
20044        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20045        int[] users;
20046        if (userId == UserHandle.USER_ALL) {
20047            users = sUserManager.getUserIds();
20048        } else {
20049            users = new int[] { userId };
20050        }
20051        final ClearStorageConnection conn = new ClearStorageConnection();
20052        if (mContext.bindServiceAsUser(
20053                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20054            try {
20055                for (int curUser : users) {
20056                    long timeout = SystemClock.uptimeMillis() + 5000;
20057                    synchronized (conn) {
20058                        long now;
20059                        while (conn.mContainerService == null &&
20060                                (now = SystemClock.uptimeMillis()) < timeout) {
20061                            try {
20062                                conn.wait(timeout - now);
20063                            } catch (InterruptedException e) {
20064                            }
20065                        }
20066                    }
20067                    if (conn.mContainerService == null) {
20068                        return;
20069                    }
20070
20071                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20072                    clearDirectory(conn.mContainerService,
20073                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20074                    if (allData) {
20075                        clearDirectory(conn.mContainerService,
20076                                userEnv.buildExternalStorageAppDataDirs(packageName));
20077                        clearDirectory(conn.mContainerService,
20078                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20079                    }
20080                }
20081            } finally {
20082                mContext.unbindService(conn);
20083            }
20084        }
20085    }
20086
20087    @Override
20088    public void clearApplicationProfileData(String packageName) {
20089        enforceSystemOrRoot("Only the system can clear all profile data");
20090
20091        final PackageParser.Package pkg;
20092        synchronized (mPackages) {
20093            pkg = mPackages.get(packageName);
20094        }
20095
20096        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20097            synchronized (mInstallLock) {
20098                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20099            }
20100        }
20101    }
20102
20103    @Override
20104    public void clearApplicationUserData(final String packageName,
20105            final IPackageDataObserver observer, final int userId) {
20106        mContext.enforceCallingOrSelfPermission(
20107                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20108
20109        final int callingUid = Binder.getCallingUid();
20110        enforceCrossUserPermission(callingUid, userId,
20111                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20112
20113        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20114        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
20115            return;
20116        }
20117        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20118            throw new SecurityException("Cannot clear data for a protected package: "
20119                    + packageName);
20120        }
20121        // Queue up an async operation since the package deletion may take a little while.
20122        mHandler.post(new Runnable() {
20123            public void run() {
20124                mHandler.removeCallbacks(this);
20125                final boolean succeeded;
20126                try (PackageFreezer freezer = freezePackage(packageName,
20127                        "clearApplicationUserData")) {
20128                    synchronized (mInstallLock) {
20129                        succeeded = clearApplicationUserDataLIF(packageName, userId);
20130                    }
20131                    clearExternalStorageDataSync(packageName, userId, true);
20132                    synchronized (mPackages) {
20133                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20134                                packageName, userId);
20135                    }
20136                }
20137                if (succeeded) {
20138                    // invoke DeviceStorageMonitor's update method to clear any notifications
20139                    DeviceStorageMonitorInternal dsm = LocalServices
20140                            .getService(DeviceStorageMonitorInternal.class);
20141                    if (dsm != null) {
20142                        dsm.checkMemory();
20143                    }
20144                }
20145                if(observer != null) {
20146                    try {
20147                        observer.onRemoveCompleted(packageName, succeeded);
20148                    } catch (RemoteException e) {
20149                        Log.i(TAG, "Observer no longer exists.");
20150                    }
20151                } //end if observer
20152            } //end run
20153        });
20154    }
20155
20156    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20157        if (packageName == null) {
20158            Slog.w(TAG, "Attempt to delete null packageName.");
20159            return false;
20160        }
20161
20162        // Try finding details about the requested package
20163        PackageParser.Package pkg;
20164        synchronized (mPackages) {
20165            pkg = mPackages.get(packageName);
20166            if (pkg == null) {
20167                final PackageSetting ps = mSettings.mPackages.get(packageName);
20168                if (ps != null) {
20169                    pkg = ps.pkg;
20170                }
20171            }
20172
20173            if (pkg == null) {
20174                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20175                return false;
20176            }
20177
20178            PackageSetting ps = (PackageSetting) pkg.mExtras;
20179            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20180        }
20181
20182        clearAppDataLIF(pkg, userId,
20183                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20184
20185        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20186        removeKeystoreDataIfNeeded(userId, appId);
20187
20188        UserManagerInternal umInternal = getUserManagerInternal();
20189        final int flags;
20190        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20191            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20192        } else if (umInternal.isUserRunning(userId)) {
20193            flags = StorageManager.FLAG_STORAGE_DE;
20194        } else {
20195            flags = 0;
20196        }
20197        prepareAppDataContentsLIF(pkg, userId, flags);
20198
20199        return true;
20200    }
20201
20202    /**
20203     * Reverts user permission state changes (permissions and flags) in
20204     * all packages for a given user.
20205     *
20206     * @param userId The device user for which to do a reset.
20207     */
20208    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20209        final int packageCount = mPackages.size();
20210        for (int i = 0; i < packageCount; i++) {
20211            PackageParser.Package pkg = mPackages.valueAt(i);
20212            PackageSetting ps = (PackageSetting) pkg.mExtras;
20213            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20214        }
20215    }
20216
20217    private void resetNetworkPolicies(int userId) {
20218        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20219    }
20220
20221    /**
20222     * Reverts user permission state changes (permissions and flags).
20223     *
20224     * @param ps The package for which to reset.
20225     * @param userId The device user for which to do a reset.
20226     */
20227    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20228            final PackageSetting ps, final int userId) {
20229        if (ps.pkg == null) {
20230            return;
20231        }
20232
20233        // These are flags that can change base on user actions.
20234        final int userSettableMask = FLAG_PERMISSION_USER_SET
20235                | FLAG_PERMISSION_USER_FIXED
20236                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20237                | FLAG_PERMISSION_REVIEW_REQUIRED;
20238
20239        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20240                | FLAG_PERMISSION_POLICY_FIXED;
20241
20242        boolean writeInstallPermissions = false;
20243        boolean writeRuntimePermissions = false;
20244
20245        final int permissionCount = ps.pkg.requestedPermissions.size();
20246        for (int i = 0; i < permissionCount; i++) {
20247            String permission = ps.pkg.requestedPermissions.get(i);
20248
20249            BasePermission bp = mSettings.mPermissions.get(permission);
20250            if (bp == null) {
20251                continue;
20252            }
20253
20254            // If shared user we just reset the state to which only this app contributed.
20255            if (ps.sharedUser != null) {
20256                boolean used = false;
20257                final int packageCount = ps.sharedUser.packages.size();
20258                for (int j = 0; j < packageCount; j++) {
20259                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20260                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20261                            && pkg.pkg.requestedPermissions.contains(permission)) {
20262                        used = true;
20263                        break;
20264                    }
20265                }
20266                if (used) {
20267                    continue;
20268                }
20269            }
20270
20271            PermissionsState permissionsState = ps.getPermissionsState();
20272
20273            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20274
20275            // Always clear the user settable flags.
20276            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20277                    bp.name) != null;
20278            // If permission review is enabled and this is a legacy app, mark the
20279            // permission as requiring a review as this is the initial state.
20280            int flags = 0;
20281            if (mPermissionReviewRequired
20282                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20283                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20284            }
20285            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20286                if (hasInstallState) {
20287                    writeInstallPermissions = true;
20288                } else {
20289                    writeRuntimePermissions = true;
20290                }
20291            }
20292
20293            // Below is only runtime permission handling.
20294            if (!bp.isRuntime()) {
20295                continue;
20296            }
20297
20298            // Never clobber system or policy.
20299            if ((oldFlags & policyOrSystemFlags) != 0) {
20300                continue;
20301            }
20302
20303            // If this permission was granted by default, make sure it is.
20304            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20305                if (permissionsState.grantRuntimePermission(bp, userId)
20306                        != PERMISSION_OPERATION_FAILURE) {
20307                    writeRuntimePermissions = true;
20308                }
20309            // If permission review is enabled the permissions for a legacy apps
20310            // are represented as constantly granted runtime ones, so don't revoke.
20311            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20312                // Otherwise, reset the permission.
20313                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20314                switch (revokeResult) {
20315                    case PERMISSION_OPERATION_SUCCESS:
20316                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20317                        writeRuntimePermissions = true;
20318                        final int appId = ps.appId;
20319                        mHandler.post(new Runnable() {
20320                            @Override
20321                            public void run() {
20322                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20323                            }
20324                        });
20325                    } break;
20326                }
20327            }
20328        }
20329
20330        // Synchronously write as we are taking permissions away.
20331        if (writeRuntimePermissions) {
20332            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20333        }
20334
20335        // Synchronously write as we are taking permissions away.
20336        if (writeInstallPermissions) {
20337            mSettings.writeLPr();
20338        }
20339    }
20340
20341    /**
20342     * Remove entries from the keystore daemon. Will only remove it if the
20343     * {@code appId} is valid.
20344     */
20345    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20346        if (appId < 0) {
20347            return;
20348        }
20349
20350        final KeyStore keyStore = KeyStore.getInstance();
20351        if (keyStore != null) {
20352            if (userId == UserHandle.USER_ALL) {
20353                for (final int individual : sUserManager.getUserIds()) {
20354                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20355                }
20356            } else {
20357                keyStore.clearUid(UserHandle.getUid(userId, appId));
20358            }
20359        } else {
20360            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20361        }
20362    }
20363
20364    @Override
20365    public void deleteApplicationCacheFiles(final String packageName,
20366            final IPackageDataObserver observer) {
20367        final int userId = UserHandle.getCallingUserId();
20368        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20369    }
20370
20371    @Override
20372    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20373            final IPackageDataObserver observer) {
20374        final int callingUid = Binder.getCallingUid();
20375        mContext.enforceCallingOrSelfPermission(
20376                android.Manifest.permission.DELETE_CACHE_FILES, null);
20377        enforceCrossUserPermission(callingUid, userId,
20378                /* requireFullPermission= */ true, /* checkShell= */ false,
20379                "delete application cache files");
20380        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20381                android.Manifest.permission.ACCESS_INSTANT_APPS);
20382
20383        final PackageParser.Package pkg;
20384        synchronized (mPackages) {
20385            pkg = mPackages.get(packageName);
20386        }
20387
20388        // Queue up an async operation since the package deletion may take a little while.
20389        mHandler.post(new Runnable() {
20390            public void run() {
20391                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20392                boolean doClearData = true;
20393                if (ps != null) {
20394                    final boolean targetIsInstantApp =
20395                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20396                    doClearData = !targetIsInstantApp
20397                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20398                }
20399                if (doClearData) {
20400                    synchronized (mInstallLock) {
20401                        final int flags = StorageManager.FLAG_STORAGE_DE
20402                                | StorageManager.FLAG_STORAGE_CE;
20403                        // We're only clearing cache files, so we don't care if the
20404                        // app is unfrozen and still able to run
20405                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20406                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20407                    }
20408                    clearExternalStorageDataSync(packageName, userId, false);
20409                }
20410                if (observer != null) {
20411                    try {
20412                        observer.onRemoveCompleted(packageName, true);
20413                    } catch (RemoteException e) {
20414                        Log.i(TAG, "Observer no longer exists.");
20415                    }
20416                }
20417            }
20418        });
20419    }
20420
20421    @Override
20422    public void getPackageSizeInfo(final String packageName, int userHandle,
20423            final IPackageStatsObserver observer) {
20424        throw new UnsupportedOperationException(
20425                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20426    }
20427
20428    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20429        final PackageSetting ps;
20430        synchronized (mPackages) {
20431            ps = mSettings.mPackages.get(packageName);
20432            if (ps == null) {
20433                Slog.w(TAG, "Failed to find settings for " + packageName);
20434                return false;
20435            }
20436        }
20437
20438        final String[] packageNames = { packageName };
20439        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20440        final String[] codePaths = { ps.codePathString };
20441
20442        try {
20443            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20444                    ps.appId, ceDataInodes, codePaths, stats);
20445
20446            // For now, ignore code size of packages on system partition
20447            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20448                stats.codeSize = 0;
20449            }
20450
20451            // External clients expect these to be tracked separately
20452            stats.dataSize -= stats.cacheSize;
20453
20454        } catch (InstallerException e) {
20455            Slog.w(TAG, String.valueOf(e));
20456            return false;
20457        }
20458
20459        return true;
20460    }
20461
20462    private int getUidTargetSdkVersionLockedLPr(int uid) {
20463        Object obj = mSettings.getUserIdLPr(uid);
20464        if (obj instanceof SharedUserSetting) {
20465            final SharedUserSetting sus = (SharedUserSetting) obj;
20466            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20467            final Iterator<PackageSetting> it = sus.packages.iterator();
20468            while (it.hasNext()) {
20469                final PackageSetting ps = it.next();
20470                if (ps.pkg != null) {
20471                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20472                    if (v < vers) vers = v;
20473                }
20474            }
20475            return vers;
20476        } else if (obj instanceof PackageSetting) {
20477            final PackageSetting ps = (PackageSetting) obj;
20478            if (ps.pkg != null) {
20479                return ps.pkg.applicationInfo.targetSdkVersion;
20480            }
20481        }
20482        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20483    }
20484
20485    @Override
20486    public void addPreferredActivity(IntentFilter filter, int match,
20487            ComponentName[] set, ComponentName activity, int userId) {
20488        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20489                "Adding preferred");
20490    }
20491
20492    private void addPreferredActivityInternal(IntentFilter filter, int match,
20493            ComponentName[] set, ComponentName activity, boolean always, int userId,
20494            String opname) {
20495        // writer
20496        int callingUid = Binder.getCallingUid();
20497        enforceCrossUserPermission(callingUid, userId,
20498                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20499        if (filter.countActions() == 0) {
20500            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20501            return;
20502        }
20503        synchronized (mPackages) {
20504            if (mContext.checkCallingOrSelfPermission(
20505                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20506                    != PackageManager.PERMISSION_GRANTED) {
20507                if (getUidTargetSdkVersionLockedLPr(callingUid)
20508                        < Build.VERSION_CODES.FROYO) {
20509                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20510                            + callingUid);
20511                    return;
20512                }
20513                mContext.enforceCallingOrSelfPermission(
20514                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20515            }
20516
20517            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20518            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20519                    + userId + ":");
20520            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20521            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20522            scheduleWritePackageRestrictionsLocked(userId);
20523            postPreferredActivityChangedBroadcast(userId);
20524        }
20525    }
20526
20527    private void postPreferredActivityChangedBroadcast(int userId) {
20528        mHandler.post(() -> {
20529            final IActivityManager am = ActivityManager.getService();
20530            if (am == null) {
20531                return;
20532            }
20533
20534            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20535            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20536            try {
20537                am.broadcastIntent(null, intent, null, null,
20538                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20539                        null, false, false, userId);
20540            } catch (RemoteException e) {
20541            }
20542        });
20543    }
20544
20545    @Override
20546    public void replacePreferredActivity(IntentFilter filter, int match,
20547            ComponentName[] set, ComponentName activity, int userId) {
20548        if (filter.countActions() != 1) {
20549            throw new IllegalArgumentException(
20550                    "replacePreferredActivity expects filter to have only 1 action.");
20551        }
20552        if (filter.countDataAuthorities() != 0
20553                || filter.countDataPaths() != 0
20554                || filter.countDataSchemes() > 1
20555                || filter.countDataTypes() != 0) {
20556            throw new IllegalArgumentException(
20557                    "replacePreferredActivity expects filter to have no data authorities, " +
20558                    "paths, or types; and at most one scheme.");
20559        }
20560
20561        final int callingUid = Binder.getCallingUid();
20562        enforceCrossUserPermission(callingUid, userId,
20563                true /* requireFullPermission */, false /* checkShell */,
20564                "replace preferred activity");
20565        synchronized (mPackages) {
20566            if (mContext.checkCallingOrSelfPermission(
20567                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20568                    != PackageManager.PERMISSION_GRANTED) {
20569                if (getUidTargetSdkVersionLockedLPr(callingUid)
20570                        < Build.VERSION_CODES.FROYO) {
20571                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20572                            + Binder.getCallingUid());
20573                    return;
20574                }
20575                mContext.enforceCallingOrSelfPermission(
20576                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20577            }
20578
20579            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20580            if (pir != null) {
20581                // Get all of the existing entries that exactly match this filter.
20582                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20583                if (existing != null && existing.size() == 1) {
20584                    PreferredActivity cur = existing.get(0);
20585                    if (DEBUG_PREFERRED) {
20586                        Slog.i(TAG, "Checking replace of preferred:");
20587                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20588                        if (!cur.mPref.mAlways) {
20589                            Slog.i(TAG, "  -- CUR; not mAlways!");
20590                        } else {
20591                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20592                            Slog.i(TAG, "  -- CUR: mSet="
20593                                    + Arrays.toString(cur.mPref.mSetComponents));
20594                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20595                            Slog.i(TAG, "  -- NEW: mMatch="
20596                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20597                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20598                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20599                        }
20600                    }
20601                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20602                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20603                            && cur.mPref.sameSet(set)) {
20604                        // Setting the preferred activity to what it happens to be already
20605                        if (DEBUG_PREFERRED) {
20606                            Slog.i(TAG, "Replacing with same preferred activity "
20607                                    + cur.mPref.mShortComponent + " for user "
20608                                    + userId + ":");
20609                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20610                        }
20611                        return;
20612                    }
20613                }
20614
20615                if (existing != null) {
20616                    if (DEBUG_PREFERRED) {
20617                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20618                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20619                    }
20620                    for (int i = 0; i < existing.size(); i++) {
20621                        PreferredActivity pa = existing.get(i);
20622                        if (DEBUG_PREFERRED) {
20623                            Slog.i(TAG, "Removing existing preferred activity "
20624                                    + pa.mPref.mComponent + ":");
20625                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20626                        }
20627                        pir.removeFilter(pa);
20628                    }
20629                }
20630            }
20631            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20632                    "Replacing preferred");
20633        }
20634    }
20635
20636    @Override
20637    public void clearPackagePreferredActivities(String packageName) {
20638        final int callingUid = Binder.getCallingUid();
20639        if (getInstantAppPackageName(callingUid) != null) {
20640            return;
20641        }
20642        // writer
20643        synchronized (mPackages) {
20644            PackageParser.Package pkg = mPackages.get(packageName);
20645            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20646                if (mContext.checkCallingOrSelfPermission(
20647                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20648                        != PackageManager.PERMISSION_GRANTED) {
20649                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20650                            < Build.VERSION_CODES.FROYO) {
20651                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20652                                + callingUid);
20653                        return;
20654                    }
20655                    mContext.enforceCallingOrSelfPermission(
20656                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20657                }
20658            }
20659            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20660            if (ps != null
20661                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20662                return;
20663            }
20664            int user = UserHandle.getCallingUserId();
20665            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20666                scheduleWritePackageRestrictionsLocked(user);
20667            }
20668        }
20669    }
20670
20671    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20672    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20673        ArrayList<PreferredActivity> removed = null;
20674        boolean changed = false;
20675        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20676            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20677            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20678            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20679                continue;
20680            }
20681            Iterator<PreferredActivity> it = pir.filterIterator();
20682            while (it.hasNext()) {
20683                PreferredActivity pa = it.next();
20684                // Mark entry for removal only if it matches the package name
20685                // and the entry is of type "always".
20686                if (packageName == null ||
20687                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20688                                && pa.mPref.mAlways)) {
20689                    if (removed == null) {
20690                        removed = new ArrayList<PreferredActivity>();
20691                    }
20692                    removed.add(pa);
20693                }
20694            }
20695            if (removed != null) {
20696                for (int j=0; j<removed.size(); j++) {
20697                    PreferredActivity pa = removed.get(j);
20698                    pir.removeFilter(pa);
20699                }
20700                changed = true;
20701            }
20702        }
20703        if (changed) {
20704            postPreferredActivityChangedBroadcast(userId);
20705        }
20706        return changed;
20707    }
20708
20709    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20710    private void clearIntentFilterVerificationsLPw(int userId) {
20711        final int packageCount = mPackages.size();
20712        for (int i = 0; i < packageCount; i++) {
20713            PackageParser.Package pkg = mPackages.valueAt(i);
20714            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20715        }
20716    }
20717
20718    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20719    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20720        if (userId == UserHandle.USER_ALL) {
20721            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20722                    sUserManager.getUserIds())) {
20723                for (int oneUserId : sUserManager.getUserIds()) {
20724                    scheduleWritePackageRestrictionsLocked(oneUserId);
20725                }
20726            }
20727        } else {
20728            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20729                scheduleWritePackageRestrictionsLocked(userId);
20730            }
20731        }
20732    }
20733
20734    /** Clears state for all users, and touches intent filter verification policy */
20735    void clearDefaultBrowserIfNeeded(String packageName) {
20736        for (int oneUserId : sUserManager.getUserIds()) {
20737            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20738        }
20739    }
20740
20741    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20742        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20743        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20744            if (packageName.equals(defaultBrowserPackageName)) {
20745                setDefaultBrowserPackageName(null, userId);
20746            }
20747        }
20748    }
20749
20750    @Override
20751    public void resetApplicationPreferences(int userId) {
20752        mContext.enforceCallingOrSelfPermission(
20753                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20754        final long identity = Binder.clearCallingIdentity();
20755        // writer
20756        try {
20757            synchronized (mPackages) {
20758                clearPackagePreferredActivitiesLPw(null, userId);
20759                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20760                // TODO: We have to reset the default SMS and Phone. This requires
20761                // significant refactoring to keep all default apps in the package
20762                // manager (cleaner but more work) or have the services provide
20763                // callbacks to the package manager to request a default app reset.
20764                applyFactoryDefaultBrowserLPw(userId);
20765                clearIntentFilterVerificationsLPw(userId);
20766                primeDomainVerificationsLPw(userId);
20767                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20768                scheduleWritePackageRestrictionsLocked(userId);
20769            }
20770            resetNetworkPolicies(userId);
20771        } finally {
20772            Binder.restoreCallingIdentity(identity);
20773        }
20774    }
20775
20776    @Override
20777    public int getPreferredActivities(List<IntentFilter> outFilters,
20778            List<ComponentName> outActivities, String packageName) {
20779        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20780            return 0;
20781        }
20782        int num = 0;
20783        final int userId = UserHandle.getCallingUserId();
20784        // reader
20785        synchronized (mPackages) {
20786            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20787            if (pir != null) {
20788                final Iterator<PreferredActivity> it = pir.filterIterator();
20789                while (it.hasNext()) {
20790                    final PreferredActivity pa = it.next();
20791                    if (packageName == null
20792                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20793                                    && pa.mPref.mAlways)) {
20794                        if (outFilters != null) {
20795                            outFilters.add(new IntentFilter(pa));
20796                        }
20797                        if (outActivities != null) {
20798                            outActivities.add(pa.mPref.mComponent);
20799                        }
20800                    }
20801                }
20802            }
20803        }
20804
20805        return num;
20806    }
20807
20808    @Override
20809    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20810            int userId) {
20811        int callingUid = Binder.getCallingUid();
20812        if (callingUid != Process.SYSTEM_UID) {
20813            throw new SecurityException(
20814                    "addPersistentPreferredActivity can only be run by the system");
20815        }
20816        if (filter.countActions() == 0) {
20817            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20818            return;
20819        }
20820        synchronized (mPackages) {
20821            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20822                    ":");
20823            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20824            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20825                    new PersistentPreferredActivity(filter, activity));
20826            scheduleWritePackageRestrictionsLocked(userId);
20827            postPreferredActivityChangedBroadcast(userId);
20828        }
20829    }
20830
20831    @Override
20832    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20833        int callingUid = Binder.getCallingUid();
20834        if (callingUid != Process.SYSTEM_UID) {
20835            throw new SecurityException(
20836                    "clearPackagePersistentPreferredActivities can only be run by the system");
20837        }
20838        ArrayList<PersistentPreferredActivity> removed = null;
20839        boolean changed = false;
20840        synchronized (mPackages) {
20841            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20842                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20843                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20844                        .valueAt(i);
20845                if (userId != thisUserId) {
20846                    continue;
20847                }
20848                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20849                while (it.hasNext()) {
20850                    PersistentPreferredActivity ppa = it.next();
20851                    // Mark entry for removal only if it matches the package name.
20852                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20853                        if (removed == null) {
20854                            removed = new ArrayList<PersistentPreferredActivity>();
20855                        }
20856                        removed.add(ppa);
20857                    }
20858                }
20859                if (removed != null) {
20860                    for (int j=0; j<removed.size(); j++) {
20861                        PersistentPreferredActivity ppa = removed.get(j);
20862                        ppir.removeFilter(ppa);
20863                    }
20864                    changed = true;
20865                }
20866            }
20867
20868            if (changed) {
20869                scheduleWritePackageRestrictionsLocked(userId);
20870                postPreferredActivityChangedBroadcast(userId);
20871            }
20872        }
20873    }
20874
20875    /**
20876     * Common machinery for picking apart a restored XML blob and passing
20877     * it to a caller-supplied functor to be applied to the running system.
20878     */
20879    private void restoreFromXml(XmlPullParser parser, int userId,
20880            String expectedStartTag, BlobXmlRestorer functor)
20881            throws IOException, XmlPullParserException {
20882        int type;
20883        while ((type = parser.next()) != XmlPullParser.START_TAG
20884                && type != XmlPullParser.END_DOCUMENT) {
20885        }
20886        if (type != XmlPullParser.START_TAG) {
20887            // oops didn't find a start tag?!
20888            if (DEBUG_BACKUP) {
20889                Slog.e(TAG, "Didn't find start tag during restore");
20890            }
20891            return;
20892        }
20893Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20894        // this is supposed to be TAG_PREFERRED_BACKUP
20895        if (!expectedStartTag.equals(parser.getName())) {
20896            if (DEBUG_BACKUP) {
20897                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20898            }
20899            return;
20900        }
20901
20902        // skip interfering stuff, then we're aligned with the backing implementation
20903        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20904Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20905        functor.apply(parser, userId);
20906    }
20907
20908    private interface BlobXmlRestorer {
20909        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20910    }
20911
20912    /**
20913     * Non-Binder method, support for the backup/restore mechanism: write the
20914     * full set of preferred activities in its canonical XML format.  Returns the
20915     * XML output as a byte array, or null if there is none.
20916     */
20917    @Override
20918    public byte[] getPreferredActivityBackup(int userId) {
20919        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20920            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20921        }
20922
20923        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20924        try {
20925            final XmlSerializer serializer = new FastXmlSerializer();
20926            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20927            serializer.startDocument(null, true);
20928            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20929
20930            synchronized (mPackages) {
20931                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20932            }
20933
20934            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20935            serializer.endDocument();
20936            serializer.flush();
20937        } catch (Exception e) {
20938            if (DEBUG_BACKUP) {
20939                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20940            }
20941            return null;
20942        }
20943
20944        return dataStream.toByteArray();
20945    }
20946
20947    @Override
20948    public void restorePreferredActivities(byte[] backup, int userId) {
20949        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20950            throw new SecurityException("Only the system may call restorePreferredActivities()");
20951        }
20952
20953        try {
20954            final XmlPullParser parser = Xml.newPullParser();
20955            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20956            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20957                    new BlobXmlRestorer() {
20958                        @Override
20959                        public void apply(XmlPullParser parser, int userId)
20960                                throws XmlPullParserException, IOException {
20961                            synchronized (mPackages) {
20962                                mSettings.readPreferredActivitiesLPw(parser, userId);
20963                            }
20964                        }
20965                    } );
20966        } catch (Exception e) {
20967            if (DEBUG_BACKUP) {
20968                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20969            }
20970        }
20971    }
20972
20973    /**
20974     * Non-Binder method, support for the backup/restore mechanism: write the
20975     * default browser (etc) settings in its canonical XML format.  Returns the default
20976     * browser XML representation as a byte array, or null if there is none.
20977     */
20978    @Override
20979    public byte[] getDefaultAppsBackup(int userId) {
20980        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20981            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20982        }
20983
20984        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20985        try {
20986            final XmlSerializer serializer = new FastXmlSerializer();
20987            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20988            serializer.startDocument(null, true);
20989            serializer.startTag(null, TAG_DEFAULT_APPS);
20990
20991            synchronized (mPackages) {
20992                mSettings.writeDefaultAppsLPr(serializer, userId);
20993            }
20994
20995            serializer.endTag(null, TAG_DEFAULT_APPS);
20996            serializer.endDocument();
20997            serializer.flush();
20998        } catch (Exception e) {
20999            if (DEBUG_BACKUP) {
21000                Slog.e(TAG, "Unable to write default apps for backup", e);
21001            }
21002            return null;
21003        }
21004
21005        return dataStream.toByteArray();
21006    }
21007
21008    @Override
21009    public void restoreDefaultApps(byte[] backup, int userId) {
21010        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21011            throw new SecurityException("Only the system may call restoreDefaultApps()");
21012        }
21013
21014        try {
21015            final XmlPullParser parser = Xml.newPullParser();
21016            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21017            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21018                    new BlobXmlRestorer() {
21019                        @Override
21020                        public void apply(XmlPullParser parser, int userId)
21021                                throws XmlPullParserException, IOException {
21022                            synchronized (mPackages) {
21023                                mSettings.readDefaultAppsLPw(parser, userId);
21024                            }
21025                        }
21026                    } );
21027        } catch (Exception e) {
21028            if (DEBUG_BACKUP) {
21029                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21030            }
21031        }
21032    }
21033
21034    @Override
21035    public byte[] getIntentFilterVerificationBackup(int userId) {
21036        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21037            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21038        }
21039
21040        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21041        try {
21042            final XmlSerializer serializer = new FastXmlSerializer();
21043            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21044            serializer.startDocument(null, true);
21045            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21046
21047            synchronized (mPackages) {
21048                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21049            }
21050
21051            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21052            serializer.endDocument();
21053            serializer.flush();
21054        } catch (Exception e) {
21055            if (DEBUG_BACKUP) {
21056                Slog.e(TAG, "Unable to write default apps for backup", e);
21057            }
21058            return null;
21059        }
21060
21061        return dataStream.toByteArray();
21062    }
21063
21064    @Override
21065    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21066        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21067            throw new SecurityException("Only the system may call restorePreferredActivities()");
21068        }
21069
21070        try {
21071            final XmlPullParser parser = Xml.newPullParser();
21072            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21073            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21074                    new BlobXmlRestorer() {
21075                        @Override
21076                        public void apply(XmlPullParser parser, int userId)
21077                                throws XmlPullParserException, IOException {
21078                            synchronized (mPackages) {
21079                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21080                                mSettings.writeLPr();
21081                            }
21082                        }
21083                    } );
21084        } catch (Exception e) {
21085            if (DEBUG_BACKUP) {
21086                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21087            }
21088        }
21089    }
21090
21091    @Override
21092    public byte[] getPermissionGrantBackup(int userId) {
21093        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21094            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21095        }
21096
21097        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21098        try {
21099            final XmlSerializer serializer = new FastXmlSerializer();
21100            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21101            serializer.startDocument(null, true);
21102            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21103
21104            synchronized (mPackages) {
21105                serializeRuntimePermissionGrantsLPr(serializer, userId);
21106            }
21107
21108            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21109            serializer.endDocument();
21110            serializer.flush();
21111        } catch (Exception e) {
21112            if (DEBUG_BACKUP) {
21113                Slog.e(TAG, "Unable to write default apps for backup", e);
21114            }
21115            return null;
21116        }
21117
21118        return dataStream.toByteArray();
21119    }
21120
21121    @Override
21122    public void restorePermissionGrants(byte[] backup, int userId) {
21123        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21124            throw new SecurityException("Only the system may call restorePermissionGrants()");
21125        }
21126
21127        try {
21128            final XmlPullParser parser = Xml.newPullParser();
21129            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21130            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21131                    new BlobXmlRestorer() {
21132                        @Override
21133                        public void apply(XmlPullParser parser, int userId)
21134                                throws XmlPullParserException, IOException {
21135                            synchronized (mPackages) {
21136                                processRestoredPermissionGrantsLPr(parser, userId);
21137                            }
21138                        }
21139                    } );
21140        } catch (Exception e) {
21141            if (DEBUG_BACKUP) {
21142                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21143            }
21144        }
21145    }
21146
21147    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21148            throws IOException {
21149        serializer.startTag(null, TAG_ALL_GRANTS);
21150
21151        final int N = mSettings.mPackages.size();
21152        for (int i = 0; i < N; i++) {
21153            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21154            boolean pkgGrantsKnown = false;
21155
21156            PermissionsState packagePerms = ps.getPermissionsState();
21157
21158            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21159                final int grantFlags = state.getFlags();
21160                // only look at grants that are not system/policy fixed
21161                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21162                    final boolean isGranted = state.isGranted();
21163                    // And only back up the user-twiddled state bits
21164                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21165                        final String packageName = mSettings.mPackages.keyAt(i);
21166                        if (!pkgGrantsKnown) {
21167                            serializer.startTag(null, TAG_GRANT);
21168                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21169                            pkgGrantsKnown = true;
21170                        }
21171
21172                        final boolean userSet =
21173                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21174                        final boolean userFixed =
21175                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21176                        final boolean revoke =
21177                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21178
21179                        serializer.startTag(null, TAG_PERMISSION);
21180                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21181                        if (isGranted) {
21182                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21183                        }
21184                        if (userSet) {
21185                            serializer.attribute(null, ATTR_USER_SET, "true");
21186                        }
21187                        if (userFixed) {
21188                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21189                        }
21190                        if (revoke) {
21191                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21192                        }
21193                        serializer.endTag(null, TAG_PERMISSION);
21194                    }
21195                }
21196            }
21197
21198            if (pkgGrantsKnown) {
21199                serializer.endTag(null, TAG_GRANT);
21200            }
21201        }
21202
21203        serializer.endTag(null, TAG_ALL_GRANTS);
21204    }
21205
21206    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21207            throws XmlPullParserException, IOException {
21208        String pkgName = null;
21209        int outerDepth = parser.getDepth();
21210        int type;
21211        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21212                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21213            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21214                continue;
21215            }
21216
21217            final String tagName = parser.getName();
21218            if (tagName.equals(TAG_GRANT)) {
21219                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21220                if (DEBUG_BACKUP) {
21221                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21222                }
21223            } else if (tagName.equals(TAG_PERMISSION)) {
21224
21225                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21226                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21227
21228                int newFlagSet = 0;
21229                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21230                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21231                }
21232                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21233                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21234                }
21235                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21236                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21237                }
21238                if (DEBUG_BACKUP) {
21239                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21240                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21241                }
21242                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21243                if (ps != null) {
21244                    // Already installed so we apply the grant immediately
21245                    if (DEBUG_BACKUP) {
21246                        Slog.v(TAG, "        + already installed; applying");
21247                    }
21248                    PermissionsState perms = ps.getPermissionsState();
21249                    BasePermission bp = mSettings.mPermissions.get(permName);
21250                    if (bp != null) {
21251                        if (isGranted) {
21252                            perms.grantRuntimePermission(bp, userId);
21253                        }
21254                        if (newFlagSet != 0) {
21255                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21256                        }
21257                    }
21258                } else {
21259                    // Need to wait for post-restore install to apply the grant
21260                    if (DEBUG_BACKUP) {
21261                        Slog.v(TAG, "        - not yet installed; saving for later");
21262                    }
21263                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21264                            isGranted, newFlagSet, userId);
21265                }
21266            } else {
21267                PackageManagerService.reportSettingsProblem(Log.WARN,
21268                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21269                XmlUtils.skipCurrentTag(parser);
21270            }
21271        }
21272
21273        scheduleWriteSettingsLocked();
21274        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21275    }
21276
21277    @Override
21278    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21279            int sourceUserId, int targetUserId, int flags) {
21280        mContext.enforceCallingOrSelfPermission(
21281                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21282        int callingUid = Binder.getCallingUid();
21283        enforceOwnerRights(ownerPackage, callingUid);
21284        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21285        if (intentFilter.countActions() == 0) {
21286            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21287            return;
21288        }
21289        synchronized (mPackages) {
21290            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21291                    ownerPackage, targetUserId, flags);
21292            CrossProfileIntentResolver resolver =
21293                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21294            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21295            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21296            if (existing != null) {
21297                int size = existing.size();
21298                for (int i = 0; i < size; i++) {
21299                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21300                        return;
21301                    }
21302                }
21303            }
21304            resolver.addFilter(newFilter);
21305            scheduleWritePackageRestrictionsLocked(sourceUserId);
21306        }
21307    }
21308
21309    @Override
21310    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21311        mContext.enforceCallingOrSelfPermission(
21312                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21313        final int callingUid = Binder.getCallingUid();
21314        enforceOwnerRights(ownerPackage, callingUid);
21315        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21316        synchronized (mPackages) {
21317            CrossProfileIntentResolver resolver =
21318                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21319            ArraySet<CrossProfileIntentFilter> set =
21320                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21321            for (CrossProfileIntentFilter filter : set) {
21322                if (filter.getOwnerPackage().equals(ownerPackage)) {
21323                    resolver.removeFilter(filter);
21324                }
21325            }
21326            scheduleWritePackageRestrictionsLocked(sourceUserId);
21327        }
21328    }
21329
21330    // Enforcing that callingUid is owning pkg on userId
21331    private void enforceOwnerRights(String pkg, int callingUid) {
21332        // The system owns everything.
21333        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21334            return;
21335        }
21336        final int callingUserId = UserHandle.getUserId(callingUid);
21337        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21338        if (pi == null) {
21339            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21340                    + callingUserId);
21341        }
21342        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21343            throw new SecurityException("Calling uid " + callingUid
21344                    + " does not own package " + pkg);
21345        }
21346    }
21347
21348    @Override
21349    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21350        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21351            return null;
21352        }
21353        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21354    }
21355
21356    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21357        UserManagerService ums = UserManagerService.getInstance();
21358        if (ums != null) {
21359            final UserInfo parent = ums.getProfileParent(userId);
21360            final int launcherUid = (parent != null) ? parent.id : userId;
21361            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21362            if (launcherComponent != null) {
21363                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21364                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21365                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21366                        .setPackage(launcherComponent.getPackageName());
21367                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21368            }
21369        }
21370    }
21371
21372    /**
21373     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21374     * then reports the most likely home activity or null if there are more than one.
21375     */
21376    private ComponentName getDefaultHomeActivity(int userId) {
21377        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21378        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21379        if (cn != null) {
21380            return cn;
21381        }
21382
21383        // Find the launcher with the highest priority and return that component if there are no
21384        // other home activity with the same priority.
21385        int lastPriority = Integer.MIN_VALUE;
21386        ComponentName lastComponent = null;
21387        final int size = allHomeCandidates.size();
21388        for (int i = 0; i < size; i++) {
21389            final ResolveInfo ri = allHomeCandidates.get(i);
21390            if (ri.priority > lastPriority) {
21391                lastComponent = ri.activityInfo.getComponentName();
21392                lastPriority = ri.priority;
21393            } else if (ri.priority == lastPriority) {
21394                // Two components found with same priority.
21395                lastComponent = null;
21396            }
21397        }
21398        return lastComponent;
21399    }
21400
21401    private Intent getHomeIntent() {
21402        Intent intent = new Intent(Intent.ACTION_MAIN);
21403        intent.addCategory(Intent.CATEGORY_HOME);
21404        intent.addCategory(Intent.CATEGORY_DEFAULT);
21405        return intent;
21406    }
21407
21408    private IntentFilter getHomeFilter() {
21409        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21410        filter.addCategory(Intent.CATEGORY_HOME);
21411        filter.addCategory(Intent.CATEGORY_DEFAULT);
21412        return filter;
21413    }
21414
21415    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21416            int userId) {
21417        Intent intent  = getHomeIntent();
21418        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21419                PackageManager.GET_META_DATA, userId);
21420        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21421                true, false, false, userId);
21422
21423        allHomeCandidates.clear();
21424        if (list != null) {
21425            for (ResolveInfo ri : list) {
21426                allHomeCandidates.add(ri);
21427            }
21428        }
21429        return (preferred == null || preferred.activityInfo == null)
21430                ? null
21431                : new ComponentName(preferred.activityInfo.packageName,
21432                        preferred.activityInfo.name);
21433    }
21434
21435    @Override
21436    public void setHomeActivity(ComponentName comp, int userId) {
21437        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21438            return;
21439        }
21440        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21441        getHomeActivitiesAsUser(homeActivities, userId);
21442
21443        boolean found = false;
21444
21445        final int size = homeActivities.size();
21446        final ComponentName[] set = new ComponentName[size];
21447        for (int i = 0; i < size; i++) {
21448            final ResolveInfo candidate = homeActivities.get(i);
21449            final ActivityInfo info = candidate.activityInfo;
21450            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21451            set[i] = activityName;
21452            if (!found && activityName.equals(comp)) {
21453                found = true;
21454            }
21455        }
21456        if (!found) {
21457            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21458                    + userId);
21459        }
21460        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21461                set, comp, userId);
21462    }
21463
21464    private @Nullable String getSetupWizardPackageName() {
21465        final Intent intent = new Intent(Intent.ACTION_MAIN);
21466        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21467
21468        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21469                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21470                        | MATCH_DISABLED_COMPONENTS,
21471                UserHandle.myUserId());
21472        if (matches.size() == 1) {
21473            return matches.get(0).getComponentInfo().packageName;
21474        } else {
21475            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21476                    + ": matches=" + matches);
21477            return null;
21478        }
21479    }
21480
21481    private @Nullable String getStorageManagerPackageName() {
21482        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21483
21484        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21485                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21486                        | MATCH_DISABLED_COMPONENTS,
21487                UserHandle.myUserId());
21488        if (matches.size() == 1) {
21489            return matches.get(0).getComponentInfo().packageName;
21490        } else {
21491            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21492                    + matches.size() + ": matches=" + matches);
21493            return null;
21494        }
21495    }
21496
21497    @Override
21498    public void setApplicationEnabledSetting(String appPackageName,
21499            int newState, int flags, int userId, String callingPackage) {
21500        if (!sUserManager.exists(userId)) return;
21501        if (callingPackage == null) {
21502            callingPackage = Integer.toString(Binder.getCallingUid());
21503        }
21504        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21505    }
21506
21507    @Override
21508    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21509        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21510        synchronized (mPackages) {
21511            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21512            if (pkgSetting != null) {
21513                pkgSetting.setUpdateAvailable(updateAvailable);
21514            }
21515        }
21516    }
21517
21518    @Override
21519    public void setComponentEnabledSetting(ComponentName componentName,
21520            int newState, int flags, int userId) {
21521        if (!sUserManager.exists(userId)) return;
21522        setEnabledSetting(componentName.getPackageName(),
21523                componentName.getClassName(), newState, flags, userId, null);
21524    }
21525
21526    private void setEnabledSetting(final String packageName, String className, int newState,
21527            final int flags, int userId, String callingPackage) {
21528        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21529              || newState == COMPONENT_ENABLED_STATE_ENABLED
21530              || newState == COMPONENT_ENABLED_STATE_DISABLED
21531              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21532              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21533            throw new IllegalArgumentException("Invalid new component state: "
21534                    + newState);
21535        }
21536        PackageSetting pkgSetting;
21537        final int callingUid = Binder.getCallingUid();
21538        final int permission;
21539        if (callingUid == Process.SYSTEM_UID) {
21540            permission = PackageManager.PERMISSION_GRANTED;
21541        } else {
21542            permission = mContext.checkCallingOrSelfPermission(
21543                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21544        }
21545        enforceCrossUserPermission(callingUid, userId,
21546                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21547        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21548        boolean sendNow = false;
21549        boolean isApp = (className == null);
21550        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21551        String componentName = isApp ? packageName : className;
21552        int packageUid = -1;
21553        ArrayList<String> components;
21554
21555        // reader
21556        synchronized (mPackages) {
21557            pkgSetting = mSettings.mPackages.get(packageName);
21558            if (pkgSetting == null) {
21559                if (!isCallerInstantApp) {
21560                    if (className == null) {
21561                        throw new IllegalArgumentException("Unknown package: " + packageName);
21562                    }
21563                    throw new IllegalArgumentException(
21564                            "Unknown component: " + packageName + "/" + className);
21565                } else {
21566                    // throw SecurityException to prevent leaking package information
21567                    throw new SecurityException(
21568                            "Attempt to change component state; "
21569                            + "pid=" + Binder.getCallingPid()
21570                            + ", uid=" + callingUid
21571                            + (className == null
21572                                    ? ", package=" + packageName
21573                                    : ", component=" + packageName + "/" + className));
21574                }
21575            }
21576        }
21577
21578        // Limit who can change which apps
21579        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21580            // Don't allow apps that don't have permission to modify other apps
21581            if (!allowedByPermission
21582                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21583                throw new SecurityException(
21584                        "Attempt to change component state; "
21585                        + "pid=" + Binder.getCallingPid()
21586                        + ", uid=" + callingUid
21587                        + (className == null
21588                                ? ", package=" + packageName
21589                                : ", component=" + packageName + "/" + className));
21590            }
21591            // Don't allow changing protected packages.
21592            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21593                throw new SecurityException("Cannot disable a protected package: " + packageName);
21594            }
21595        }
21596
21597        synchronized (mPackages) {
21598            if (callingUid == Process.SHELL_UID
21599                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21600                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21601                // unless it is a test package.
21602                int oldState = pkgSetting.getEnabled(userId);
21603                if (className == null
21604                    &&
21605                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21606                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21607                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21608                    &&
21609                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21610                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21611                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21612                    // ok
21613                } else {
21614                    throw new SecurityException(
21615                            "Shell cannot change component state for " + packageName + "/"
21616                            + className + " to " + newState);
21617                }
21618            }
21619            if (className == null) {
21620                // We're dealing with an application/package level state change
21621                if (pkgSetting.getEnabled(userId) == newState) {
21622                    // Nothing to do
21623                    return;
21624                }
21625                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21626                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21627                    // Don't care about who enables an app.
21628                    callingPackage = null;
21629                }
21630                pkgSetting.setEnabled(newState, userId, callingPackage);
21631                // pkgSetting.pkg.mSetEnabled = newState;
21632            } else {
21633                // We're dealing with a component level state change
21634                // First, verify that this is a valid class name.
21635                PackageParser.Package pkg = pkgSetting.pkg;
21636                if (pkg == null || !pkg.hasComponentClassName(className)) {
21637                    if (pkg != null &&
21638                            pkg.applicationInfo.targetSdkVersion >=
21639                                    Build.VERSION_CODES.JELLY_BEAN) {
21640                        throw new IllegalArgumentException("Component class " + className
21641                                + " does not exist in " + packageName);
21642                    } else {
21643                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21644                                + className + " does not exist in " + packageName);
21645                    }
21646                }
21647                switch (newState) {
21648                case COMPONENT_ENABLED_STATE_ENABLED:
21649                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21650                        return;
21651                    }
21652                    break;
21653                case COMPONENT_ENABLED_STATE_DISABLED:
21654                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21655                        return;
21656                    }
21657                    break;
21658                case COMPONENT_ENABLED_STATE_DEFAULT:
21659                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21660                        return;
21661                    }
21662                    break;
21663                default:
21664                    Slog.e(TAG, "Invalid new component state: " + newState);
21665                    return;
21666                }
21667            }
21668            scheduleWritePackageRestrictionsLocked(userId);
21669            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21670            final long callingId = Binder.clearCallingIdentity();
21671            try {
21672                updateInstantAppInstallerLocked(packageName);
21673            } finally {
21674                Binder.restoreCallingIdentity(callingId);
21675            }
21676            components = mPendingBroadcasts.get(userId, packageName);
21677            final boolean newPackage = components == null;
21678            if (newPackage) {
21679                components = new ArrayList<String>();
21680            }
21681            if (!components.contains(componentName)) {
21682                components.add(componentName);
21683            }
21684            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21685                sendNow = true;
21686                // Purge entry from pending broadcast list if another one exists already
21687                // since we are sending one right away.
21688                mPendingBroadcasts.remove(userId, packageName);
21689            } else {
21690                if (newPackage) {
21691                    mPendingBroadcasts.put(userId, packageName, components);
21692                }
21693                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21694                    // Schedule a message
21695                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21696                }
21697            }
21698        }
21699
21700        long callingId = Binder.clearCallingIdentity();
21701        try {
21702            if (sendNow) {
21703                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21704                sendPackageChangedBroadcast(packageName,
21705                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21706            }
21707        } finally {
21708            Binder.restoreCallingIdentity(callingId);
21709        }
21710    }
21711
21712    @Override
21713    public void flushPackageRestrictionsAsUser(int userId) {
21714        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21715            return;
21716        }
21717        if (!sUserManager.exists(userId)) {
21718            return;
21719        }
21720        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21721                false /* checkShell */, "flushPackageRestrictions");
21722        synchronized (mPackages) {
21723            mSettings.writePackageRestrictionsLPr(userId);
21724            mDirtyUsers.remove(userId);
21725            if (mDirtyUsers.isEmpty()) {
21726                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21727            }
21728        }
21729    }
21730
21731    private void sendPackageChangedBroadcast(String packageName,
21732            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21733        if (DEBUG_INSTALL)
21734            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21735                    + componentNames);
21736        Bundle extras = new Bundle(4);
21737        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21738        String nameList[] = new String[componentNames.size()];
21739        componentNames.toArray(nameList);
21740        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21741        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21742        extras.putInt(Intent.EXTRA_UID, packageUid);
21743        // If this is not reporting a change of the overall package, then only send it
21744        // to registered receivers.  We don't want to launch a swath of apps for every
21745        // little component state change.
21746        final int flags = !componentNames.contains(packageName)
21747                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21748        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21749                new int[] {UserHandle.getUserId(packageUid)});
21750    }
21751
21752    @Override
21753    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21754        if (!sUserManager.exists(userId)) return;
21755        final int callingUid = Binder.getCallingUid();
21756        if (getInstantAppPackageName(callingUid) != null) {
21757            return;
21758        }
21759        final int permission = mContext.checkCallingOrSelfPermission(
21760                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21761        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21762        enforceCrossUserPermission(callingUid, userId,
21763                true /* requireFullPermission */, true /* checkShell */, "stop package");
21764        // writer
21765        synchronized (mPackages) {
21766            final PackageSetting ps = mSettings.mPackages.get(packageName);
21767            if (!filterAppAccessLPr(ps, callingUid, userId)
21768                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21769                            allowedByPermission, callingUid, userId)) {
21770                scheduleWritePackageRestrictionsLocked(userId);
21771            }
21772        }
21773    }
21774
21775    @Override
21776    public String getInstallerPackageName(String packageName) {
21777        final int callingUid = Binder.getCallingUid();
21778        if (getInstantAppPackageName(callingUid) != null) {
21779            return null;
21780        }
21781        // reader
21782        synchronized (mPackages) {
21783            final PackageSetting ps = mSettings.mPackages.get(packageName);
21784            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21785                return null;
21786            }
21787            return mSettings.getInstallerPackageNameLPr(packageName);
21788        }
21789    }
21790
21791    public boolean isOrphaned(String packageName) {
21792        // reader
21793        synchronized (mPackages) {
21794            return mSettings.isOrphaned(packageName);
21795        }
21796    }
21797
21798    @Override
21799    public int getApplicationEnabledSetting(String packageName, int userId) {
21800        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21801        int callingUid = Binder.getCallingUid();
21802        enforceCrossUserPermission(callingUid, userId,
21803                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21804        // reader
21805        synchronized (mPackages) {
21806            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21807                return COMPONENT_ENABLED_STATE_DISABLED;
21808            }
21809            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21810        }
21811    }
21812
21813    @Override
21814    public int getComponentEnabledSetting(ComponentName component, int userId) {
21815        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21816        int callingUid = Binder.getCallingUid();
21817        enforceCrossUserPermission(callingUid, userId,
21818                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21819        synchronized (mPackages) {
21820            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21821                    component, TYPE_UNKNOWN, userId)) {
21822                return COMPONENT_ENABLED_STATE_DISABLED;
21823            }
21824            return mSettings.getComponentEnabledSettingLPr(component, userId);
21825        }
21826    }
21827
21828    @Override
21829    public void enterSafeMode() {
21830        enforceSystemOrRoot("Only the system can request entering safe mode");
21831
21832        if (!mSystemReady) {
21833            mSafeMode = true;
21834        }
21835    }
21836
21837    @Override
21838    public void systemReady() {
21839        enforceSystemOrRoot("Only the system can claim the system is ready");
21840
21841        mSystemReady = true;
21842        final ContentResolver resolver = mContext.getContentResolver();
21843        ContentObserver co = new ContentObserver(mHandler) {
21844            @Override
21845            public void onChange(boolean selfChange) {
21846                mEphemeralAppsDisabled =
21847                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21848                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21849            }
21850        };
21851        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21852                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21853                false, co, UserHandle.USER_SYSTEM);
21854        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21855                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21856        co.onChange(true);
21857
21858        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21859        // disabled after already being started.
21860        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21861                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21862
21863        // Read the compatibilty setting when the system is ready.
21864        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21865                mContext.getContentResolver(),
21866                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21867        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21868        if (DEBUG_SETTINGS) {
21869            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21870        }
21871
21872        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21873
21874        synchronized (mPackages) {
21875            // Verify that all of the preferred activity components actually
21876            // exist.  It is possible for applications to be updated and at
21877            // that point remove a previously declared activity component that
21878            // had been set as a preferred activity.  We try to clean this up
21879            // the next time we encounter that preferred activity, but it is
21880            // possible for the user flow to never be able to return to that
21881            // situation so here we do a sanity check to make sure we haven't
21882            // left any junk around.
21883            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21884            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21885                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21886                removed.clear();
21887                for (PreferredActivity pa : pir.filterSet()) {
21888                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21889                        removed.add(pa);
21890                    }
21891                }
21892                if (removed.size() > 0) {
21893                    for (int r=0; r<removed.size(); r++) {
21894                        PreferredActivity pa = removed.get(r);
21895                        Slog.w(TAG, "Removing dangling preferred activity: "
21896                                + pa.mPref.mComponent);
21897                        pir.removeFilter(pa);
21898                    }
21899                    mSettings.writePackageRestrictionsLPr(
21900                            mSettings.mPreferredActivities.keyAt(i));
21901                }
21902            }
21903
21904            for (int userId : UserManagerService.getInstance().getUserIds()) {
21905                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21906                    grantPermissionsUserIds = ArrayUtils.appendInt(
21907                            grantPermissionsUserIds, userId);
21908                }
21909            }
21910        }
21911        sUserManager.systemReady();
21912
21913        // If we upgraded grant all default permissions before kicking off.
21914        for (int userId : grantPermissionsUserIds) {
21915            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21916        }
21917
21918        // If we did not grant default permissions, we preload from this the
21919        // default permission exceptions lazily to ensure we don't hit the
21920        // disk on a new user creation.
21921        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21922            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21923        }
21924
21925        // Kick off any messages waiting for system ready
21926        if (mPostSystemReadyMessages != null) {
21927            for (Message msg : mPostSystemReadyMessages) {
21928                msg.sendToTarget();
21929            }
21930            mPostSystemReadyMessages = null;
21931        }
21932
21933        // Watch for external volumes that come and go over time
21934        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21935        storage.registerListener(mStorageListener);
21936
21937        mInstallerService.systemReady();
21938        mPackageDexOptimizer.systemReady();
21939
21940        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21941                StorageManagerInternal.class);
21942        StorageManagerInternal.addExternalStoragePolicy(
21943                new StorageManagerInternal.ExternalStorageMountPolicy() {
21944            @Override
21945            public int getMountMode(int uid, String packageName) {
21946                if (Process.isIsolated(uid)) {
21947                    return Zygote.MOUNT_EXTERNAL_NONE;
21948                }
21949                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21950                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21951                }
21952                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21953                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21954                }
21955                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21956                    return Zygote.MOUNT_EXTERNAL_READ;
21957                }
21958                return Zygote.MOUNT_EXTERNAL_WRITE;
21959            }
21960
21961            @Override
21962            public boolean hasExternalStorage(int uid, String packageName) {
21963                return true;
21964            }
21965        });
21966
21967        // Now that we're mostly running, clean up stale users and apps
21968        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21969        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21970
21971        if (mPrivappPermissionsViolations != null) {
21972            Slog.wtf(TAG,"Signature|privileged permissions not in "
21973                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21974            mPrivappPermissionsViolations = null;
21975        }
21976    }
21977
21978    public void waitForAppDataPrepared() {
21979        if (mPrepareAppDataFuture == null) {
21980            return;
21981        }
21982        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21983        mPrepareAppDataFuture = null;
21984    }
21985
21986    @Override
21987    public boolean isSafeMode() {
21988        // allow instant applications
21989        return mSafeMode;
21990    }
21991
21992    @Override
21993    public boolean hasSystemUidErrors() {
21994        // allow instant applications
21995        return mHasSystemUidErrors;
21996    }
21997
21998    static String arrayToString(int[] array) {
21999        StringBuffer buf = new StringBuffer(128);
22000        buf.append('[');
22001        if (array != null) {
22002            for (int i=0; i<array.length; i++) {
22003                if (i > 0) buf.append(", ");
22004                buf.append(array[i]);
22005            }
22006        }
22007        buf.append(']');
22008        return buf.toString();
22009    }
22010
22011    static class DumpState {
22012        public static final int DUMP_LIBS = 1 << 0;
22013        public static final int DUMP_FEATURES = 1 << 1;
22014        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22015        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22016        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22017        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22018        public static final int DUMP_PERMISSIONS = 1 << 6;
22019        public static final int DUMP_PACKAGES = 1 << 7;
22020        public static final int DUMP_SHARED_USERS = 1 << 8;
22021        public static final int DUMP_MESSAGES = 1 << 9;
22022        public static final int DUMP_PROVIDERS = 1 << 10;
22023        public static final int DUMP_VERIFIERS = 1 << 11;
22024        public static final int DUMP_PREFERRED = 1 << 12;
22025        public static final int DUMP_PREFERRED_XML = 1 << 13;
22026        public static final int DUMP_KEYSETS = 1 << 14;
22027        public static final int DUMP_VERSION = 1 << 15;
22028        public static final int DUMP_INSTALLS = 1 << 16;
22029        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22030        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22031        public static final int DUMP_FROZEN = 1 << 19;
22032        public static final int DUMP_DEXOPT = 1 << 20;
22033        public static final int DUMP_COMPILER_STATS = 1 << 21;
22034        public static final int DUMP_CHANGES = 1 << 22;
22035        public static final int DUMP_VOLUMES = 1 << 23;
22036
22037        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22038
22039        private int mTypes;
22040
22041        private int mOptions;
22042
22043        private boolean mTitlePrinted;
22044
22045        private SharedUserSetting mSharedUser;
22046
22047        public boolean isDumping(int type) {
22048            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22049                return true;
22050            }
22051
22052            return (mTypes & type) != 0;
22053        }
22054
22055        public void setDump(int type) {
22056            mTypes |= type;
22057        }
22058
22059        public boolean isOptionEnabled(int option) {
22060            return (mOptions & option) != 0;
22061        }
22062
22063        public void setOptionEnabled(int option) {
22064            mOptions |= option;
22065        }
22066
22067        public boolean onTitlePrinted() {
22068            final boolean printed = mTitlePrinted;
22069            mTitlePrinted = true;
22070            return printed;
22071        }
22072
22073        public boolean getTitlePrinted() {
22074            return mTitlePrinted;
22075        }
22076
22077        public void setTitlePrinted(boolean enabled) {
22078            mTitlePrinted = enabled;
22079        }
22080
22081        public SharedUserSetting getSharedUser() {
22082            return mSharedUser;
22083        }
22084
22085        public void setSharedUser(SharedUserSetting user) {
22086            mSharedUser = user;
22087        }
22088    }
22089
22090    @Override
22091    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22092            FileDescriptor err, String[] args, ShellCallback callback,
22093            ResultReceiver resultReceiver) {
22094        (new PackageManagerShellCommand(this)).exec(
22095                this, in, out, err, args, callback, resultReceiver);
22096    }
22097
22098    @Override
22099    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22100        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22101
22102        DumpState dumpState = new DumpState();
22103        boolean fullPreferred = false;
22104        boolean checkin = false;
22105
22106        String packageName = null;
22107        ArraySet<String> permissionNames = null;
22108
22109        int opti = 0;
22110        while (opti < args.length) {
22111            String opt = args[opti];
22112            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22113                break;
22114            }
22115            opti++;
22116
22117            if ("-a".equals(opt)) {
22118                // Right now we only know how to print all.
22119            } else if ("-h".equals(opt)) {
22120                pw.println("Package manager dump options:");
22121                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22122                pw.println("    --checkin: dump for a checkin");
22123                pw.println("    -f: print details of intent filters");
22124                pw.println("    -h: print this help");
22125                pw.println("  cmd may be one of:");
22126                pw.println("    l[ibraries]: list known shared libraries");
22127                pw.println("    f[eatures]: list device features");
22128                pw.println("    k[eysets]: print known keysets");
22129                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22130                pw.println("    perm[issions]: dump permissions");
22131                pw.println("    permission [name ...]: dump declaration and use of given permission");
22132                pw.println("    pref[erred]: print preferred package settings");
22133                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22134                pw.println("    prov[iders]: dump content providers");
22135                pw.println("    p[ackages]: dump installed packages");
22136                pw.println("    s[hared-users]: dump shared user IDs");
22137                pw.println("    m[essages]: print collected runtime messages");
22138                pw.println("    v[erifiers]: print package verifier info");
22139                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22140                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22141                pw.println("    version: print database version info");
22142                pw.println("    write: write current settings now");
22143                pw.println("    installs: details about install sessions");
22144                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22145                pw.println("    dexopt: dump dexopt state");
22146                pw.println("    compiler-stats: dump compiler statistics");
22147                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22148                pw.println("    <package.name>: info about given package");
22149                return;
22150            } else if ("--checkin".equals(opt)) {
22151                checkin = true;
22152            } else if ("-f".equals(opt)) {
22153                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22154            } else if ("--proto".equals(opt)) {
22155                dumpProto(fd);
22156                return;
22157            } else {
22158                pw.println("Unknown argument: " + opt + "; use -h for help");
22159            }
22160        }
22161
22162        // Is the caller requesting to dump a particular piece of data?
22163        if (opti < args.length) {
22164            String cmd = args[opti];
22165            opti++;
22166            // Is this a package name?
22167            if ("android".equals(cmd) || cmd.contains(".")) {
22168                packageName = cmd;
22169                // When dumping a single package, we always dump all of its
22170                // filter information since the amount of data will be reasonable.
22171                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22172            } else if ("check-permission".equals(cmd)) {
22173                if (opti >= args.length) {
22174                    pw.println("Error: check-permission missing permission argument");
22175                    return;
22176                }
22177                String perm = args[opti];
22178                opti++;
22179                if (opti >= args.length) {
22180                    pw.println("Error: check-permission missing package argument");
22181                    return;
22182                }
22183
22184                String pkg = args[opti];
22185                opti++;
22186                int user = UserHandle.getUserId(Binder.getCallingUid());
22187                if (opti < args.length) {
22188                    try {
22189                        user = Integer.parseInt(args[opti]);
22190                    } catch (NumberFormatException e) {
22191                        pw.println("Error: check-permission user argument is not a number: "
22192                                + args[opti]);
22193                        return;
22194                    }
22195                }
22196
22197                // Normalize package name to handle renamed packages and static libs
22198                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22199
22200                pw.println(checkPermission(perm, pkg, user));
22201                return;
22202            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22203                dumpState.setDump(DumpState.DUMP_LIBS);
22204            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22205                dumpState.setDump(DumpState.DUMP_FEATURES);
22206            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22207                if (opti >= args.length) {
22208                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22209                            | DumpState.DUMP_SERVICE_RESOLVERS
22210                            | DumpState.DUMP_RECEIVER_RESOLVERS
22211                            | DumpState.DUMP_CONTENT_RESOLVERS);
22212                } else {
22213                    while (opti < args.length) {
22214                        String name = args[opti];
22215                        if ("a".equals(name) || "activity".equals(name)) {
22216                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22217                        } else if ("s".equals(name) || "service".equals(name)) {
22218                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22219                        } else if ("r".equals(name) || "receiver".equals(name)) {
22220                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22221                        } else if ("c".equals(name) || "content".equals(name)) {
22222                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22223                        } else {
22224                            pw.println("Error: unknown resolver table type: " + name);
22225                            return;
22226                        }
22227                        opti++;
22228                    }
22229                }
22230            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22231                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22232            } else if ("permission".equals(cmd)) {
22233                if (opti >= args.length) {
22234                    pw.println("Error: permission requires permission name");
22235                    return;
22236                }
22237                permissionNames = new ArraySet<>();
22238                while (opti < args.length) {
22239                    permissionNames.add(args[opti]);
22240                    opti++;
22241                }
22242                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22243                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22244            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22245                dumpState.setDump(DumpState.DUMP_PREFERRED);
22246            } else if ("preferred-xml".equals(cmd)) {
22247                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22248                if (opti < args.length && "--full".equals(args[opti])) {
22249                    fullPreferred = true;
22250                    opti++;
22251                }
22252            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22253                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22254            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22255                dumpState.setDump(DumpState.DUMP_PACKAGES);
22256            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22257                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22258            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22259                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22260            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22261                dumpState.setDump(DumpState.DUMP_MESSAGES);
22262            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22263                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22264            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22265                    || "intent-filter-verifiers".equals(cmd)) {
22266                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22267            } else if ("version".equals(cmd)) {
22268                dumpState.setDump(DumpState.DUMP_VERSION);
22269            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22270                dumpState.setDump(DumpState.DUMP_KEYSETS);
22271            } else if ("installs".equals(cmd)) {
22272                dumpState.setDump(DumpState.DUMP_INSTALLS);
22273            } else if ("frozen".equals(cmd)) {
22274                dumpState.setDump(DumpState.DUMP_FROZEN);
22275            } else if ("volumes".equals(cmd)) {
22276                dumpState.setDump(DumpState.DUMP_VOLUMES);
22277            } else if ("dexopt".equals(cmd)) {
22278                dumpState.setDump(DumpState.DUMP_DEXOPT);
22279            } else if ("compiler-stats".equals(cmd)) {
22280                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22281            } else if ("changes".equals(cmd)) {
22282                dumpState.setDump(DumpState.DUMP_CHANGES);
22283            } else if ("write".equals(cmd)) {
22284                synchronized (mPackages) {
22285                    mSettings.writeLPr();
22286                    pw.println("Settings written.");
22287                    return;
22288                }
22289            }
22290        }
22291
22292        if (checkin) {
22293            pw.println("vers,1");
22294        }
22295
22296        // reader
22297        synchronized (mPackages) {
22298            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22299                if (!checkin) {
22300                    if (dumpState.onTitlePrinted())
22301                        pw.println();
22302                    pw.println("Database versions:");
22303                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22304                }
22305            }
22306
22307            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22308                if (!checkin) {
22309                    if (dumpState.onTitlePrinted())
22310                        pw.println();
22311                    pw.println("Verifiers:");
22312                    pw.print("  Required: ");
22313                    pw.print(mRequiredVerifierPackage);
22314                    pw.print(" (uid=");
22315                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22316                            UserHandle.USER_SYSTEM));
22317                    pw.println(")");
22318                } else if (mRequiredVerifierPackage != null) {
22319                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22320                    pw.print(",");
22321                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22322                            UserHandle.USER_SYSTEM));
22323                }
22324            }
22325
22326            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22327                    packageName == null) {
22328                if (mIntentFilterVerifierComponent != null) {
22329                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22330                    if (!checkin) {
22331                        if (dumpState.onTitlePrinted())
22332                            pw.println();
22333                        pw.println("Intent Filter Verifier:");
22334                        pw.print("  Using: ");
22335                        pw.print(verifierPackageName);
22336                        pw.print(" (uid=");
22337                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22338                                UserHandle.USER_SYSTEM));
22339                        pw.println(")");
22340                    } else if (verifierPackageName != null) {
22341                        pw.print("ifv,"); pw.print(verifierPackageName);
22342                        pw.print(",");
22343                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22344                                UserHandle.USER_SYSTEM));
22345                    }
22346                } else {
22347                    pw.println();
22348                    pw.println("No Intent Filter Verifier available!");
22349                }
22350            }
22351
22352            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22353                boolean printedHeader = false;
22354                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22355                while (it.hasNext()) {
22356                    String libName = it.next();
22357                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22358                    if (versionedLib == null) {
22359                        continue;
22360                    }
22361                    final int versionCount = versionedLib.size();
22362                    for (int i = 0; i < versionCount; i++) {
22363                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22364                        if (!checkin) {
22365                            if (!printedHeader) {
22366                                if (dumpState.onTitlePrinted())
22367                                    pw.println();
22368                                pw.println("Libraries:");
22369                                printedHeader = true;
22370                            }
22371                            pw.print("  ");
22372                        } else {
22373                            pw.print("lib,");
22374                        }
22375                        pw.print(libEntry.info.getName());
22376                        if (libEntry.info.isStatic()) {
22377                            pw.print(" version=" + libEntry.info.getVersion());
22378                        }
22379                        if (!checkin) {
22380                            pw.print(" -> ");
22381                        }
22382                        if (libEntry.path != null) {
22383                            pw.print(" (jar) ");
22384                            pw.print(libEntry.path);
22385                        } else {
22386                            pw.print(" (apk) ");
22387                            pw.print(libEntry.apk);
22388                        }
22389                        pw.println();
22390                    }
22391                }
22392            }
22393
22394            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22395                if (dumpState.onTitlePrinted())
22396                    pw.println();
22397                if (!checkin) {
22398                    pw.println("Features:");
22399                }
22400
22401                synchronized (mAvailableFeatures) {
22402                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22403                        if (checkin) {
22404                            pw.print("feat,");
22405                            pw.print(feat.name);
22406                            pw.print(",");
22407                            pw.println(feat.version);
22408                        } else {
22409                            pw.print("  ");
22410                            pw.print(feat.name);
22411                            if (feat.version > 0) {
22412                                pw.print(" version=");
22413                                pw.print(feat.version);
22414                            }
22415                            pw.println();
22416                        }
22417                    }
22418                }
22419            }
22420
22421            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22422                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22423                        : "Activity Resolver Table:", "  ", packageName,
22424                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22425                    dumpState.setTitlePrinted(true);
22426                }
22427            }
22428            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22429                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22430                        : "Receiver Resolver Table:", "  ", packageName,
22431                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22432                    dumpState.setTitlePrinted(true);
22433                }
22434            }
22435            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22436                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22437                        : "Service Resolver Table:", "  ", packageName,
22438                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22439                    dumpState.setTitlePrinted(true);
22440                }
22441            }
22442            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22443                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22444                        : "Provider Resolver Table:", "  ", packageName,
22445                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22446                    dumpState.setTitlePrinted(true);
22447                }
22448            }
22449
22450            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22451                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22452                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22453                    int user = mSettings.mPreferredActivities.keyAt(i);
22454                    if (pir.dump(pw,
22455                            dumpState.getTitlePrinted()
22456                                ? "\nPreferred Activities User " + user + ":"
22457                                : "Preferred Activities User " + user + ":", "  ",
22458                            packageName, true, false)) {
22459                        dumpState.setTitlePrinted(true);
22460                    }
22461                }
22462            }
22463
22464            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22465                pw.flush();
22466                FileOutputStream fout = new FileOutputStream(fd);
22467                BufferedOutputStream str = new BufferedOutputStream(fout);
22468                XmlSerializer serializer = new FastXmlSerializer();
22469                try {
22470                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22471                    serializer.startDocument(null, true);
22472                    serializer.setFeature(
22473                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22474                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22475                    serializer.endDocument();
22476                    serializer.flush();
22477                } catch (IllegalArgumentException e) {
22478                    pw.println("Failed writing: " + e);
22479                } catch (IllegalStateException e) {
22480                    pw.println("Failed writing: " + e);
22481                } catch (IOException e) {
22482                    pw.println("Failed writing: " + e);
22483                }
22484            }
22485
22486            if (!checkin
22487                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22488                    && packageName == null) {
22489                pw.println();
22490                int count = mSettings.mPackages.size();
22491                if (count == 0) {
22492                    pw.println("No applications!");
22493                    pw.println();
22494                } else {
22495                    final String prefix = "  ";
22496                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22497                    if (allPackageSettings.size() == 0) {
22498                        pw.println("No domain preferred apps!");
22499                        pw.println();
22500                    } else {
22501                        pw.println("App verification status:");
22502                        pw.println();
22503                        count = 0;
22504                        for (PackageSetting ps : allPackageSettings) {
22505                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22506                            if (ivi == null || ivi.getPackageName() == null) continue;
22507                            pw.println(prefix + "Package: " + ivi.getPackageName());
22508                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22509                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22510                            pw.println();
22511                            count++;
22512                        }
22513                        if (count == 0) {
22514                            pw.println(prefix + "No app verification established.");
22515                            pw.println();
22516                        }
22517                        for (int userId : sUserManager.getUserIds()) {
22518                            pw.println("App linkages for user " + userId + ":");
22519                            pw.println();
22520                            count = 0;
22521                            for (PackageSetting ps : allPackageSettings) {
22522                                final long status = ps.getDomainVerificationStatusForUser(userId);
22523                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22524                                        && !DEBUG_DOMAIN_VERIFICATION) {
22525                                    continue;
22526                                }
22527                                pw.println(prefix + "Package: " + ps.name);
22528                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22529                                String statusStr = IntentFilterVerificationInfo.
22530                                        getStatusStringFromValue(status);
22531                                pw.println(prefix + "Status:  " + statusStr);
22532                                pw.println();
22533                                count++;
22534                            }
22535                            if (count == 0) {
22536                                pw.println(prefix + "No configured app linkages.");
22537                                pw.println();
22538                            }
22539                        }
22540                    }
22541                }
22542            }
22543
22544            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22545                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22546                if (packageName == null && permissionNames == null) {
22547                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22548                        if (iperm == 0) {
22549                            if (dumpState.onTitlePrinted())
22550                                pw.println();
22551                            pw.println("AppOp Permissions:");
22552                        }
22553                        pw.print("  AppOp Permission ");
22554                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22555                        pw.println(":");
22556                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22557                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22558                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22559                        }
22560                    }
22561                }
22562            }
22563
22564            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22565                boolean printedSomething = false;
22566                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22567                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22568                        continue;
22569                    }
22570                    if (!printedSomething) {
22571                        if (dumpState.onTitlePrinted())
22572                            pw.println();
22573                        pw.println("Registered ContentProviders:");
22574                        printedSomething = true;
22575                    }
22576                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22577                    pw.print("    "); pw.println(p.toString());
22578                }
22579                printedSomething = false;
22580                for (Map.Entry<String, PackageParser.Provider> entry :
22581                        mProvidersByAuthority.entrySet()) {
22582                    PackageParser.Provider p = entry.getValue();
22583                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22584                        continue;
22585                    }
22586                    if (!printedSomething) {
22587                        if (dumpState.onTitlePrinted())
22588                            pw.println();
22589                        pw.println("ContentProvider Authorities:");
22590                        printedSomething = true;
22591                    }
22592                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22593                    pw.print("    "); pw.println(p.toString());
22594                    if (p.info != null && p.info.applicationInfo != null) {
22595                        final String appInfo = p.info.applicationInfo.toString();
22596                        pw.print("      applicationInfo="); pw.println(appInfo);
22597                    }
22598                }
22599            }
22600
22601            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22602                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22603            }
22604
22605            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22606                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22607            }
22608
22609            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22610                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22611            }
22612
22613            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22614                if (dumpState.onTitlePrinted()) pw.println();
22615                pw.println("Package Changes:");
22616                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22617                final int K = mChangedPackages.size();
22618                for (int i = 0; i < K; i++) {
22619                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22620                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22621                    final int N = changes.size();
22622                    if (N == 0) {
22623                        pw.print("    "); pw.println("No packages changed");
22624                    } else {
22625                        for (int j = 0; j < N; j++) {
22626                            final String pkgName = changes.valueAt(j);
22627                            final int sequenceNumber = changes.keyAt(j);
22628                            pw.print("    ");
22629                            pw.print("seq=");
22630                            pw.print(sequenceNumber);
22631                            pw.print(", package=");
22632                            pw.println(pkgName);
22633                        }
22634                    }
22635                }
22636            }
22637
22638            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22639                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22640            }
22641
22642            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22643                // XXX should handle packageName != null by dumping only install data that
22644                // the given package is involved with.
22645                if (dumpState.onTitlePrinted()) pw.println();
22646
22647                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22648                ipw.println();
22649                ipw.println("Frozen packages:");
22650                ipw.increaseIndent();
22651                if (mFrozenPackages.size() == 0) {
22652                    ipw.println("(none)");
22653                } else {
22654                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22655                        ipw.println(mFrozenPackages.valueAt(i));
22656                    }
22657                }
22658                ipw.decreaseIndent();
22659            }
22660
22661            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22662                if (dumpState.onTitlePrinted()) pw.println();
22663
22664                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22665                ipw.println();
22666                ipw.println("Loaded volumes:");
22667                ipw.increaseIndent();
22668                if (mLoadedVolumes.size() == 0) {
22669                    ipw.println("(none)");
22670                } else {
22671                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22672                        ipw.println(mLoadedVolumes.valueAt(i));
22673                    }
22674                }
22675                ipw.decreaseIndent();
22676            }
22677
22678            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22679                if (dumpState.onTitlePrinted()) pw.println();
22680                dumpDexoptStateLPr(pw, packageName);
22681            }
22682
22683            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22684                if (dumpState.onTitlePrinted()) pw.println();
22685                dumpCompilerStatsLPr(pw, packageName);
22686            }
22687
22688            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22689                if (dumpState.onTitlePrinted()) pw.println();
22690                mSettings.dumpReadMessagesLPr(pw, dumpState);
22691
22692                pw.println();
22693                pw.println("Package warning messages:");
22694                BufferedReader in = null;
22695                String line = null;
22696                try {
22697                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22698                    while ((line = in.readLine()) != null) {
22699                        if (line.contains("ignored: updated version")) continue;
22700                        pw.println(line);
22701                    }
22702                } catch (IOException ignored) {
22703                } finally {
22704                    IoUtils.closeQuietly(in);
22705                }
22706            }
22707
22708            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22709                BufferedReader in = null;
22710                String line = null;
22711                try {
22712                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22713                    while ((line = in.readLine()) != null) {
22714                        if (line.contains("ignored: updated version")) continue;
22715                        pw.print("msg,");
22716                        pw.println(line);
22717                    }
22718                } catch (IOException ignored) {
22719                } finally {
22720                    IoUtils.closeQuietly(in);
22721                }
22722            }
22723        }
22724
22725        // PackageInstaller should be called outside of mPackages lock
22726        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22727            // XXX should handle packageName != null by dumping only install data that
22728            // the given package is involved with.
22729            if (dumpState.onTitlePrinted()) pw.println();
22730            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22731        }
22732    }
22733
22734    private void dumpProto(FileDescriptor fd) {
22735        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22736
22737        synchronized (mPackages) {
22738            final long requiredVerifierPackageToken =
22739                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22740            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22741            proto.write(
22742                    PackageServiceDumpProto.PackageShortProto.UID,
22743                    getPackageUid(
22744                            mRequiredVerifierPackage,
22745                            MATCH_DEBUG_TRIAGED_MISSING,
22746                            UserHandle.USER_SYSTEM));
22747            proto.end(requiredVerifierPackageToken);
22748
22749            if (mIntentFilterVerifierComponent != null) {
22750                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22751                final long verifierPackageToken =
22752                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22753                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22754                proto.write(
22755                        PackageServiceDumpProto.PackageShortProto.UID,
22756                        getPackageUid(
22757                                verifierPackageName,
22758                                MATCH_DEBUG_TRIAGED_MISSING,
22759                                UserHandle.USER_SYSTEM));
22760                proto.end(verifierPackageToken);
22761            }
22762
22763            dumpSharedLibrariesProto(proto);
22764            dumpFeaturesProto(proto);
22765            mSettings.dumpPackagesProto(proto);
22766            mSettings.dumpSharedUsersProto(proto);
22767            dumpMessagesProto(proto);
22768        }
22769        proto.flush();
22770    }
22771
22772    private void dumpMessagesProto(ProtoOutputStream proto) {
22773        BufferedReader in = null;
22774        String line = null;
22775        try {
22776            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22777            while ((line = in.readLine()) != null) {
22778                if (line.contains("ignored: updated version")) continue;
22779                proto.write(PackageServiceDumpProto.MESSAGES, line);
22780            }
22781        } catch (IOException ignored) {
22782        } finally {
22783            IoUtils.closeQuietly(in);
22784        }
22785    }
22786
22787    private void dumpFeaturesProto(ProtoOutputStream proto) {
22788        synchronized (mAvailableFeatures) {
22789            final int count = mAvailableFeatures.size();
22790            for (int i = 0; i < count; i++) {
22791                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22792                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22793                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22794                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22795                proto.end(featureToken);
22796            }
22797        }
22798    }
22799
22800    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22801        final int count = mSharedLibraries.size();
22802        for (int i = 0; i < count; i++) {
22803            final String libName = mSharedLibraries.keyAt(i);
22804            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22805            if (versionedLib == null) {
22806                continue;
22807            }
22808            final int versionCount = versionedLib.size();
22809            for (int j = 0; j < versionCount; j++) {
22810                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22811                final long sharedLibraryToken =
22812                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22813                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22814                final boolean isJar = (libEntry.path != null);
22815                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22816                if (isJar) {
22817                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22818                } else {
22819                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22820                }
22821                proto.end(sharedLibraryToken);
22822            }
22823        }
22824    }
22825
22826    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22827        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22828        ipw.println();
22829        ipw.println("Dexopt state:");
22830        ipw.increaseIndent();
22831        Collection<PackageParser.Package> packages = null;
22832        if (packageName != null) {
22833            PackageParser.Package targetPackage = mPackages.get(packageName);
22834            if (targetPackage != null) {
22835                packages = Collections.singletonList(targetPackage);
22836            } else {
22837                ipw.println("Unable to find package: " + packageName);
22838                return;
22839            }
22840        } else {
22841            packages = mPackages.values();
22842        }
22843
22844        for (PackageParser.Package pkg : packages) {
22845            ipw.println("[" + pkg.packageName + "]");
22846            ipw.increaseIndent();
22847            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22848            ipw.decreaseIndent();
22849        }
22850    }
22851
22852    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22853        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22854        ipw.println();
22855        ipw.println("Compiler stats:");
22856        ipw.increaseIndent();
22857        Collection<PackageParser.Package> packages = null;
22858        if (packageName != null) {
22859            PackageParser.Package targetPackage = mPackages.get(packageName);
22860            if (targetPackage != null) {
22861                packages = Collections.singletonList(targetPackage);
22862            } else {
22863                ipw.println("Unable to find package: " + packageName);
22864                return;
22865            }
22866        } else {
22867            packages = mPackages.values();
22868        }
22869
22870        for (PackageParser.Package pkg : packages) {
22871            ipw.println("[" + pkg.packageName + "]");
22872            ipw.increaseIndent();
22873
22874            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22875            if (stats == null) {
22876                ipw.println("(No recorded stats)");
22877            } else {
22878                stats.dump(ipw);
22879            }
22880            ipw.decreaseIndent();
22881        }
22882    }
22883
22884    private String dumpDomainString(String packageName) {
22885        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22886                .getList();
22887        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22888
22889        ArraySet<String> result = new ArraySet<>();
22890        if (iviList.size() > 0) {
22891            for (IntentFilterVerificationInfo ivi : iviList) {
22892                for (String host : ivi.getDomains()) {
22893                    result.add(host);
22894                }
22895            }
22896        }
22897        if (filters != null && filters.size() > 0) {
22898            for (IntentFilter filter : filters) {
22899                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22900                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22901                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22902                    result.addAll(filter.getHostsList());
22903                }
22904            }
22905        }
22906
22907        StringBuilder sb = new StringBuilder(result.size() * 16);
22908        for (String domain : result) {
22909            if (sb.length() > 0) sb.append(" ");
22910            sb.append(domain);
22911        }
22912        return sb.toString();
22913    }
22914
22915    // ------- apps on sdcard specific code -------
22916    static final boolean DEBUG_SD_INSTALL = false;
22917
22918    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22919
22920    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22921
22922    private boolean mMediaMounted = false;
22923
22924    static String getEncryptKey() {
22925        try {
22926            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22927                    SD_ENCRYPTION_KEYSTORE_NAME);
22928            if (sdEncKey == null) {
22929                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22930                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22931                if (sdEncKey == null) {
22932                    Slog.e(TAG, "Failed to create encryption keys");
22933                    return null;
22934                }
22935            }
22936            return sdEncKey;
22937        } catch (NoSuchAlgorithmException nsae) {
22938            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22939            return null;
22940        } catch (IOException ioe) {
22941            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22942            return null;
22943        }
22944    }
22945
22946    /*
22947     * Update media status on PackageManager.
22948     */
22949    @Override
22950    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22951        enforceSystemOrRoot("Media status can only be updated by the system");
22952        // reader; this apparently protects mMediaMounted, but should probably
22953        // be a different lock in that case.
22954        synchronized (mPackages) {
22955            Log.i(TAG, "Updating external media status from "
22956                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22957                    + (mediaStatus ? "mounted" : "unmounted"));
22958            if (DEBUG_SD_INSTALL)
22959                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22960                        + ", mMediaMounted=" + mMediaMounted);
22961            if (mediaStatus == mMediaMounted) {
22962                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22963                        : 0, -1);
22964                mHandler.sendMessage(msg);
22965                return;
22966            }
22967            mMediaMounted = mediaStatus;
22968        }
22969        // Queue up an async operation since the package installation may take a
22970        // little while.
22971        mHandler.post(new Runnable() {
22972            public void run() {
22973                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22974            }
22975        });
22976    }
22977
22978    /**
22979     * Called by StorageManagerService when the initial ASECs to scan are available.
22980     * Should block until all the ASEC containers are finished being scanned.
22981     */
22982    public void scanAvailableAsecs() {
22983        updateExternalMediaStatusInner(true, false, false);
22984    }
22985
22986    /*
22987     * Collect information of applications on external media, map them against
22988     * existing containers and update information based on current mount status.
22989     * Please note that we always have to report status if reportStatus has been
22990     * set to true especially when unloading packages.
22991     */
22992    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22993            boolean externalStorage) {
22994        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22995        int[] uidArr = EmptyArray.INT;
22996
22997        final String[] list = PackageHelper.getSecureContainerList();
22998        if (ArrayUtils.isEmpty(list)) {
22999            Log.i(TAG, "No secure containers found");
23000        } else {
23001            // Process list of secure containers and categorize them
23002            // as active or stale based on their package internal state.
23003
23004            // reader
23005            synchronized (mPackages) {
23006                for (String cid : list) {
23007                    // Leave stages untouched for now; installer service owns them
23008                    if (PackageInstallerService.isStageName(cid)) continue;
23009
23010                    if (DEBUG_SD_INSTALL)
23011                        Log.i(TAG, "Processing container " + cid);
23012                    String pkgName = getAsecPackageName(cid);
23013                    if (pkgName == null) {
23014                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23015                        continue;
23016                    }
23017                    if (DEBUG_SD_INSTALL)
23018                        Log.i(TAG, "Looking for pkg : " + pkgName);
23019
23020                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23021                    if (ps == null) {
23022                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23023                        continue;
23024                    }
23025
23026                    /*
23027                     * Skip packages that are not external if we're unmounting
23028                     * external storage.
23029                     */
23030                    if (externalStorage && !isMounted && !isExternal(ps)) {
23031                        continue;
23032                    }
23033
23034                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23035                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23036                    // The package status is changed only if the code path
23037                    // matches between settings and the container id.
23038                    if (ps.codePathString != null
23039                            && ps.codePathString.startsWith(args.getCodePath())) {
23040                        if (DEBUG_SD_INSTALL) {
23041                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23042                                    + " at code path: " + ps.codePathString);
23043                        }
23044
23045                        // We do have a valid package installed on sdcard
23046                        processCids.put(args, ps.codePathString);
23047                        final int uid = ps.appId;
23048                        if (uid != -1) {
23049                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23050                        }
23051                    } else {
23052                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23053                                + ps.codePathString);
23054                    }
23055                }
23056            }
23057
23058            Arrays.sort(uidArr);
23059        }
23060
23061        // Process packages with valid entries.
23062        if (isMounted) {
23063            if (DEBUG_SD_INSTALL)
23064                Log.i(TAG, "Loading packages");
23065            loadMediaPackages(processCids, uidArr, externalStorage);
23066            startCleaningPackages();
23067            mInstallerService.onSecureContainersAvailable();
23068        } else {
23069            if (DEBUG_SD_INSTALL)
23070                Log.i(TAG, "Unloading packages");
23071            unloadMediaPackages(processCids, uidArr, reportStatus);
23072        }
23073    }
23074
23075    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23076            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23077        final int size = infos.size();
23078        final String[] packageNames = new String[size];
23079        final int[] packageUids = new int[size];
23080        for (int i = 0; i < size; i++) {
23081            final ApplicationInfo info = infos.get(i);
23082            packageNames[i] = info.packageName;
23083            packageUids[i] = info.uid;
23084        }
23085        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23086                finishedReceiver);
23087    }
23088
23089    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23090            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23091        sendResourcesChangedBroadcast(mediaStatus, replacing,
23092                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23093    }
23094
23095    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23096            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23097        int size = pkgList.length;
23098        if (size > 0) {
23099            // Send broadcasts here
23100            Bundle extras = new Bundle();
23101            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23102            if (uidArr != null) {
23103                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23104            }
23105            if (replacing) {
23106                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23107            }
23108            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23109                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23110            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23111        }
23112    }
23113
23114   /*
23115     * Look at potentially valid container ids from processCids If package
23116     * information doesn't match the one on record or package scanning fails,
23117     * the cid is added to list of removeCids. We currently don't delete stale
23118     * containers.
23119     */
23120    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23121            boolean externalStorage) {
23122        ArrayList<String> pkgList = new ArrayList<String>();
23123        Set<AsecInstallArgs> keys = processCids.keySet();
23124
23125        for (AsecInstallArgs args : keys) {
23126            String codePath = processCids.get(args);
23127            if (DEBUG_SD_INSTALL)
23128                Log.i(TAG, "Loading container : " + args.cid);
23129            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23130            try {
23131                // Make sure there are no container errors first.
23132                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23133                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23134                            + " when installing from sdcard");
23135                    continue;
23136                }
23137                // Check code path here.
23138                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23139                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23140                            + " does not match one in settings " + codePath);
23141                    continue;
23142                }
23143                // Parse package
23144                int parseFlags = mDefParseFlags;
23145                if (args.isExternalAsec()) {
23146                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23147                }
23148                if (args.isFwdLocked()) {
23149                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23150                }
23151
23152                synchronized (mInstallLock) {
23153                    PackageParser.Package pkg = null;
23154                    try {
23155                        // Sadly we don't know the package name yet to freeze it
23156                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23157                                SCAN_IGNORE_FROZEN, 0, null);
23158                    } catch (PackageManagerException e) {
23159                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23160                    }
23161                    // Scan the package
23162                    if (pkg != null) {
23163                        /*
23164                         * TODO why is the lock being held? doPostInstall is
23165                         * called in other places without the lock. This needs
23166                         * to be straightened out.
23167                         */
23168                        // writer
23169                        synchronized (mPackages) {
23170                            retCode = PackageManager.INSTALL_SUCCEEDED;
23171                            pkgList.add(pkg.packageName);
23172                            // Post process args
23173                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23174                                    pkg.applicationInfo.uid);
23175                        }
23176                    } else {
23177                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23178                    }
23179                }
23180
23181            } finally {
23182                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23183                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23184                }
23185            }
23186        }
23187        // writer
23188        synchronized (mPackages) {
23189            // If the platform SDK has changed since the last time we booted,
23190            // we need to re-grant app permission to catch any new ones that
23191            // appear. This is really a hack, and means that apps can in some
23192            // cases get permissions that the user didn't initially explicitly
23193            // allow... it would be nice to have some better way to handle
23194            // this situation.
23195            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23196                    : mSettings.getInternalVersion();
23197            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23198                    : StorageManager.UUID_PRIVATE_INTERNAL;
23199
23200            int updateFlags = UPDATE_PERMISSIONS_ALL;
23201            if (ver.sdkVersion != mSdkVersion) {
23202                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23203                        + mSdkVersion + "; regranting permissions for external");
23204                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23205            }
23206            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23207
23208            // Yay, everything is now upgraded
23209            ver.forceCurrent();
23210
23211            // can downgrade to reader
23212            // Persist settings
23213            mSettings.writeLPr();
23214        }
23215        // Send a broadcast to let everyone know we are done processing
23216        if (pkgList.size() > 0) {
23217            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23218        }
23219    }
23220
23221   /*
23222     * Utility method to unload a list of specified containers
23223     */
23224    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23225        // Just unmount all valid containers.
23226        for (AsecInstallArgs arg : cidArgs) {
23227            synchronized (mInstallLock) {
23228                arg.doPostDeleteLI(false);
23229           }
23230       }
23231   }
23232
23233    /*
23234     * Unload packages mounted on external media. This involves deleting package
23235     * data from internal structures, sending broadcasts about disabled packages,
23236     * gc'ing to free up references, unmounting all secure containers
23237     * corresponding to packages on external media, and posting a
23238     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23239     * that we always have to post this message if status has been requested no
23240     * matter what.
23241     */
23242    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23243            final boolean reportStatus) {
23244        if (DEBUG_SD_INSTALL)
23245            Log.i(TAG, "unloading media packages");
23246        ArrayList<String> pkgList = new ArrayList<String>();
23247        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23248        final Set<AsecInstallArgs> keys = processCids.keySet();
23249        for (AsecInstallArgs args : keys) {
23250            String pkgName = args.getPackageName();
23251            if (DEBUG_SD_INSTALL)
23252                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23253            // Delete package internally
23254            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23255            synchronized (mInstallLock) {
23256                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23257                final boolean res;
23258                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23259                        "unloadMediaPackages")) {
23260                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23261                            null);
23262                }
23263                if (res) {
23264                    pkgList.add(pkgName);
23265                } else {
23266                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23267                    failedList.add(args);
23268                }
23269            }
23270        }
23271
23272        // reader
23273        synchronized (mPackages) {
23274            // We didn't update the settings after removing each package;
23275            // write them now for all packages.
23276            mSettings.writeLPr();
23277        }
23278
23279        // We have to absolutely send UPDATED_MEDIA_STATUS only
23280        // after confirming that all the receivers processed the ordered
23281        // broadcast when packages get disabled, force a gc to clean things up.
23282        // and unload all the containers.
23283        if (pkgList.size() > 0) {
23284            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23285                    new IIntentReceiver.Stub() {
23286                public void performReceive(Intent intent, int resultCode, String data,
23287                        Bundle extras, boolean ordered, boolean sticky,
23288                        int sendingUser) throws RemoteException {
23289                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23290                            reportStatus ? 1 : 0, 1, keys);
23291                    mHandler.sendMessage(msg);
23292                }
23293            });
23294        } else {
23295            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23296                    keys);
23297            mHandler.sendMessage(msg);
23298        }
23299    }
23300
23301    private void loadPrivatePackages(final VolumeInfo vol) {
23302        mHandler.post(new Runnable() {
23303            @Override
23304            public void run() {
23305                loadPrivatePackagesInner(vol);
23306            }
23307        });
23308    }
23309
23310    private void loadPrivatePackagesInner(VolumeInfo vol) {
23311        final String volumeUuid = vol.fsUuid;
23312        if (TextUtils.isEmpty(volumeUuid)) {
23313            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23314            return;
23315        }
23316
23317        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23318        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23319        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23320
23321        final VersionInfo ver;
23322        final List<PackageSetting> packages;
23323        synchronized (mPackages) {
23324            ver = mSettings.findOrCreateVersion(volumeUuid);
23325            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23326        }
23327
23328        for (PackageSetting ps : packages) {
23329            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23330            synchronized (mInstallLock) {
23331                final PackageParser.Package pkg;
23332                try {
23333                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23334                    loaded.add(pkg.applicationInfo);
23335
23336                } catch (PackageManagerException e) {
23337                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23338                }
23339
23340                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23341                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23342                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23343                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23344                }
23345            }
23346        }
23347
23348        // Reconcile app data for all started/unlocked users
23349        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23350        final UserManager um = mContext.getSystemService(UserManager.class);
23351        UserManagerInternal umInternal = getUserManagerInternal();
23352        for (UserInfo user : um.getUsers()) {
23353            final int flags;
23354            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23355                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23356            } else if (umInternal.isUserRunning(user.id)) {
23357                flags = StorageManager.FLAG_STORAGE_DE;
23358            } else {
23359                continue;
23360            }
23361
23362            try {
23363                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23364                synchronized (mInstallLock) {
23365                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23366                }
23367            } catch (IllegalStateException e) {
23368                // Device was probably ejected, and we'll process that event momentarily
23369                Slog.w(TAG, "Failed to prepare storage: " + e);
23370            }
23371        }
23372
23373        synchronized (mPackages) {
23374            int updateFlags = UPDATE_PERMISSIONS_ALL;
23375            if (ver.sdkVersion != mSdkVersion) {
23376                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23377                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23378                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23379            }
23380            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23381
23382            // Yay, everything is now upgraded
23383            ver.forceCurrent();
23384
23385            mSettings.writeLPr();
23386        }
23387
23388        for (PackageFreezer freezer : freezers) {
23389            freezer.close();
23390        }
23391
23392        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23393        sendResourcesChangedBroadcast(true, false, loaded, null);
23394        mLoadedVolumes.add(vol.getId());
23395    }
23396
23397    private void unloadPrivatePackages(final VolumeInfo vol) {
23398        mHandler.post(new Runnable() {
23399            @Override
23400            public void run() {
23401                unloadPrivatePackagesInner(vol);
23402            }
23403        });
23404    }
23405
23406    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23407        final String volumeUuid = vol.fsUuid;
23408        if (TextUtils.isEmpty(volumeUuid)) {
23409            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23410            return;
23411        }
23412
23413        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23414        synchronized (mInstallLock) {
23415        synchronized (mPackages) {
23416            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23417            for (PackageSetting ps : packages) {
23418                if (ps.pkg == null) continue;
23419
23420                final ApplicationInfo info = ps.pkg.applicationInfo;
23421                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23422                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23423
23424                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23425                        "unloadPrivatePackagesInner")) {
23426                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23427                            false, null)) {
23428                        unloaded.add(info);
23429                    } else {
23430                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23431                    }
23432                }
23433
23434                // Try very hard to release any references to this package
23435                // so we don't risk the system server being killed due to
23436                // open FDs
23437                AttributeCache.instance().removePackage(ps.name);
23438            }
23439
23440            mSettings.writeLPr();
23441        }
23442        }
23443
23444        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23445        sendResourcesChangedBroadcast(false, false, unloaded, null);
23446        mLoadedVolumes.remove(vol.getId());
23447
23448        // Try very hard to release any references to this path so we don't risk
23449        // the system server being killed due to open FDs
23450        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23451
23452        for (int i = 0; i < 3; i++) {
23453            System.gc();
23454            System.runFinalization();
23455        }
23456    }
23457
23458    private void assertPackageKnown(String volumeUuid, String packageName)
23459            throws PackageManagerException {
23460        synchronized (mPackages) {
23461            // Normalize package name to handle renamed packages
23462            packageName = normalizePackageNameLPr(packageName);
23463
23464            final PackageSetting ps = mSettings.mPackages.get(packageName);
23465            if (ps == null) {
23466                throw new PackageManagerException("Package " + packageName + " is unknown");
23467            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23468                throw new PackageManagerException(
23469                        "Package " + packageName + " found on unknown volume " + volumeUuid
23470                                + "; expected volume " + ps.volumeUuid);
23471            }
23472        }
23473    }
23474
23475    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23476            throws PackageManagerException {
23477        synchronized (mPackages) {
23478            // Normalize package name to handle renamed packages
23479            packageName = normalizePackageNameLPr(packageName);
23480
23481            final PackageSetting ps = mSettings.mPackages.get(packageName);
23482            if (ps == null) {
23483                throw new PackageManagerException("Package " + packageName + " is unknown");
23484            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23485                throw new PackageManagerException(
23486                        "Package " + packageName + " found on unknown volume " + volumeUuid
23487                                + "; expected volume " + ps.volumeUuid);
23488            } else if (!ps.getInstalled(userId)) {
23489                throw new PackageManagerException(
23490                        "Package " + packageName + " not installed for user " + userId);
23491            }
23492        }
23493    }
23494
23495    private List<String> collectAbsoluteCodePaths() {
23496        synchronized (mPackages) {
23497            List<String> codePaths = new ArrayList<>();
23498            final int packageCount = mSettings.mPackages.size();
23499            for (int i = 0; i < packageCount; i++) {
23500                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23501                codePaths.add(ps.codePath.getAbsolutePath());
23502            }
23503            return codePaths;
23504        }
23505    }
23506
23507    /**
23508     * Examine all apps present on given mounted volume, and destroy apps that
23509     * aren't expected, either due to uninstallation or reinstallation on
23510     * another volume.
23511     */
23512    private void reconcileApps(String volumeUuid) {
23513        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23514        List<File> filesToDelete = null;
23515
23516        final File[] files = FileUtils.listFilesOrEmpty(
23517                Environment.getDataAppDirectory(volumeUuid));
23518        for (File file : files) {
23519            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23520                    && !PackageInstallerService.isStageName(file.getName());
23521            if (!isPackage) {
23522                // Ignore entries which are not packages
23523                continue;
23524            }
23525
23526            String absolutePath = file.getAbsolutePath();
23527
23528            boolean pathValid = false;
23529            final int absoluteCodePathCount = absoluteCodePaths.size();
23530            for (int i = 0; i < absoluteCodePathCount; i++) {
23531                String absoluteCodePath = absoluteCodePaths.get(i);
23532                if (absolutePath.startsWith(absoluteCodePath)) {
23533                    pathValid = true;
23534                    break;
23535                }
23536            }
23537
23538            if (!pathValid) {
23539                if (filesToDelete == null) {
23540                    filesToDelete = new ArrayList<>();
23541                }
23542                filesToDelete.add(file);
23543            }
23544        }
23545
23546        if (filesToDelete != null) {
23547            final int fileToDeleteCount = filesToDelete.size();
23548            for (int i = 0; i < fileToDeleteCount; i++) {
23549                File fileToDelete = filesToDelete.get(i);
23550                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23551                synchronized (mInstallLock) {
23552                    removeCodePathLI(fileToDelete);
23553                }
23554            }
23555        }
23556    }
23557
23558    /**
23559     * Reconcile all app data for the given user.
23560     * <p>
23561     * Verifies that directories exist and that ownership and labeling is
23562     * correct for all installed apps on all mounted volumes.
23563     */
23564    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23565        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23566        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23567            final String volumeUuid = vol.getFsUuid();
23568            synchronized (mInstallLock) {
23569                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23570            }
23571        }
23572    }
23573
23574    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23575            boolean migrateAppData) {
23576        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23577    }
23578
23579    /**
23580     * Reconcile all app data on given mounted volume.
23581     * <p>
23582     * Destroys app data that isn't expected, either due to uninstallation or
23583     * reinstallation on another volume.
23584     * <p>
23585     * Verifies that directories exist and that ownership and labeling is
23586     * correct for all installed apps.
23587     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23588     */
23589    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23590            boolean migrateAppData, boolean onlyCoreApps) {
23591        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23592                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23593        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23594
23595        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23596        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23597
23598        // First look for stale data that doesn't belong, and check if things
23599        // have changed since we did our last restorecon
23600        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23601            if (StorageManager.isFileEncryptedNativeOrEmulated()
23602                    && !StorageManager.isUserKeyUnlocked(userId)) {
23603                throw new RuntimeException(
23604                        "Yikes, someone asked us to reconcile CE storage while " + userId
23605                                + " was still locked; this would have caused massive data loss!");
23606            }
23607
23608            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23609            for (File file : files) {
23610                final String packageName = file.getName();
23611                try {
23612                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23613                } catch (PackageManagerException e) {
23614                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23615                    try {
23616                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23617                                StorageManager.FLAG_STORAGE_CE, 0);
23618                    } catch (InstallerException e2) {
23619                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23620                    }
23621                }
23622            }
23623        }
23624        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23625            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23626            for (File file : files) {
23627                final String packageName = file.getName();
23628                try {
23629                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23630                } catch (PackageManagerException e) {
23631                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23632                    try {
23633                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23634                                StorageManager.FLAG_STORAGE_DE, 0);
23635                    } catch (InstallerException e2) {
23636                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23637                    }
23638                }
23639            }
23640        }
23641
23642        // Ensure that data directories are ready to roll for all packages
23643        // installed for this volume and user
23644        final List<PackageSetting> packages;
23645        synchronized (mPackages) {
23646            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23647        }
23648        int preparedCount = 0;
23649        for (PackageSetting ps : packages) {
23650            final String packageName = ps.name;
23651            if (ps.pkg == null) {
23652                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23653                // TODO: might be due to legacy ASEC apps; we should circle back
23654                // and reconcile again once they're scanned
23655                continue;
23656            }
23657            // Skip non-core apps if requested
23658            if (onlyCoreApps && !ps.pkg.coreApp) {
23659                result.add(packageName);
23660                continue;
23661            }
23662
23663            if (ps.getInstalled(userId)) {
23664                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23665                preparedCount++;
23666            }
23667        }
23668
23669        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23670        return result;
23671    }
23672
23673    /**
23674     * Prepare app data for the given app just after it was installed or
23675     * upgraded. This method carefully only touches users that it's installed
23676     * for, and it forces a restorecon to handle any seinfo changes.
23677     * <p>
23678     * Verifies that directories exist and that ownership and labeling is
23679     * correct for all installed apps. If there is an ownership mismatch, it
23680     * will try recovering system apps by wiping data; third-party app data is
23681     * left intact.
23682     * <p>
23683     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23684     */
23685    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23686        final PackageSetting ps;
23687        synchronized (mPackages) {
23688            ps = mSettings.mPackages.get(pkg.packageName);
23689            mSettings.writeKernelMappingLPr(ps);
23690        }
23691
23692        final UserManager um = mContext.getSystemService(UserManager.class);
23693        UserManagerInternal umInternal = getUserManagerInternal();
23694        for (UserInfo user : um.getUsers()) {
23695            final int flags;
23696            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23697                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23698            } else if (umInternal.isUserRunning(user.id)) {
23699                flags = StorageManager.FLAG_STORAGE_DE;
23700            } else {
23701                continue;
23702            }
23703
23704            if (ps.getInstalled(user.id)) {
23705                // TODO: when user data is locked, mark that we're still dirty
23706                prepareAppDataLIF(pkg, user.id, flags);
23707            }
23708        }
23709    }
23710
23711    /**
23712     * Prepare app data for the given app.
23713     * <p>
23714     * Verifies that directories exist and that ownership and labeling is
23715     * correct for all installed apps. If there is an ownership mismatch, this
23716     * will try recovering system apps by wiping data; third-party app data is
23717     * left intact.
23718     */
23719    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23720        if (pkg == null) {
23721            Slog.wtf(TAG, "Package was null!", new Throwable());
23722            return;
23723        }
23724        prepareAppDataLeafLIF(pkg, userId, flags);
23725        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23726        for (int i = 0; i < childCount; i++) {
23727            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23728        }
23729    }
23730
23731    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23732            boolean maybeMigrateAppData) {
23733        prepareAppDataLIF(pkg, userId, flags);
23734
23735        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23736            // We may have just shuffled around app data directories, so
23737            // prepare them one more time
23738            prepareAppDataLIF(pkg, userId, flags);
23739        }
23740    }
23741
23742    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23743        if (DEBUG_APP_DATA) {
23744            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23745                    + Integer.toHexString(flags));
23746        }
23747
23748        final String volumeUuid = pkg.volumeUuid;
23749        final String packageName = pkg.packageName;
23750        final ApplicationInfo app = pkg.applicationInfo;
23751        final int appId = UserHandle.getAppId(app.uid);
23752
23753        Preconditions.checkNotNull(app.seInfo);
23754
23755        long ceDataInode = -1;
23756        try {
23757            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23758                    appId, app.seInfo, app.targetSdkVersion);
23759        } catch (InstallerException e) {
23760            if (app.isSystemApp()) {
23761                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23762                        + ", but trying to recover: " + e);
23763                destroyAppDataLeafLIF(pkg, userId, flags);
23764                try {
23765                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23766                            appId, app.seInfo, app.targetSdkVersion);
23767                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23768                } catch (InstallerException e2) {
23769                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23770                }
23771            } else {
23772                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23773            }
23774        }
23775
23776        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23777            // TODO: mark this structure as dirty so we persist it!
23778            synchronized (mPackages) {
23779                final PackageSetting ps = mSettings.mPackages.get(packageName);
23780                if (ps != null) {
23781                    ps.setCeDataInode(ceDataInode, userId);
23782                }
23783            }
23784        }
23785
23786        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23787    }
23788
23789    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23790        if (pkg == null) {
23791            Slog.wtf(TAG, "Package was null!", new Throwable());
23792            return;
23793        }
23794        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23795        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23796        for (int i = 0; i < childCount; i++) {
23797            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23798        }
23799    }
23800
23801    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23802        final String volumeUuid = pkg.volumeUuid;
23803        final String packageName = pkg.packageName;
23804        final ApplicationInfo app = pkg.applicationInfo;
23805
23806        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23807            // Create a native library symlink only if we have native libraries
23808            // and if the native libraries are 32 bit libraries. We do not provide
23809            // this symlink for 64 bit libraries.
23810            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23811                final String nativeLibPath = app.nativeLibraryDir;
23812                try {
23813                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23814                            nativeLibPath, userId);
23815                } catch (InstallerException e) {
23816                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23817                }
23818            }
23819        }
23820    }
23821
23822    /**
23823     * For system apps on non-FBE devices, this method migrates any existing
23824     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23825     * requested by the app.
23826     */
23827    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23828        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23829                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23830            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23831                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23832            try {
23833                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23834                        storageTarget);
23835            } catch (InstallerException e) {
23836                logCriticalInfo(Log.WARN,
23837                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23838            }
23839            return true;
23840        } else {
23841            return false;
23842        }
23843    }
23844
23845    public PackageFreezer freezePackage(String packageName, String killReason) {
23846        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23847    }
23848
23849    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23850        return new PackageFreezer(packageName, userId, killReason);
23851    }
23852
23853    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23854            String killReason) {
23855        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23856    }
23857
23858    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23859            String killReason) {
23860        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23861            return new PackageFreezer();
23862        } else {
23863            return freezePackage(packageName, userId, killReason);
23864        }
23865    }
23866
23867    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23868            String killReason) {
23869        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23870    }
23871
23872    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23873            String killReason) {
23874        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23875            return new PackageFreezer();
23876        } else {
23877            return freezePackage(packageName, userId, killReason);
23878        }
23879    }
23880
23881    /**
23882     * Class that freezes and kills the given package upon creation, and
23883     * unfreezes it upon closing. This is typically used when doing surgery on
23884     * app code/data to prevent the app from running while you're working.
23885     */
23886    private class PackageFreezer implements AutoCloseable {
23887        private final String mPackageName;
23888        private final PackageFreezer[] mChildren;
23889
23890        private final boolean mWeFroze;
23891
23892        private final AtomicBoolean mClosed = new AtomicBoolean();
23893        private final CloseGuard mCloseGuard = CloseGuard.get();
23894
23895        /**
23896         * Create and return a stub freezer that doesn't actually do anything,
23897         * typically used when someone requested
23898         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23899         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23900         */
23901        public PackageFreezer() {
23902            mPackageName = null;
23903            mChildren = null;
23904            mWeFroze = false;
23905            mCloseGuard.open("close");
23906        }
23907
23908        public PackageFreezer(String packageName, int userId, String killReason) {
23909            synchronized (mPackages) {
23910                mPackageName = packageName;
23911                mWeFroze = mFrozenPackages.add(mPackageName);
23912
23913                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23914                if (ps != null) {
23915                    killApplication(ps.name, ps.appId, userId, killReason);
23916                }
23917
23918                final PackageParser.Package p = mPackages.get(packageName);
23919                if (p != null && p.childPackages != null) {
23920                    final int N = p.childPackages.size();
23921                    mChildren = new PackageFreezer[N];
23922                    for (int i = 0; i < N; i++) {
23923                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23924                                userId, killReason);
23925                    }
23926                } else {
23927                    mChildren = null;
23928                }
23929            }
23930            mCloseGuard.open("close");
23931        }
23932
23933        @Override
23934        protected void finalize() throws Throwable {
23935            try {
23936                if (mCloseGuard != null) {
23937                    mCloseGuard.warnIfOpen();
23938                }
23939
23940                close();
23941            } finally {
23942                super.finalize();
23943            }
23944        }
23945
23946        @Override
23947        public void close() {
23948            mCloseGuard.close();
23949            if (mClosed.compareAndSet(false, true)) {
23950                synchronized (mPackages) {
23951                    if (mWeFroze) {
23952                        mFrozenPackages.remove(mPackageName);
23953                    }
23954
23955                    if (mChildren != null) {
23956                        for (PackageFreezer freezer : mChildren) {
23957                            freezer.close();
23958                        }
23959                    }
23960                }
23961            }
23962        }
23963    }
23964
23965    /**
23966     * Verify that given package is currently frozen.
23967     */
23968    private void checkPackageFrozen(String packageName) {
23969        synchronized (mPackages) {
23970            if (!mFrozenPackages.contains(packageName)) {
23971                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23972            }
23973        }
23974    }
23975
23976    @Override
23977    public int movePackage(final String packageName, final String volumeUuid) {
23978        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23979
23980        final int callingUid = Binder.getCallingUid();
23981        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23982        final int moveId = mNextMoveId.getAndIncrement();
23983        mHandler.post(new Runnable() {
23984            @Override
23985            public void run() {
23986                try {
23987                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23988                } catch (PackageManagerException e) {
23989                    Slog.w(TAG, "Failed to move " + packageName, e);
23990                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
23991                }
23992            }
23993        });
23994        return moveId;
23995    }
23996
23997    private void movePackageInternal(final String packageName, final String volumeUuid,
23998            final int moveId, final int callingUid, UserHandle user)
23999                    throws PackageManagerException {
24000        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24001        final PackageManager pm = mContext.getPackageManager();
24002
24003        final boolean currentAsec;
24004        final String currentVolumeUuid;
24005        final File codeFile;
24006        final String installerPackageName;
24007        final String packageAbiOverride;
24008        final int appId;
24009        final String seinfo;
24010        final String label;
24011        final int targetSdkVersion;
24012        final PackageFreezer freezer;
24013        final int[] installedUserIds;
24014
24015        // reader
24016        synchronized (mPackages) {
24017            final PackageParser.Package pkg = mPackages.get(packageName);
24018            final PackageSetting ps = mSettings.mPackages.get(packageName);
24019            if (pkg == null
24020                    || ps == null
24021                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24022                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24023            }
24024            if (pkg.applicationInfo.isSystemApp()) {
24025                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24026                        "Cannot move system application");
24027            }
24028
24029            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24030            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24031                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24032            if (isInternalStorage && !allow3rdPartyOnInternal) {
24033                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24034                        "3rd party apps are not allowed on internal storage");
24035            }
24036
24037            if (pkg.applicationInfo.isExternalAsec()) {
24038                currentAsec = true;
24039                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24040            } else if (pkg.applicationInfo.isForwardLocked()) {
24041                currentAsec = true;
24042                currentVolumeUuid = "forward_locked";
24043            } else {
24044                currentAsec = false;
24045                currentVolumeUuid = ps.volumeUuid;
24046
24047                final File probe = new File(pkg.codePath);
24048                final File probeOat = new File(probe, "oat");
24049                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24050                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24051                            "Move only supported for modern cluster style installs");
24052                }
24053            }
24054
24055            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24056                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24057                        "Package already moved to " + volumeUuid);
24058            }
24059            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24060                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24061                        "Device admin cannot be moved");
24062            }
24063
24064            if (mFrozenPackages.contains(packageName)) {
24065                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24066                        "Failed to move already frozen package");
24067            }
24068
24069            codeFile = new File(pkg.codePath);
24070            installerPackageName = ps.installerPackageName;
24071            packageAbiOverride = ps.cpuAbiOverrideString;
24072            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24073            seinfo = pkg.applicationInfo.seInfo;
24074            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24075            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24076            freezer = freezePackage(packageName, "movePackageInternal");
24077            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24078        }
24079
24080        final Bundle extras = new Bundle();
24081        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24082        extras.putString(Intent.EXTRA_TITLE, label);
24083        mMoveCallbacks.notifyCreated(moveId, extras);
24084
24085        int installFlags;
24086        final boolean moveCompleteApp;
24087        final File measurePath;
24088
24089        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24090            installFlags = INSTALL_INTERNAL;
24091            moveCompleteApp = !currentAsec;
24092            measurePath = Environment.getDataAppDirectory(volumeUuid);
24093        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24094            installFlags = INSTALL_EXTERNAL;
24095            moveCompleteApp = false;
24096            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24097        } else {
24098            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24099            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24100                    || !volume.isMountedWritable()) {
24101                freezer.close();
24102                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24103                        "Move location not mounted private volume");
24104            }
24105
24106            Preconditions.checkState(!currentAsec);
24107
24108            installFlags = INSTALL_INTERNAL;
24109            moveCompleteApp = true;
24110            measurePath = Environment.getDataAppDirectory(volumeUuid);
24111        }
24112
24113        // If we're moving app data around, we need all the users unlocked
24114        if (moveCompleteApp) {
24115            for (int userId : installedUserIds) {
24116                if (StorageManager.isFileEncryptedNativeOrEmulated()
24117                        && !StorageManager.isUserKeyUnlocked(userId)) {
24118                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24119                            "User " + userId + " must be unlocked");
24120                }
24121            }
24122        }
24123
24124        final PackageStats stats = new PackageStats(null, -1);
24125        synchronized (mInstaller) {
24126            for (int userId : installedUserIds) {
24127                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24128                    freezer.close();
24129                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24130                            "Failed to measure package size");
24131                }
24132            }
24133        }
24134
24135        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24136                + stats.dataSize);
24137
24138        final long startFreeBytes = measurePath.getUsableSpace();
24139        final long sizeBytes;
24140        if (moveCompleteApp) {
24141            sizeBytes = stats.codeSize + stats.dataSize;
24142        } else {
24143            sizeBytes = stats.codeSize;
24144        }
24145
24146        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24147            freezer.close();
24148            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24149                    "Not enough free space to move");
24150        }
24151
24152        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24153
24154        final CountDownLatch installedLatch = new CountDownLatch(1);
24155        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24156            @Override
24157            public void onUserActionRequired(Intent intent) throws RemoteException {
24158                throw new IllegalStateException();
24159            }
24160
24161            @Override
24162            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24163                    Bundle extras) throws RemoteException {
24164                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24165                        + PackageManager.installStatusToString(returnCode, msg));
24166
24167                installedLatch.countDown();
24168                freezer.close();
24169
24170                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24171                switch (status) {
24172                    case PackageInstaller.STATUS_SUCCESS:
24173                        mMoveCallbacks.notifyStatusChanged(moveId,
24174                                PackageManager.MOVE_SUCCEEDED);
24175                        break;
24176                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24177                        mMoveCallbacks.notifyStatusChanged(moveId,
24178                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24179                        break;
24180                    default:
24181                        mMoveCallbacks.notifyStatusChanged(moveId,
24182                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24183                        break;
24184                }
24185            }
24186        };
24187
24188        final MoveInfo move;
24189        if (moveCompleteApp) {
24190            // Kick off a thread to report progress estimates
24191            new Thread() {
24192                @Override
24193                public void run() {
24194                    while (true) {
24195                        try {
24196                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24197                                break;
24198                            }
24199                        } catch (InterruptedException ignored) {
24200                        }
24201
24202                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24203                        final int progress = 10 + (int) MathUtils.constrain(
24204                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24205                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24206                    }
24207                }
24208            }.start();
24209
24210            final String dataAppName = codeFile.getName();
24211            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24212                    dataAppName, appId, seinfo, targetSdkVersion);
24213        } else {
24214            move = null;
24215        }
24216
24217        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24218
24219        final Message msg = mHandler.obtainMessage(INIT_COPY);
24220        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24221        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24222                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24223                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24224                PackageManager.INSTALL_REASON_UNKNOWN);
24225        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24226        msg.obj = params;
24227
24228        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24229                System.identityHashCode(msg.obj));
24230        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24231                System.identityHashCode(msg.obj));
24232
24233        mHandler.sendMessage(msg);
24234    }
24235
24236    @Override
24237    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24238        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24239
24240        final int realMoveId = mNextMoveId.getAndIncrement();
24241        final Bundle extras = new Bundle();
24242        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24243        mMoveCallbacks.notifyCreated(realMoveId, extras);
24244
24245        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24246            @Override
24247            public void onCreated(int moveId, Bundle extras) {
24248                // Ignored
24249            }
24250
24251            @Override
24252            public void onStatusChanged(int moveId, int status, long estMillis) {
24253                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24254            }
24255        };
24256
24257        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24258        storage.setPrimaryStorageUuid(volumeUuid, callback);
24259        return realMoveId;
24260    }
24261
24262    @Override
24263    public int getMoveStatus(int moveId) {
24264        mContext.enforceCallingOrSelfPermission(
24265                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24266        return mMoveCallbacks.mLastStatus.get(moveId);
24267    }
24268
24269    @Override
24270    public void registerMoveCallback(IPackageMoveObserver callback) {
24271        mContext.enforceCallingOrSelfPermission(
24272                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24273        mMoveCallbacks.register(callback);
24274    }
24275
24276    @Override
24277    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24278        mContext.enforceCallingOrSelfPermission(
24279                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24280        mMoveCallbacks.unregister(callback);
24281    }
24282
24283    @Override
24284    public boolean setInstallLocation(int loc) {
24285        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24286                null);
24287        if (getInstallLocation() == loc) {
24288            return true;
24289        }
24290        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24291                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24292            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24293                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24294            return true;
24295        }
24296        return false;
24297   }
24298
24299    @Override
24300    public int getInstallLocation() {
24301        // allow instant app access
24302        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24303                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24304                PackageHelper.APP_INSTALL_AUTO);
24305    }
24306
24307    /** Called by UserManagerService */
24308    void cleanUpUser(UserManagerService userManager, int userHandle) {
24309        synchronized (mPackages) {
24310            mDirtyUsers.remove(userHandle);
24311            mUserNeedsBadging.delete(userHandle);
24312            mSettings.removeUserLPw(userHandle);
24313            mPendingBroadcasts.remove(userHandle);
24314            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24315            removeUnusedPackagesLPw(userManager, userHandle);
24316        }
24317    }
24318
24319    /**
24320     * We're removing userHandle and would like to remove any downloaded packages
24321     * that are no longer in use by any other user.
24322     * @param userHandle the user being removed
24323     */
24324    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24325        final boolean DEBUG_CLEAN_APKS = false;
24326        int [] users = userManager.getUserIds();
24327        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24328        while (psit.hasNext()) {
24329            PackageSetting ps = psit.next();
24330            if (ps.pkg == null) {
24331                continue;
24332            }
24333            final String packageName = ps.pkg.packageName;
24334            // Skip over if system app
24335            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24336                continue;
24337            }
24338            if (DEBUG_CLEAN_APKS) {
24339                Slog.i(TAG, "Checking package " + packageName);
24340            }
24341            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24342            if (keep) {
24343                if (DEBUG_CLEAN_APKS) {
24344                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24345                }
24346            } else {
24347                for (int i = 0; i < users.length; i++) {
24348                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24349                        keep = true;
24350                        if (DEBUG_CLEAN_APKS) {
24351                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24352                                    + users[i]);
24353                        }
24354                        break;
24355                    }
24356                }
24357            }
24358            if (!keep) {
24359                if (DEBUG_CLEAN_APKS) {
24360                    Slog.i(TAG, "  Removing package " + packageName);
24361                }
24362                mHandler.post(new Runnable() {
24363                    public void run() {
24364                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24365                                userHandle, 0);
24366                    } //end run
24367                });
24368            }
24369        }
24370    }
24371
24372    /** Called by UserManagerService */
24373    void createNewUser(int userId, String[] disallowedPackages) {
24374        synchronized (mInstallLock) {
24375            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24376        }
24377        synchronized (mPackages) {
24378            scheduleWritePackageRestrictionsLocked(userId);
24379            scheduleWritePackageListLocked(userId);
24380            applyFactoryDefaultBrowserLPw(userId);
24381            primeDomainVerificationsLPw(userId);
24382        }
24383    }
24384
24385    void onNewUserCreated(final int userId) {
24386        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24387        // If permission review for legacy apps is required, we represent
24388        // dagerous permissions for such apps as always granted runtime
24389        // permissions to keep per user flag state whether review is needed.
24390        // Hence, if a new user is added we have to propagate dangerous
24391        // permission grants for these legacy apps.
24392        if (mPermissionReviewRequired) {
24393            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24394                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24395        }
24396    }
24397
24398    @Override
24399    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24400        mContext.enforceCallingOrSelfPermission(
24401                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24402                "Only package verification agents can read the verifier device identity");
24403
24404        synchronized (mPackages) {
24405            return mSettings.getVerifierDeviceIdentityLPw();
24406        }
24407    }
24408
24409    @Override
24410    public void setPermissionEnforced(String permission, boolean enforced) {
24411        // TODO: Now that we no longer change GID for storage, this should to away.
24412        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24413                "setPermissionEnforced");
24414        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24415            synchronized (mPackages) {
24416                if (mSettings.mReadExternalStorageEnforced == null
24417                        || mSettings.mReadExternalStorageEnforced != enforced) {
24418                    mSettings.mReadExternalStorageEnforced = enforced;
24419                    mSettings.writeLPr();
24420                }
24421            }
24422            // kill any non-foreground processes so we restart them and
24423            // grant/revoke the GID.
24424            final IActivityManager am = ActivityManager.getService();
24425            if (am != null) {
24426                final long token = Binder.clearCallingIdentity();
24427                try {
24428                    am.killProcessesBelowForeground("setPermissionEnforcement");
24429                } catch (RemoteException e) {
24430                } finally {
24431                    Binder.restoreCallingIdentity(token);
24432                }
24433            }
24434        } else {
24435            throw new IllegalArgumentException("No selective enforcement for " + permission);
24436        }
24437    }
24438
24439    @Override
24440    @Deprecated
24441    public boolean isPermissionEnforced(String permission) {
24442        // allow instant applications
24443        return true;
24444    }
24445
24446    @Override
24447    public boolean isStorageLow() {
24448        // allow instant applications
24449        final long token = Binder.clearCallingIdentity();
24450        try {
24451            final DeviceStorageMonitorInternal
24452                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24453            if (dsm != null) {
24454                return dsm.isMemoryLow();
24455            } else {
24456                return false;
24457            }
24458        } finally {
24459            Binder.restoreCallingIdentity(token);
24460        }
24461    }
24462
24463    @Override
24464    public IPackageInstaller getPackageInstaller() {
24465        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24466            return null;
24467        }
24468        return mInstallerService;
24469    }
24470
24471    private boolean userNeedsBadging(int userId) {
24472        int index = mUserNeedsBadging.indexOfKey(userId);
24473        if (index < 0) {
24474            final UserInfo userInfo;
24475            final long token = Binder.clearCallingIdentity();
24476            try {
24477                userInfo = sUserManager.getUserInfo(userId);
24478            } finally {
24479                Binder.restoreCallingIdentity(token);
24480            }
24481            final boolean b;
24482            if (userInfo != null && userInfo.isManagedProfile()) {
24483                b = true;
24484            } else {
24485                b = false;
24486            }
24487            mUserNeedsBadging.put(userId, b);
24488            return b;
24489        }
24490        return mUserNeedsBadging.valueAt(index);
24491    }
24492
24493    @Override
24494    public KeySet getKeySetByAlias(String packageName, String alias) {
24495        if (packageName == null || alias == null) {
24496            return null;
24497        }
24498        synchronized(mPackages) {
24499            final PackageParser.Package pkg = mPackages.get(packageName);
24500            if (pkg == null) {
24501                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24502                throw new IllegalArgumentException("Unknown package: " + packageName);
24503            }
24504            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24505            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24506                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24507                throw new IllegalArgumentException("Unknown package: " + packageName);
24508            }
24509            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24510            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24511        }
24512    }
24513
24514    @Override
24515    public KeySet getSigningKeySet(String packageName) {
24516        if (packageName == null) {
24517            return null;
24518        }
24519        synchronized(mPackages) {
24520            final int callingUid = Binder.getCallingUid();
24521            final int callingUserId = UserHandle.getUserId(callingUid);
24522            final PackageParser.Package pkg = mPackages.get(packageName);
24523            if (pkg == null) {
24524                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24525                throw new IllegalArgumentException("Unknown package: " + packageName);
24526            }
24527            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24528            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24529                // filter and pretend the package doesn't exist
24530                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24531                        + ", uid:" + callingUid);
24532                throw new IllegalArgumentException("Unknown package: " + packageName);
24533            }
24534            if (pkg.applicationInfo.uid != callingUid
24535                    && Process.SYSTEM_UID != callingUid) {
24536                throw new SecurityException("May not access signing KeySet of other apps.");
24537            }
24538            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24539            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24540        }
24541    }
24542
24543    @Override
24544    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24545        final int callingUid = Binder.getCallingUid();
24546        if (getInstantAppPackageName(callingUid) != null) {
24547            return false;
24548        }
24549        if (packageName == null || ks == null) {
24550            return false;
24551        }
24552        synchronized(mPackages) {
24553            final PackageParser.Package pkg = mPackages.get(packageName);
24554            if (pkg == null
24555                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24556                            UserHandle.getUserId(callingUid))) {
24557                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24558                throw new IllegalArgumentException("Unknown package: " + packageName);
24559            }
24560            IBinder ksh = ks.getToken();
24561            if (ksh instanceof KeySetHandle) {
24562                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24563                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24564            }
24565            return false;
24566        }
24567    }
24568
24569    @Override
24570    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24571        final int callingUid = Binder.getCallingUid();
24572        if (getInstantAppPackageName(callingUid) != null) {
24573            return false;
24574        }
24575        if (packageName == null || ks == null) {
24576            return false;
24577        }
24578        synchronized(mPackages) {
24579            final PackageParser.Package pkg = mPackages.get(packageName);
24580            if (pkg == null
24581                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24582                            UserHandle.getUserId(callingUid))) {
24583                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24584                throw new IllegalArgumentException("Unknown package: " + packageName);
24585            }
24586            IBinder ksh = ks.getToken();
24587            if (ksh instanceof KeySetHandle) {
24588                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24589                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24590            }
24591            return false;
24592        }
24593    }
24594
24595    private void deletePackageIfUnusedLPr(final String packageName) {
24596        PackageSetting ps = mSettings.mPackages.get(packageName);
24597        if (ps == null) {
24598            return;
24599        }
24600        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24601            // TODO Implement atomic delete if package is unused
24602            // It is currently possible that the package will be deleted even if it is installed
24603            // after this method returns.
24604            mHandler.post(new Runnable() {
24605                public void run() {
24606                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24607                            0, PackageManager.DELETE_ALL_USERS);
24608                }
24609            });
24610        }
24611    }
24612
24613    /**
24614     * Check and throw if the given before/after packages would be considered a
24615     * downgrade.
24616     */
24617    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24618            throws PackageManagerException {
24619        if (after.versionCode < before.mVersionCode) {
24620            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24621                    "Update version code " + after.versionCode + " is older than current "
24622                    + before.mVersionCode);
24623        } else if (after.versionCode == before.mVersionCode) {
24624            if (after.baseRevisionCode < before.baseRevisionCode) {
24625                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24626                        "Update base revision code " + after.baseRevisionCode
24627                        + " is older than current " + before.baseRevisionCode);
24628            }
24629
24630            if (!ArrayUtils.isEmpty(after.splitNames)) {
24631                for (int i = 0; i < after.splitNames.length; i++) {
24632                    final String splitName = after.splitNames[i];
24633                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24634                    if (j != -1) {
24635                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24636                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24637                                    "Update split " + splitName + " revision code "
24638                                    + after.splitRevisionCodes[i] + " is older than current "
24639                                    + before.splitRevisionCodes[j]);
24640                        }
24641                    }
24642                }
24643            }
24644        }
24645    }
24646
24647    private static class MoveCallbacks extends Handler {
24648        private static final int MSG_CREATED = 1;
24649        private static final int MSG_STATUS_CHANGED = 2;
24650
24651        private final RemoteCallbackList<IPackageMoveObserver>
24652                mCallbacks = new RemoteCallbackList<>();
24653
24654        private final SparseIntArray mLastStatus = new SparseIntArray();
24655
24656        public MoveCallbacks(Looper looper) {
24657            super(looper);
24658        }
24659
24660        public void register(IPackageMoveObserver callback) {
24661            mCallbacks.register(callback);
24662        }
24663
24664        public void unregister(IPackageMoveObserver callback) {
24665            mCallbacks.unregister(callback);
24666        }
24667
24668        @Override
24669        public void handleMessage(Message msg) {
24670            final SomeArgs args = (SomeArgs) msg.obj;
24671            final int n = mCallbacks.beginBroadcast();
24672            for (int i = 0; i < n; i++) {
24673                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24674                try {
24675                    invokeCallback(callback, msg.what, args);
24676                } catch (RemoteException ignored) {
24677                }
24678            }
24679            mCallbacks.finishBroadcast();
24680            args.recycle();
24681        }
24682
24683        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24684                throws RemoteException {
24685            switch (what) {
24686                case MSG_CREATED: {
24687                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24688                    break;
24689                }
24690                case MSG_STATUS_CHANGED: {
24691                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24692                    break;
24693                }
24694            }
24695        }
24696
24697        private void notifyCreated(int moveId, Bundle extras) {
24698            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24699
24700            final SomeArgs args = SomeArgs.obtain();
24701            args.argi1 = moveId;
24702            args.arg2 = extras;
24703            obtainMessage(MSG_CREATED, args).sendToTarget();
24704        }
24705
24706        private void notifyStatusChanged(int moveId, int status) {
24707            notifyStatusChanged(moveId, status, -1);
24708        }
24709
24710        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24711            Slog.v(TAG, "Move " + moveId + " status " + status);
24712
24713            final SomeArgs args = SomeArgs.obtain();
24714            args.argi1 = moveId;
24715            args.argi2 = status;
24716            args.arg3 = estMillis;
24717            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24718
24719            synchronized (mLastStatus) {
24720                mLastStatus.put(moveId, status);
24721            }
24722        }
24723    }
24724
24725    private final static class OnPermissionChangeListeners extends Handler {
24726        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24727
24728        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24729                new RemoteCallbackList<>();
24730
24731        public OnPermissionChangeListeners(Looper looper) {
24732            super(looper);
24733        }
24734
24735        @Override
24736        public void handleMessage(Message msg) {
24737            switch (msg.what) {
24738                case MSG_ON_PERMISSIONS_CHANGED: {
24739                    final int uid = msg.arg1;
24740                    handleOnPermissionsChanged(uid);
24741                } break;
24742            }
24743        }
24744
24745        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24746            mPermissionListeners.register(listener);
24747
24748        }
24749
24750        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24751            mPermissionListeners.unregister(listener);
24752        }
24753
24754        public void onPermissionsChanged(int uid) {
24755            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24756                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24757            }
24758        }
24759
24760        private void handleOnPermissionsChanged(int uid) {
24761            final int count = mPermissionListeners.beginBroadcast();
24762            try {
24763                for (int i = 0; i < count; i++) {
24764                    IOnPermissionsChangeListener callback = mPermissionListeners
24765                            .getBroadcastItem(i);
24766                    try {
24767                        callback.onPermissionsChanged(uid);
24768                    } catch (RemoteException e) {
24769                        Log.e(TAG, "Permission listener is dead", e);
24770                    }
24771                }
24772            } finally {
24773                mPermissionListeners.finishBroadcast();
24774            }
24775        }
24776    }
24777
24778    private class PackageManagerInternalImpl extends PackageManagerInternal {
24779        @Override
24780        public void setLocationPackagesProvider(PackagesProvider provider) {
24781            synchronized (mPackages) {
24782                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24783            }
24784        }
24785
24786        @Override
24787        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24788            synchronized (mPackages) {
24789                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24790            }
24791        }
24792
24793        @Override
24794        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24795            synchronized (mPackages) {
24796                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24797            }
24798        }
24799
24800        @Override
24801        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24802            synchronized (mPackages) {
24803                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24804            }
24805        }
24806
24807        @Override
24808        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24809            synchronized (mPackages) {
24810                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24811            }
24812        }
24813
24814        @Override
24815        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24816            synchronized (mPackages) {
24817                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24818            }
24819        }
24820
24821        @Override
24822        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24823            synchronized (mPackages) {
24824                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24825                        packageName, userId);
24826            }
24827        }
24828
24829        @Override
24830        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24831            synchronized (mPackages) {
24832                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24833                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24834                        packageName, userId);
24835            }
24836        }
24837
24838        @Override
24839        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24840            synchronized (mPackages) {
24841                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24842                        packageName, userId);
24843            }
24844        }
24845
24846        @Override
24847        public void setKeepUninstalledPackages(final List<String> packageList) {
24848            Preconditions.checkNotNull(packageList);
24849            List<String> removedFromList = null;
24850            synchronized (mPackages) {
24851                if (mKeepUninstalledPackages != null) {
24852                    final int packagesCount = mKeepUninstalledPackages.size();
24853                    for (int i = 0; i < packagesCount; i++) {
24854                        String oldPackage = mKeepUninstalledPackages.get(i);
24855                        if (packageList != null && packageList.contains(oldPackage)) {
24856                            continue;
24857                        }
24858                        if (removedFromList == null) {
24859                            removedFromList = new ArrayList<>();
24860                        }
24861                        removedFromList.add(oldPackage);
24862                    }
24863                }
24864                mKeepUninstalledPackages = new ArrayList<>(packageList);
24865                if (removedFromList != null) {
24866                    final int removedCount = removedFromList.size();
24867                    for (int i = 0; i < removedCount; i++) {
24868                        deletePackageIfUnusedLPr(removedFromList.get(i));
24869                    }
24870                }
24871            }
24872        }
24873
24874        @Override
24875        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24876            synchronized (mPackages) {
24877                // If we do not support permission review, done.
24878                if (!mPermissionReviewRequired) {
24879                    return false;
24880                }
24881
24882                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24883                if (packageSetting == null) {
24884                    return false;
24885                }
24886
24887                // Permission review applies only to apps not supporting the new permission model.
24888                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24889                    return false;
24890                }
24891
24892                // Legacy apps have the permission and get user consent on launch.
24893                PermissionsState permissionsState = packageSetting.getPermissionsState();
24894                return permissionsState.isPermissionReviewRequired(userId);
24895            }
24896        }
24897
24898        @Override
24899        public PackageInfo getPackageInfo(
24900                String packageName, int flags, int filterCallingUid, int userId) {
24901            return PackageManagerService.this
24902                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24903                            flags, filterCallingUid, userId);
24904        }
24905
24906        @Override
24907        public ApplicationInfo getApplicationInfo(
24908                String packageName, int flags, int filterCallingUid, int userId) {
24909            return PackageManagerService.this
24910                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24911        }
24912
24913        @Override
24914        public ActivityInfo getActivityInfo(
24915                ComponentName component, int flags, int filterCallingUid, int userId) {
24916            return PackageManagerService.this
24917                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24918        }
24919
24920        @Override
24921        public List<ResolveInfo> queryIntentActivities(
24922                Intent intent, int flags, int filterCallingUid, int userId) {
24923            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24924            return PackageManagerService.this
24925                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24926                            userId, false /*resolveForStart*/);
24927        }
24928
24929        @Override
24930        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24931                int userId) {
24932            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24933        }
24934
24935        @Override
24936        public void setDeviceAndProfileOwnerPackages(
24937                int deviceOwnerUserId, String deviceOwnerPackage,
24938                SparseArray<String> profileOwnerPackages) {
24939            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24940                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24941        }
24942
24943        @Override
24944        public boolean isPackageDataProtected(int userId, String packageName) {
24945            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24946        }
24947
24948        @Override
24949        public boolean isPackageEphemeral(int userId, String packageName) {
24950            synchronized (mPackages) {
24951                final PackageSetting ps = mSettings.mPackages.get(packageName);
24952                return ps != null ? ps.getInstantApp(userId) : false;
24953            }
24954        }
24955
24956        @Override
24957        public boolean wasPackageEverLaunched(String packageName, int userId) {
24958            synchronized (mPackages) {
24959                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24960            }
24961        }
24962
24963        @Override
24964        public void grantRuntimePermission(String packageName, String name, int userId,
24965                boolean overridePolicy) {
24966            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24967                    overridePolicy);
24968        }
24969
24970        @Override
24971        public void revokeRuntimePermission(String packageName, String name, int userId,
24972                boolean overridePolicy) {
24973            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24974                    overridePolicy);
24975        }
24976
24977        @Override
24978        public String getNameForUid(int uid) {
24979            return PackageManagerService.this.getNameForUid(uid);
24980        }
24981
24982        @Override
24983        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24984                Intent origIntent, String resolvedType, String callingPackage,
24985                Bundle verificationBundle, int userId) {
24986            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24987                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24988                    userId);
24989        }
24990
24991        @Override
24992        public void grantEphemeralAccess(int userId, Intent intent,
24993                int targetAppId, int ephemeralAppId) {
24994            synchronized (mPackages) {
24995                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24996                        targetAppId, ephemeralAppId);
24997            }
24998        }
24999
25000        @Override
25001        public boolean isInstantAppInstallerComponent(ComponentName component) {
25002            synchronized (mPackages) {
25003                return mInstantAppInstallerActivity != null
25004                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25005            }
25006        }
25007
25008        @Override
25009        public void pruneInstantApps() {
25010            mInstantAppRegistry.pruneInstantApps();
25011        }
25012
25013        @Override
25014        public String getSetupWizardPackageName() {
25015            return mSetupWizardPackage;
25016        }
25017
25018        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25019            if (policy != null) {
25020                mExternalSourcesPolicy = policy;
25021            }
25022        }
25023
25024        @Override
25025        public boolean isPackagePersistent(String packageName) {
25026            synchronized (mPackages) {
25027                PackageParser.Package pkg = mPackages.get(packageName);
25028                return pkg != null
25029                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25030                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25031                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25032                        : false;
25033            }
25034        }
25035
25036        @Override
25037        public List<PackageInfo> getOverlayPackages(int userId) {
25038            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25039            synchronized (mPackages) {
25040                for (PackageParser.Package p : mPackages.values()) {
25041                    if (p.mOverlayTarget != null) {
25042                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25043                        if (pkg != null) {
25044                            overlayPackages.add(pkg);
25045                        }
25046                    }
25047                }
25048            }
25049            return overlayPackages;
25050        }
25051
25052        @Override
25053        public List<String> getTargetPackageNames(int userId) {
25054            List<String> targetPackages = new ArrayList<>();
25055            synchronized (mPackages) {
25056                for (PackageParser.Package p : mPackages.values()) {
25057                    if (p.mOverlayTarget == null) {
25058                        targetPackages.add(p.packageName);
25059                    }
25060                }
25061            }
25062            return targetPackages;
25063        }
25064
25065        @Override
25066        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25067                @Nullable List<String> overlayPackageNames) {
25068            synchronized (mPackages) {
25069                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25070                    Slog.e(TAG, "failed to find package " + targetPackageName);
25071                    return false;
25072                }
25073                ArrayList<String> overlayPaths = null;
25074                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25075                    final int N = overlayPackageNames.size();
25076                    overlayPaths = new ArrayList<>(N);
25077                    for (int i = 0; i < N; i++) {
25078                        final String packageName = overlayPackageNames.get(i);
25079                        final PackageParser.Package pkg = mPackages.get(packageName);
25080                        if (pkg == null) {
25081                            Slog.e(TAG, "failed to find package " + packageName);
25082                            return false;
25083                        }
25084                        overlayPaths.add(pkg.baseCodePath);
25085                    }
25086                }
25087
25088                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25089                ps.setOverlayPaths(overlayPaths, userId);
25090                return true;
25091            }
25092        }
25093
25094        @Override
25095        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25096                int flags, int userId) {
25097            return resolveIntentInternal(
25098                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25099        }
25100
25101        @Override
25102        public ResolveInfo resolveService(Intent intent, String resolvedType,
25103                int flags, int userId, int callingUid) {
25104            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25105        }
25106
25107        @Override
25108        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25109            synchronized (mPackages) {
25110                mIsolatedOwners.put(isolatedUid, ownerUid);
25111            }
25112        }
25113
25114        @Override
25115        public void removeIsolatedUid(int isolatedUid) {
25116            synchronized (mPackages) {
25117                mIsolatedOwners.delete(isolatedUid);
25118            }
25119        }
25120
25121        @Override
25122        public int getUidTargetSdkVersion(int uid) {
25123            synchronized (mPackages) {
25124                return getUidTargetSdkVersionLockedLPr(uid);
25125            }
25126        }
25127
25128        @Override
25129        public boolean canAccessInstantApps(int callingUid, int userId) {
25130            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25131        }
25132    }
25133
25134    @Override
25135    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25136        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25137        synchronized (mPackages) {
25138            final long identity = Binder.clearCallingIdentity();
25139            try {
25140                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25141                        packageNames, userId);
25142            } finally {
25143                Binder.restoreCallingIdentity(identity);
25144            }
25145        }
25146    }
25147
25148    @Override
25149    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25150        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25151        synchronized (mPackages) {
25152            final long identity = Binder.clearCallingIdentity();
25153            try {
25154                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25155                        packageNames, userId);
25156            } finally {
25157                Binder.restoreCallingIdentity(identity);
25158            }
25159        }
25160    }
25161
25162    private static void enforceSystemOrPhoneCaller(String tag) {
25163        int callingUid = Binder.getCallingUid();
25164        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25165            throw new SecurityException(
25166                    "Cannot call " + tag + " from UID " + callingUid);
25167        }
25168    }
25169
25170    boolean isHistoricalPackageUsageAvailable() {
25171        return mPackageUsage.isHistoricalPackageUsageAvailable();
25172    }
25173
25174    /**
25175     * Return a <b>copy</b> of the collection of packages known to the package manager.
25176     * @return A copy of the values of mPackages.
25177     */
25178    Collection<PackageParser.Package> getPackages() {
25179        synchronized (mPackages) {
25180            return new ArrayList<>(mPackages.values());
25181        }
25182    }
25183
25184    /**
25185     * Logs process start information (including base APK hash) to the security log.
25186     * @hide
25187     */
25188    @Override
25189    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25190            String apkFile, int pid) {
25191        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25192            return;
25193        }
25194        if (!SecurityLog.isLoggingEnabled()) {
25195            return;
25196        }
25197        Bundle data = new Bundle();
25198        data.putLong("startTimestamp", System.currentTimeMillis());
25199        data.putString("processName", processName);
25200        data.putInt("uid", uid);
25201        data.putString("seinfo", seinfo);
25202        data.putString("apkFile", apkFile);
25203        data.putInt("pid", pid);
25204        Message msg = mProcessLoggingHandler.obtainMessage(
25205                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25206        msg.setData(data);
25207        mProcessLoggingHandler.sendMessage(msg);
25208    }
25209
25210    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25211        return mCompilerStats.getPackageStats(pkgName);
25212    }
25213
25214    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25215        return getOrCreateCompilerPackageStats(pkg.packageName);
25216    }
25217
25218    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25219        return mCompilerStats.getOrCreatePackageStats(pkgName);
25220    }
25221
25222    public void deleteCompilerPackageStats(String pkgName) {
25223        mCompilerStats.deletePackageStats(pkgName);
25224    }
25225
25226    @Override
25227    public int getInstallReason(String packageName, int userId) {
25228        final int callingUid = Binder.getCallingUid();
25229        enforceCrossUserPermission(callingUid, userId,
25230                true /* requireFullPermission */, false /* checkShell */,
25231                "get install reason");
25232        synchronized (mPackages) {
25233            final PackageSetting ps = mSettings.mPackages.get(packageName);
25234            if (filterAppAccessLPr(ps, callingUid, userId)) {
25235                return PackageManager.INSTALL_REASON_UNKNOWN;
25236            }
25237            if (ps != null) {
25238                return ps.getInstallReason(userId);
25239            }
25240        }
25241        return PackageManager.INSTALL_REASON_UNKNOWN;
25242    }
25243
25244    @Override
25245    public boolean canRequestPackageInstalls(String packageName, int userId) {
25246        return canRequestPackageInstallsInternal(packageName, 0, userId,
25247                true /* throwIfPermNotDeclared*/);
25248    }
25249
25250    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25251            boolean throwIfPermNotDeclared) {
25252        int callingUid = Binder.getCallingUid();
25253        int uid = getPackageUid(packageName, 0, userId);
25254        if (callingUid != uid && callingUid != Process.ROOT_UID
25255                && callingUid != Process.SYSTEM_UID) {
25256            throw new SecurityException(
25257                    "Caller uid " + callingUid + " does not own package " + packageName);
25258        }
25259        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25260        if (info == null) {
25261            return false;
25262        }
25263        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25264            return false;
25265        }
25266        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25267        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25268        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25269            if (throwIfPermNotDeclared) {
25270                throw new SecurityException("Need to declare " + appOpPermission
25271                        + " to call this api");
25272            } else {
25273                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25274                return false;
25275            }
25276        }
25277        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25278            return false;
25279        }
25280        if (mExternalSourcesPolicy != null) {
25281            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25282            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25283                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25284            }
25285        }
25286        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25287    }
25288
25289    @Override
25290    public ComponentName getInstantAppResolverSettingsComponent() {
25291        return mInstantAppResolverSettingsComponent;
25292    }
25293
25294    @Override
25295    public ComponentName getInstantAppInstallerComponent() {
25296        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25297            return null;
25298        }
25299        return mInstantAppInstallerActivity == null
25300                ? null : mInstantAppInstallerActivity.getComponentName();
25301    }
25302
25303    @Override
25304    public String getInstantAppAndroidId(String packageName, int userId) {
25305        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25306                "getInstantAppAndroidId");
25307        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25308                true /* requireFullPermission */, false /* checkShell */,
25309                "getInstantAppAndroidId");
25310        // Make sure the target is an Instant App.
25311        if (!isInstantApp(packageName, userId)) {
25312            return null;
25313        }
25314        synchronized (mPackages) {
25315            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25316        }
25317    }
25318
25319    boolean canHaveOatDir(String packageName) {
25320        synchronized (mPackages) {
25321            PackageParser.Package p = mPackages.get(packageName);
25322            if (p == null) {
25323                return false;
25324            }
25325            return p.canHaveOatDir();
25326        }
25327    }
25328
25329    private String getOatDir(PackageParser.Package pkg) {
25330        if (!pkg.canHaveOatDir()) {
25331            return null;
25332        }
25333        File codePath = new File(pkg.codePath);
25334        if (codePath.isDirectory()) {
25335            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25336        }
25337        return null;
25338    }
25339
25340    void deleteOatArtifactsOfPackage(String packageName) {
25341        final String[] instructionSets;
25342        final List<String> codePaths;
25343        final String oatDir;
25344        final PackageParser.Package pkg;
25345        synchronized (mPackages) {
25346            pkg = mPackages.get(packageName);
25347        }
25348        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25349        codePaths = pkg.getAllCodePaths();
25350        oatDir = getOatDir(pkg);
25351
25352        for (String codePath : codePaths) {
25353            for (String isa : instructionSets) {
25354                try {
25355                    mInstaller.deleteOdex(codePath, isa, oatDir);
25356                } catch (InstallerException e) {
25357                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25358                }
25359            }
25360        }
25361    }
25362
25363    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25364        Set<String> unusedPackages = new HashSet<>();
25365        long currentTimeInMillis = System.currentTimeMillis();
25366        synchronized (mPackages) {
25367            for (PackageParser.Package pkg : mPackages.values()) {
25368                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25369                if (ps == null) {
25370                    continue;
25371                }
25372                PackageDexUsage.PackageUseInfo packageUseInfo = getDexManager().getPackageUseInfo(
25373                        pkg.packageName);
25374                if (PackageManagerServiceUtils
25375                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25376                                downgradeTimeThresholdMillis, packageUseInfo,
25377                                pkg.getLatestPackageUseTimeInMills(),
25378                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25379                    unusedPackages.add(pkg.packageName);
25380                }
25381            }
25382        }
25383        return unusedPackages;
25384    }
25385}
25386
25387interface PackageSender {
25388    void sendPackageBroadcast(final String action, final String pkg,
25389        final Bundle extras, final int flags, final String targetPkg,
25390        final IIntentReceiver finishedReceiver, final int[] userIds);
25391    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25392        boolean includeStopped, int appId, int... userIds);
25393}
25394