PackageManagerService.java revision 1d875ad3ae5bb27016f9650b5bf4c39c08b6570e
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.os.storage.StorageManager.FLAG_STORAGE_CE;
89import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
90import static android.system.OsConstants.O_CREAT;
91import static android.system.OsConstants.O_RDWR;
92
93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
94import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
95import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
96import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
97import static com.android.internal.util.ArrayUtils.appendInt;
98import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
100import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
101import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
102import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
103import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
104import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
106import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
107import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
108
109import android.Manifest;
110import android.annotation.IntDef;
111import android.annotation.NonNull;
112import android.annotation.Nullable;
113import android.app.ActivityManager;
114import android.app.AppOpsManager;
115import android.app.IActivityManager;
116import android.app.ResourcesManager;
117import android.app.admin.IDevicePolicyManager;
118import android.app.admin.SecurityLog;
119import android.app.backup.IBackupManager;
120import android.content.BroadcastReceiver;
121import android.content.ComponentName;
122import android.content.ContentResolver;
123import android.content.Context;
124import android.content.IIntentReceiver;
125import android.content.Intent;
126import android.content.IntentFilter;
127import android.content.IntentSender;
128import android.content.IntentSender.SendIntentException;
129import android.content.ServiceConnection;
130import android.content.pm.ActivityInfo;
131import android.content.pm.ApplicationInfo;
132import android.content.pm.AppsQueryHelper;
133import android.content.pm.AuxiliaryResolveInfo;
134import android.content.pm.ChangedPackages;
135import android.content.pm.ComponentInfo;
136import android.content.pm.FallbackCategoryProvider;
137import android.content.pm.FeatureInfo;
138import android.content.pm.IDexModuleRegisterCallback;
139import android.content.pm.IOnPermissionsChangeListener;
140import android.content.pm.IPackageDataObserver;
141import android.content.pm.IPackageDeleteObserver;
142import android.content.pm.IPackageDeleteObserver2;
143import android.content.pm.IPackageInstallObserver2;
144import android.content.pm.IPackageInstaller;
145import android.content.pm.IPackageManager;
146import android.content.pm.IPackageManagerNative;
147import android.content.pm.IPackageMoveObserver;
148import android.content.pm.IPackageStatsObserver;
149import android.content.pm.InstantAppInfo;
150import android.content.pm.InstantAppRequest;
151import android.content.pm.InstantAppResolveInfo;
152import android.content.pm.InstrumentationInfo;
153import android.content.pm.IntentFilterVerificationInfo;
154import android.content.pm.KeySet;
155import android.content.pm.PackageCleanItem;
156import android.content.pm.PackageInfo;
157import android.content.pm.PackageInfoLite;
158import android.content.pm.PackageInstaller;
159import android.content.pm.PackageManager;
160import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
161import android.content.pm.PackageManagerInternal;
162import android.content.pm.PackageParser;
163import android.content.pm.PackageParser.ActivityIntentInfo;
164import android.content.pm.PackageParser.PackageLite;
165import android.content.pm.PackageParser.PackageParserException;
166import android.content.pm.PackageStats;
167import android.content.pm.PackageUserState;
168import android.content.pm.ParceledListSlice;
169import android.content.pm.PermissionGroupInfo;
170import android.content.pm.PermissionInfo;
171import android.content.pm.ProviderInfo;
172import android.content.pm.ResolveInfo;
173import android.content.pm.ServiceInfo;
174import android.content.pm.SharedLibraryInfo;
175import android.content.pm.Signature;
176import android.content.pm.UserInfo;
177import android.content.pm.VerifierDeviceIdentity;
178import android.content.pm.VerifierInfo;
179import android.content.pm.VersionedPackage;
180import android.content.pm.dex.IArtManager;
181import android.content.res.Resources;
182import android.database.ContentObserver;
183import android.graphics.Bitmap;
184import android.hardware.display.DisplayManager;
185import android.net.Uri;
186import android.os.Binder;
187import android.os.Build;
188import android.os.Bundle;
189import android.os.Debug;
190import android.os.Environment;
191import android.os.Environment.UserEnvironment;
192import android.os.FileUtils;
193import android.os.Handler;
194import android.os.IBinder;
195import android.os.Looper;
196import android.os.Message;
197import android.os.Parcel;
198import android.os.ParcelFileDescriptor;
199import android.os.PatternMatcher;
200import android.os.Process;
201import android.os.RemoteCallbackList;
202import android.os.RemoteException;
203import android.os.ResultReceiver;
204import android.os.SELinux;
205import android.os.ServiceManager;
206import android.os.ShellCallback;
207import android.os.SystemClock;
208import android.os.SystemProperties;
209import android.os.Trace;
210import android.os.UserHandle;
211import android.os.UserManager;
212import android.os.UserManagerInternal;
213import android.os.storage.IStorageManager;
214import android.os.storage.StorageEventListener;
215import android.os.storage.StorageManager;
216import android.os.storage.StorageManagerInternal;
217import android.os.storage.VolumeInfo;
218import android.os.storage.VolumeRecord;
219import android.provider.Settings.Global;
220import android.provider.Settings.Secure;
221import android.security.KeyStore;
222import android.security.SystemKeyStore;
223import android.service.pm.PackageServiceDumpProto;
224import android.system.ErrnoException;
225import android.system.Os;
226import android.text.TextUtils;
227import android.text.format.DateUtils;
228import android.util.ArrayMap;
229import android.util.ArraySet;
230import android.util.Base64;
231import android.util.TimingsTraceLog;
232import android.util.DisplayMetrics;
233import android.util.EventLog;
234import android.util.ExceptionUtils;
235import android.util.Log;
236import android.util.LogPrinter;
237import android.util.MathUtils;
238import android.util.PackageUtils;
239import android.util.Pair;
240import android.util.PrintStreamPrinter;
241import android.util.Slog;
242import android.util.SparseArray;
243import android.util.SparseBooleanArray;
244import android.util.SparseIntArray;
245import android.util.Xml;
246import android.util.jar.StrictJarFile;
247import android.util.proto.ProtoOutputStream;
248import android.view.Display;
249
250import com.android.internal.R;
251import com.android.internal.annotations.GuardedBy;
252import com.android.internal.app.IMediaContainerService;
253import com.android.internal.app.ResolverActivity;
254import com.android.internal.content.NativeLibraryHelper;
255import com.android.internal.content.PackageHelper;
256import com.android.internal.logging.MetricsLogger;
257import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
258import com.android.internal.os.IParcelFileDescriptorFactory;
259import com.android.internal.os.RoSystemProperties;
260import com.android.internal.os.SomeArgs;
261import com.android.internal.os.Zygote;
262import com.android.internal.telephony.CarrierAppUtils;
263import com.android.internal.util.ArrayUtils;
264import com.android.internal.util.ConcurrentUtils;
265import com.android.internal.util.DumpUtils;
266import com.android.internal.util.FastPrintWriter;
267import com.android.internal.util.FastXmlSerializer;
268import com.android.internal.util.IndentingPrintWriter;
269import com.android.internal.util.Preconditions;
270import com.android.internal.util.XmlUtils;
271import com.android.server.AttributeCache;
272import com.android.server.DeviceIdleController;
273import com.android.server.EventLogTags;
274import com.android.server.FgThread;
275import com.android.server.IntentResolver;
276import com.android.server.LocalServices;
277import com.android.server.LockGuard;
278import com.android.server.ServiceThread;
279import com.android.server.SystemConfig;
280import com.android.server.SystemServerInitThreadPool;
281import com.android.server.Watchdog;
282import com.android.server.net.NetworkPolicyManagerInternal;
283import com.android.server.pm.Installer.InstallerException;
284import com.android.server.pm.PermissionsState.PermissionState;
285import com.android.server.pm.Settings.DatabaseVersion;
286import com.android.server.pm.Settings.VersionInfo;
287import com.android.server.pm.dex.ArtManagerService;
288import com.android.server.pm.dex.DexLogger;
289import com.android.server.pm.dex.DexManager;
290import com.android.server.pm.dex.DexoptOptions;
291import com.android.server.pm.dex.PackageDexUsage;
292import com.android.server.storage.DeviceStorageMonitorInternal;
293
294import dalvik.system.CloseGuard;
295import dalvik.system.VMRuntime;
296
297import libcore.io.IoUtils;
298import libcore.io.Streams;
299import libcore.util.EmptyArray;
300
301import org.xmlpull.v1.XmlPullParser;
302import org.xmlpull.v1.XmlPullParserException;
303import org.xmlpull.v1.XmlSerializer;
304
305import java.io.BufferedOutputStream;
306import java.io.BufferedReader;
307import java.io.ByteArrayInputStream;
308import java.io.ByteArrayOutputStream;
309import java.io.File;
310import java.io.FileDescriptor;
311import java.io.FileInputStream;
312import java.io.FileOutputStream;
313import java.io.FileReader;
314import java.io.FilenameFilter;
315import java.io.IOException;
316import java.io.InputStream;
317import java.io.OutputStream;
318import java.io.PrintWriter;
319import java.lang.annotation.Retention;
320import java.lang.annotation.RetentionPolicy;
321import java.nio.charset.StandardCharsets;
322import java.security.DigestInputStream;
323import java.security.MessageDigest;
324import java.security.NoSuchAlgorithmException;
325import java.security.PublicKey;
326import java.security.SecureRandom;
327import java.security.cert.Certificate;
328import java.security.cert.CertificateEncodingException;
329import java.security.cert.CertificateException;
330import java.text.SimpleDateFormat;
331import java.util.ArrayList;
332import java.util.Arrays;
333import java.util.Collection;
334import java.util.Collections;
335import java.util.Comparator;
336import java.util.Date;
337import java.util.HashMap;
338import java.util.HashSet;
339import java.util.Iterator;
340import java.util.LinkedHashSet;
341import java.util.List;
342import java.util.Map;
343import java.util.Objects;
344import java.util.Set;
345import java.util.concurrent.CountDownLatch;
346import java.util.concurrent.Future;
347import java.util.concurrent.TimeUnit;
348import java.util.concurrent.atomic.AtomicBoolean;
349import java.util.concurrent.atomic.AtomicInteger;
350import java.util.zip.GZIPInputStream;
351
352/**
353 * Keep track of all those APKs everywhere.
354 * <p>
355 * Internally there are two important locks:
356 * <ul>
357 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
358 * and other related state. It is a fine-grained lock that should only be held
359 * momentarily, as it's one of the most contended locks in the system.
360 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
361 * operations typically involve heavy lifting of application data on disk. Since
362 * {@code installd} is single-threaded, and it's operations can often be slow,
363 * this lock should never be acquired while already holding {@link #mPackages}.
364 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
365 * holding {@link #mInstallLock}.
366 * </ul>
367 * Many internal methods rely on the caller to hold the appropriate locks, and
368 * this contract is expressed through method name suffixes:
369 * <ul>
370 * <li>fooLI(): the caller must hold {@link #mInstallLock}
371 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
372 * being modified must be frozen
373 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
374 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
375 * </ul>
376 * <p>
377 * Because this class is very central to the platform's security; please run all
378 * CTS and unit tests whenever making modifications:
379 *
380 * <pre>
381 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
382 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
383 * </pre>
384 */
385public class PackageManagerService extends IPackageManager.Stub
386        implements PackageSender {
387    static final String TAG = "PackageManager";
388    static final boolean DEBUG_SETTINGS = false;
389    static final boolean DEBUG_PREFERRED = false;
390    static final boolean DEBUG_UPGRADE = false;
391    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
392    private static final boolean DEBUG_BACKUP = false;
393    private static final boolean DEBUG_INSTALL = false;
394    private static final boolean DEBUG_REMOVE = false;
395    private static final boolean DEBUG_BROADCASTS = false;
396    private static final boolean DEBUG_SHOW_INFO = false;
397    private static final boolean DEBUG_PACKAGE_INFO = false;
398    private static final boolean DEBUG_INTENT_MATCHING = false;
399    private static final boolean DEBUG_PACKAGE_SCANNING = false;
400    private static final boolean DEBUG_VERIFY = false;
401    private static final boolean DEBUG_FILTERS = false;
402    private static final boolean DEBUG_PERMISSIONS = false;
403    private static final boolean DEBUG_SHARED_LIBRARIES = false;
404    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
405
406    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
407    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
408    // user, but by default initialize to this.
409    public static final boolean DEBUG_DEXOPT = false;
410
411    private static final boolean DEBUG_ABI_SELECTION = false;
412    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
413    private static final boolean DEBUG_TRIAGED_MISSING = false;
414    private static final boolean DEBUG_APP_DATA = false;
415
416    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
417    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
418
419    private static final boolean HIDE_EPHEMERAL_APIS = false;
420
421    private static final boolean ENABLE_FREE_CACHE_V2 =
422            SystemProperties.getBoolean("fw.free_cache_v2", true);
423
424    private static final int RADIO_UID = Process.PHONE_UID;
425    private static final int LOG_UID = Process.LOG_UID;
426    private static final int NFC_UID = Process.NFC_UID;
427    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
428    private static final int SHELL_UID = Process.SHELL_UID;
429    private static final int SE_UID = Process.SE_UID;
430
431    // Cap the size of permission trees that 3rd party apps can define
432    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
433
434    // Suffix used during package installation when copying/moving
435    // package apks to install directory.
436    private static final String INSTALL_PACKAGE_SUFFIX = "-";
437
438    static final int SCAN_NO_DEX = 1<<1;
439    static final int SCAN_FORCE_DEX = 1<<2;
440    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
441    static final int SCAN_NEW_INSTALL = 1<<4;
442    static final int SCAN_UPDATE_TIME = 1<<5;
443    static final int SCAN_BOOTING = 1<<6;
444    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
445    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
446    static final int SCAN_REPLACING = 1<<9;
447    static final int SCAN_REQUIRE_KNOWN = 1<<10;
448    static final int SCAN_MOVE = 1<<11;
449    static final int SCAN_INITIAL = 1<<12;
450    static final int SCAN_CHECK_ONLY = 1<<13;
451    static final int SCAN_DONT_KILL_APP = 1<<14;
452    static final int SCAN_IGNORE_FROZEN = 1<<15;
453    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
454    static final int SCAN_AS_INSTANT_APP = 1<<17;
455    static final int SCAN_AS_FULL_APP = 1<<18;
456    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
457    /** Should not be with the scan flags */
458    static final int FLAGS_REMOVE_CHATTY = 1<<31;
459
460    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
461    /** Extension of the compressed packages */
462    private final static String COMPRESSED_EXTENSION = ".gz";
463    /** Suffix of stub packages on the system partition */
464    private final static String STUB_SUFFIX = "-Stub";
465
466    private static final int[] EMPTY_INT_ARRAY = new int[0];
467
468    private static final int TYPE_UNKNOWN = 0;
469    private static final int TYPE_ACTIVITY = 1;
470    private static final int TYPE_RECEIVER = 2;
471    private static final int TYPE_SERVICE = 3;
472    private static final int TYPE_PROVIDER = 4;
473    @IntDef(prefix = { "TYPE_" }, value = {
474            TYPE_UNKNOWN,
475            TYPE_ACTIVITY,
476            TYPE_RECEIVER,
477            TYPE_SERVICE,
478            TYPE_PROVIDER,
479    })
480    @Retention(RetentionPolicy.SOURCE)
481    public @interface ComponentType {}
482
483    /**
484     * Timeout (in milliseconds) after which the watchdog should declare that
485     * our handler thread is wedged.  The usual default for such things is one
486     * minute but we sometimes do very lengthy I/O operations on this thread,
487     * such as installing multi-gigabyte applications, so ours needs to be longer.
488     */
489    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
490
491    /**
492     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
493     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
494     * settings entry if available, otherwise we use the hardcoded default.  If it's been
495     * more than this long since the last fstrim, we force one during the boot sequence.
496     *
497     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
498     * one gets run at the next available charging+idle time.  This final mandatory
499     * no-fstrim check kicks in only of the other scheduling criteria is never met.
500     */
501    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
502
503    /**
504     * Whether verification is enabled by default.
505     */
506    private static final boolean DEFAULT_VERIFY_ENABLE = true;
507
508    /**
509     * The default maximum time to wait for the verification agent to return in
510     * milliseconds.
511     */
512    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
513
514    /**
515     * The default response for package verification timeout.
516     *
517     * This can be either PackageManager.VERIFICATION_ALLOW or
518     * PackageManager.VERIFICATION_REJECT.
519     */
520    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
521
522    static final String PLATFORM_PACKAGE_NAME = "android";
523
524    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
525
526    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
527            DEFAULT_CONTAINER_PACKAGE,
528            "com.android.defcontainer.DefaultContainerService");
529
530    private static final String KILL_APP_REASON_GIDS_CHANGED =
531            "permission grant or revoke changed gids";
532
533    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
534            "permissions revoked";
535
536    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
537
538    private static final String PACKAGE_SCHEME = "package";
539
540    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
541
542    /** Permission grant: not grant the permission. */
543    private static final int GRANT_DENIED = 1;
544
545    /** Permission grant: grant the permission as an install permission. */
546    private static final int GRANT_INSTALL = 2;
547
548    /** Permission grant: grant the permission as a runtime one. */
549    private static final int GRANT_RUNTIME = 3;
550
551    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
552    private static final int GRANT_UPGRADE = 4;
553
554    /** Canonical intent used to identify what counts as a "web browser" app */
555    private static final Intent sBrowserIntent;
556    static {
557        sBrowserIntent = new Intent();
558        sBrowserIntent.setAction(Intent.ACTION_VIEW);
559        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
560        sBrowserIntent.setData(Uri.parse("http:"));
561    }
562
563    /**
564     * The set of all protected actions [i.e. those actions for which a high priority
565     * intent filter is disallowed].
566     */
567    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
568    static {
569        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
570        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
571        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
572        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
573    }
574
575    // Compilation reasons.
576    public static final int REASON_FIRST_BOOT = 0;
577    public static final int REASON_BOOT = 1;
578    public static final int REASON_INSTALL = 2;
579    public static final int REASON_BACKGROUND_DEXOPT = 3;
580    public static final int REASON_AB_OTA = 4;
581    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
582    public static final int REASON_SHARED = 6;
583
584    public static final int REASON_LAST = REASON_SHARED;
585
586    /** All dangerous permission names in the same order as the events in MetricsEvent */
587    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
588            Manifest.permission.READ_CALENDAR,
589            Manifest.permission.WRITE_CALENDAR,
590            Manifest.permission.CAMERA,
591            Manifest.permission.READ_CONTACTS,
592            Manifest.permission.WRITE_CONTACTS,
593            Manifest.permission.GET_ACCOUNTS,
594            Manifest.permission.ACCESS_FINE_LOCATION,
595            Manifest.permission.ACCESS_COARSE_LOCATION,
596            Manifest.permission.RECORD_AUDIO,
597            Manifest.permission.READ_PHONE_STATE,
598            Manifest.permission.CALL_PHONE,
599            Manifest.permission.READ_CALL_LOG,
600            Manifest.permission.WRITE_CALL_LOG,
601            Manifest.permission.ADD_VOICEMAIL,
602            Manifest.permission.USE_SIP,
603            Manifest.permission.PROCESS_OUTGOING_CALLS,
604            Manifest.permission.READ_CELL_BROADCASTS,
605            Manifest.permission.BODY_SENSORS,
606            Manifest.permission.SEND_SMS,
607            Manifest.permission.RECEIVE_SMS,
608            Manifest.permission.READ_SMS,
609            Manifest.permission.RECEIVE_WAP_PUSH,
610            Manifest.permission.RECEIVE_MMS,
611            Manifest.permission.READ_EXTERNAL_STORAGE,
612            Manifest.permission.WRITE_EXTERNAL_STORAGE,
613            Manifest.permission.READ_PHONE_NUMBERS,
614            Manifest.permission.ANSWER_PHONE_CALLS,
615            Manifest.permission.ACCEPT_HANDOVER);
616
617
618    /**
619     * Version number for the package parser cache. Increment this whenever the format or
620     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
621     */
622    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
623
624    /**
625     * Whether the package parser cache is enabled.
626     */
627    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
628
629    final ServiceThread mHandlerThread;
630
631    final PackageHandler mHandler;
632
633    private final ProcessLoggingHandler mProcessLoggingHandler;
634
635    /**
636     * Messages for {@link #mHandler} that need to wait for system ready before
637     * being dispatched.
638     */
639    private ArrayList<Message> mPostSystemReadyMessages;
640
641    final int mSdkVersion = Build.VERSION.SDK_INT;
642
643    final Context mContext;
644    final boolean mFactoryTest;
645    final boolean mOnlyCore;
646    final DisplayMetrics mMetrics;
647    final int mDefParseFlags;
648    final String[] mSeparateProcesses;
649    final boolean mIsUpgrade;
650    final boolean mIsPreNUpgrade;
651    final boolean mIsPreNMR1Upgrade;
652
653    // Have we told the Activity Manager to whitelist the default container service by uid yet?
654    @GuardedBy("mPackages")
655    boolean mDefaultContainerWhitelisted = false;
656
657    @GuardedBy("mPackages")
658    private boolean mDexOptDialogShown;
659
660    /** The location for ASEC container files on internal storage. */
661    final String mAsecInternalPath;
662
663    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
664    // LOCK HELD.  Can be called with mInstallLock held.
665    @GuardedBy("mInstallLock")
666    final Installer mInstaller;
667
668    /** Directory where installed third-party apps stored */
669    final File mAppInstallDir;
670
671    /**
672     * Directory to which applications installed internally have their
673     * 32 bit native libraries copied.
674     */
675    private File mAppLib32InstallDir;
676
677    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
678    // apps.
679    final File mDrmAppPrivateInstallDir;
680
681    // ----------------------------------------------------------------
682
683    // Lock for state used when installing and doing other long running
684    // operations.  Methods that must be called with this lock held have
685    // the suffix "LI".
686    final Object mInstallLock = new Object();
687
688    // ----------------------------------------------------------------
689
690    // Keys are String (package name), values are Package.  This also serves
691    // as the lock for the global state.  Methods that must be called with
692    // this lock held have the prefix "LP".
693    @GuardedBy("mPackages")
694    final ArrayMap<String, PackageParser.Package> mPackages =
695            new ArrayMap<String, PackageParser.Package>();
696
697    final ArrayMap<String, Set<String>> mKnownCodebase =
698            new ArrayMap<String, Set<String>>();
699
700    // Keys are isolated uids and values are the uid of the application
701    // that created the isolated proccess.
702    @GuardedBy("mPackages")
703    final SparseIntArray mIsolatedOwners = new SparseIntArray();
704
705    /**
706     * Tracks new system packages [received in an OTA] that we expect to
707     * find updated user-installed versions. Keys are package name, values
708     * are package location.
709     */
710    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
711    /**
712     * Tracks high priority intent filters for protected actions. During boot, certain
713     * filter actions are protected and should never be allowed to have a high priority
714     * intent filter for them. However, there is one, and only one exception -- the
715     * setup wizard. It must be able to define a high priority intent filter for these
716     * actions to ensure there are no escapes from the wizard. We need to delay processing
717     * of these during boot as we need to look at all of the system packages in order
718     * to know which component is the setup wizard.
719     */
720    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
721    /**
722     * Whether or not processing protected filters should be deferred.
723     */
724    private boolean mDeferProtectedFilters = true;
725
726    /**
727     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
728     */
729    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
730    /**
731     * Whether or not system app permissions should be promoted from install to runtime.
732     */
733    boolean mPromoteSystemApps;
734
735    @GuardedBy("mPackages")
736    final Settings mSettings;
737
738    /**
739     * Set of package names that are currently "frozen", which means active
740     * surgery is being done on the code/data for that package. The platform
741     * will refuse to launch frozen packages to avoid race conditions.
742     *
743     * @see PackageFreezer
744     */
745    @GuardedBy("mPackages")
746    final ArraySet<String> mFrozenPackages = new ArraySet<>();
747
748    final ProtectedPackages mProtectedPackages;
749
750    @GuardedBy("mLoadedVolumes")
751    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
752
753    boolean mFirstBoot;
754
755    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
756
757    // System configuration read by SystemConfig.
758    final int[] mGlobalGids;
759    final SparseArray<ArraySet<String>> mSystemPermissions;
760    @GuardedBy("mAvailableFeatures")
761    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
762
763    // If mac_permissions.xml was found for seinfo labeling.
764    boolean mFoundPolicyFile;
765
766    private final InstantAppRegistry mInstantAppRegistry;
767
768    @GuardedBy("mPackages")
769    int mChangedPackagesSequenceNumber;
770    /**
771     * List of changed [installed, removed or updated] packages.
772     * mapping from user id -> sequence number -> package name
773     */
774    @GuardedBy("mPackages")
775    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
776    /**
777     * The sequence number of the last change to a package.
778     * mapping from user id -> package name -> sequence number
779     */
780    @GuardedBy("mPackages")
781    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
782
783    class PackageParserCallback implements PackageParser.Callback {
784        @Override public final boolean hasFeature(String feature) {
785            return PackageManagerService.this.hasSystemFeature(feature, 0);
786        }
787
788        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
789                Collection<PackageParser.Package> allPackages, String targetPackageName) {
790            List<PackageParser.Package> overlayPackages = null;
791            for (PackageParser.Package p : allPackages) {
792                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
793                    if (overlayPackages == null) {
794                        overlayPackages = new ArrayList<PackageParser.Package>();
795                    }
796                    overlayPackages.add(p);
797                }
798            }
799            if (overlayPackages != null) {
800                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
801                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
802                        return p1.mOverlayPriority - p2.mOverlayPriority;
803                    }
804                };
805                Collections.sort(overlayPackages, cmp);
806            }
807            return overlayPackages;
808        }
809
810        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
811                String targetPackageName, String targetPath) {
812            if ("android".equals(targetPackageName)) {
813                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
814                // native AssetManager.
815                return null;
816            }
817            List<PackageParser.Package> overlayPackages =
818                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
819            if (overlayPackages == null || overlayPackages.isEmpty()) {
820                return null;
821            }
822            List<String> overlayPathList = null;
823            for (PackageParser.Package overlayPackage : overlayPackages) {
824                if (targetPath == null) {
825                    if (overlayPathList == null) {
826                        overlayPathList = new ArrayList<String>();
827                    }
828                    overlayPathList.add(overlayPackage.baseCodePath);
829                    continue;
830                }
831
832                try {
833                    // Creates idmaps for system to parse correctly the Android manifest of the
834                    // target package.
835                    //
836                    // OverlayManagerService will update each of them with a correct gid from its
837                    // target package app id.
838                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
839                            UserHandle.getSharedAppGid(
840                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
841                    if (overlayPathList == null) {
842                        overlayPathList = new ArrayList<String>();
843                    }
844                    overlayPathList.add(overlayPackage.baseCodePath);
845                } catch (InstallerException e) {
846                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
847                            overlayPackage.baseCodePath);
848                }
849            }
850            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
851        }
852
853        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
854            synchronized (mPackages) {
855                return getStaticOverlayPathsLocked(
856                        mPackages.values(), targetPackageName, targetPath);
857            }
858        }
859
860        @Override public final String[] getOverlayApks(String targetPackageName) {
861            return getStaticOverlayPaths(targetPackageName, null);
862        }
863
864        @Override public final String[] getOverlayPaths(String targetPackageName,
865                String targetPath) {
866            return getStaticOverlayPaths(targetPackageName, targetPath);
867        }
868    };
869
870    class ParallelPackageParserCallback extends PackageParserCallback {
871        List<PackageParser.Package> mOverlayPackages = null;
872
873        void findStaticOverlayPackages() {
874            synchronized (mPackages) {
875                for (PackageParser.Package p : mPackages.values()) {
876                    if (p.mIsStaticOverlay) {
877                        if (mOverlayPackages == null) {
878                            mOverlayPackages = new ArrayList<PackageParser.Package>();
879                        }
880                        mOverlayPackages.add(p);
881                    }
882                }
883            }
884        }
885
886        @Override
887        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
888            // We can trust mOverlayPackages without holding mPackages because package uninstall
889            // can't happen while running parallel parsing.
890            // Moreover holding mPackages on each parsing thread causes dead-lock.
891            return mOverlayPackages == null ? null :
892                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
893        }
894    }
895
896    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
897    final ParallelPackageParserCallback mParallelPackageParserCallback =
898            new ParallelPackageParserCallback();
899
900    public static final class SharedLibraryEntry {
901        public final @Nullable String path;
902        public final @Nullable String apk;
903        public final @NonNull SharedLibraryInfo info;
904
905        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
906                String declaringPackageName, int declaringPackageVersionCode) {
907            path = _path;
908            apk = _apk;
909            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
910                    declaringPackageName, declaringPackageVersionCode), null);
911        }
912    }
913
914    // Currently known shared libraries.
915    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
916    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
917            new ArrayMap<>();
918
919    // All available activities, for your resolving pleasure.
920    final ActivityIntentResolver mActivities =
921            new ActivityIntentResolver();
922
923    // All available receivers, for your resolving pleasure.
924    final ActivityIntentResolver mReceivers =
925            new ActivityIntentResolver();
926
927    // All available services, for your resolving pleasure.
928    final ServiceIntentResolver mServices = new ServiceIntentResolver();
929
930    // All available providers, for your resolving pleasure.
931    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
932
933    // Mapping from provider base names (first directory in content URI codePath)
934    // to the provider information.
935    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
936            new ArrayMap<String, PackageParser.Provider>();
937
938    // Mapping from instrumentation class names to info about them.
939    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
940            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
941
942    // Mapping from permission names to info about them.
943    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
944            new ArrayMap<String, PackageParser.PermissionGroup>();
945
946    // Packages whose data we have transfered into another package, thus
947    // should no longer exist.
948    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
949
950    // Broadcast actions that are only available to the system.
951    @GuardedBy("mProtectedBroadcasts")
952    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
953
954    /** List of packages waiting for verification. */
955    final SparseArray<PackageVerificationState> mPendingVerification
956            = new SparseArray<PackageVerificationState>();
957
958    /** Set of packages associated with each app op permission. */
959    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
960
961    final PackageInstallerService mInstallerService;
962
963    final ArtManagerService mArtManagerService;
964
965    private final PackageDexOptimizer mPackageDexOptimizer;
966    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
967    // is used by other apps).
968    private final DexManager mDexManager;
969
970    private AtomicInteger mNextMoveId = new AtomicInteger();
971    private final MoveCallbacks mMoveCallbacks;
972
973    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
974
975    // Cache of users who need badging.
976    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
977
978    /** Token for keys in mPendingVerification. */
979    private int mPendingVerificationToken = 0;
980
981    volatile boolean mSystemReady;
982    volatile boolean mSafeMode;
983    volatile boolean mHasSystemUidErrors;
984    private volatile boolean mEphemeralAppsDisabled;
985
986    ApplicationInfo mAndroidApplication;
987    final ActivityInfo mResolveActivity = new ActivityInfo();
988    final ResolveInfo mResolveInfo = new ResolveInfo();
989    ComponentName mResolveComponentName;
990    PackageParser.Package mPlatformPackage;
991    ComponentName mCustomResolverComponentName;
992
993    boolean mResolverReplaced = false;
994
995    private final @Nullable ComponentName mIntentFilterVerifierComponent;
996    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
997
998    private int mIntentFilterVerificationToken = 0;
999
1000    /** The service connection to the ephemeral resolver */
1001    final EphemeralResolverConnection mInstantAppResolverConnection;
1002    /** Component used to show resolver settings for Instant Apps */
1003    final ComponentName mInstantAppResolverSettingsComponent;
1004
1005    /** Activity used to install instant applications */
1006    ActivityInfo mInstantAppInstallerActivity;
1007    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1008
1009    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1010            = new SparseArray<IntentFilterVerificationState>();
1011
1012    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1013
1014    // List of packages names to keep cached, even if they are uninstalled for all users
1015    private List<String> mKeepUninstalledPackages;
1016
1017    private UserManagerInternal mUserManagerInternal;
1018
1019    private DeviceIdleController.LocalService mDeviceIdleController;
1020
1021    private File mCacheDir;
1022
1023    private ArraySet<String> mPrivappPermissionsViolations;
1024
1025    private Future<?> mPrepareAppDataFuture;
1026
1027    private static class IFVerificationParams {
1028        PackageParser.Package pkg;
1029        boolean replacing;
1030        int userId;
1031        int verifierUid;
1032
1033        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1034                int _userId, int _verifierUid) {
1035            pkg = _pkg;
1036            replacing = _replacing;
1037            userId = _userId;
1038            replacing = _replacing;
1039            verifierUid = _verifierUid;
1040        }
1041    }
1042
1043    private interface IntentFilterVerifier<T extends IntentFilter> {
1044        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1045                                               T filter, String packageName);
1046        void startVerifications(int userId);
1047        void receiveVerificationResponse(int verificationId);
1048    }
1049
1050    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1051        private Context mContext;
1052        private ComponentName mIntentFilterVerifierComponent;
1053        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1054
1055        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1056            mContext = context;
1057            mIntentFilterVerifierComponent = verifierComponent;
1058        }
1059
1060        private String getDefaultScheme() {
1061            return IntentFilter.SCHEME_HTTPS;
1062        }
1063
1064        @Override
1065        public void startVerifications(int userId) {
1066            // Launch verifications requests
1067            int count = mCurrentIntentFilterVerifications.size();
1068            for (int n=0; n<count; n++) {
1069                int verificationId = mCurrentIntentFilterVerifications.get(n);
1070                final IntentFilterVerificationState ivs =
1071                        mIntentFilterVerificationStates.get(verificationId);
1072
1073                String packageName = ivs.getPackageName();
1074
1075                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1076                final int filterCount = filters.size();
1077                ArraySet<String> domainsSet = new ArraySet<>();
1078                for (int m=0; m<filterCount; m++) {
1079                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1080                    domainsSet.addAll(filter.getHostsList());
1081                }
1082                synchronized (mPackages) {
1083                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1084                            packageName, domainsSet) != null) {
1085                        scheduleWriteSettingsLocked();
1086                    }
1087                }
1088                sendVerificationRequest(verificationId, ivs);
1089            }
1090            mCurrentIntentFilterVerifications.clear();
1091        }
1092
1093        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1094            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1095            verificationIntent.putExtra(
1096                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1097                    verificationId);
1098            verificationIntent.putExtra(
1099                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1100                    getDefaultScheme());
1101            verificationIntent.putExtra(
1102                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1103                    ivs.getHostsString());
1104            verificationIntent.putExtra(
1105                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1106                    ivs.getPackageName());
1107            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1108            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1109
1110            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1111            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1112                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1113                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1114
1115            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1116            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1117                    "Sending IntentFilter verification broadcast");
1118        }
1119
1120        public void receiveVerificationResponse(int verificationId) {
1121            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1122
1123            final boolean verified = ivs.isVerified();
1124
1125            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1126            final int count = filters.size();
1127            if (DEBUG_DOMAIN_VERIFICATION) {
1128                Slog.i(TAG, "Received verification response " + verificationId
1129                        + " for " + count + " filters, verified=" + verified);
1130            }
1131            for (int n=0; n<count; n++) {
1132                PackageParser.ActivityIntentInfo filter = filters.get(n);
1133                filter.setVerified(verified);
1134
1135                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1136                        + " verified with result:" + verified + " and hosts:"
1137                        + ivs.getHostsString());
1138            }
1139
1140            mIntentFilterVerificationStates.remove(verificationId);
1141
1142            final String packageName = ivs.getPackageName();
1143            IntentFilterVerificationInfo ivi = null;
1144
1145            synchronized (mPackages) {
1146                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1147            }
1148            if (ivi == null) {
1149                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1150                        + verificationId + " packageName:" + packageName);
1151                return;
1152            }
1153            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1154                    "Updating IntentFilterVerificationInfo for package " + packageName
1155                            +" verificationId:" + verificationId);
1156
1157            synchronized (mPackages) {
1158                if (verified) {
1159                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1160                } else {
1161                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1162                }
1163                scheduleWriteSettingsLocked();
1164
1165                final int userId = ivs.getUserId();
1166                if (userId != UserHandle.USER_ALL) {
1167                    final int userStatus =
1168                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1169
1170                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1171                    boolean needUpdate = false;
1172
1173                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1174                    // already been set by the User thru the Disambiguation dialog
1175                    switch (userStatus) {
1176                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1177                            if (verified) {
1178                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1179                            } else {
1180                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1181                            }
1182                            needUpdate = true;
1183                            break;
1184
1185                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1186                            if (verified) {
1187                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1188                                needUpdate = true;
1189                            }
1190                            break;
1191
1192                        default:
1193                            // Nothing to do
1194                    }
1195
1196                    if (needUpdate) {
1197                        mSettings.updateIntentFilterVerificationStatusLPw(
1198                                packageName, updatedStatus, userId);
1199                        scheduleWritePackageRestrictionsLocked(userId);
1200                    }
1201                }
1202            }
1203        }
1204
1205        @Override
1206        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1207                    ActivityIntentInfo filter, String packageName) {
1208            if (!hasValidDomains(filter)) {
1209                return false;
1210            }
1211            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1212            if (ivs == null) {
1213                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1214                        packageName);
1215            }
1216            if (DEBUG_DOMAIN_VERIFICATION) {
1217                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1218            }
1219            ivs.addFilter(filter);
1220            return true;
1221        }
1222
1223        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1224                int userId, int verificationId, String packageName) {
1225            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1226                    verifierUid, userId, packageName);
1227            ivs.setPendingState();
1228            synchronized (mPackages) {
1229                mIntentFilterVerificationStates.append(verificationId, ivs);
1230                mCurrentIntentFilterVerifications.add(verificationId);
1231            }
1232            return ivs;
1233        }
1234    }
1235
1236    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1237        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1238                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1239                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1240    }
1241
1242    // Set of pending broadcasts for aggregating enable/disable of components.
1243    static class PendingPackageBroadcasts {
1244        // for each user id, a map of <package name -> components within that package>
1245        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1246
1247        public PendingPackageBroadcasts() {
1248            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1249        }
1250
1251        public ArrayList<String> get(int userId, String packageName) {
1252            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1253            return packages.get(packageName);
1254        }
1255
1256        public void put(int userId, String packageName, ArrayList<String> components) {
1257            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1258            packages.put(packageName, components);
1259        }
1260
1261        public void remove(int userId, String packageName) {
1262            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1263            if (packages != null) {
1264                packages.remove(packageName);
1265            }
1266        }
1267
1268        public void remove(int userId) {
1269            mUidMap.remove(userId);
1270        }
1271
1272        public int userIdCount() {
1273            return mUidMap.size();
1274        }
1275
1276        public int userIdAt(int n) {
1277            return mUidMap.keyAt(n);
1278        }
1279
1280        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1281            return mUidMap.get(userId);
1282        }
1283
1284        public int size() {
1285            // total number of pending broadcast entries across all userIds
1286            int num = 0;
1287            for (int i = 0; i< mUidMap.size(); i++) {
1288                num += mUidMap.valueAt(i).size();
1289            }
1290            return num;
1291        }
1292
1293        public void clear() {
1294            mUidMap.clear();
1295        }
1296
1297        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1298            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1299            if (map == null) {
1300                map = new ArrayMap<String, ArrayList<String>>();
1301                mUidMap.put(userId, map);
1302            }
1303            return map;
1304        }
1305    }
1306    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1307
1308    // Service Connection to remote media container service to copy
1309    // package uri's from external media onto secure containers
1310    // or internal storage.
1311    private IMediaContainerService mContainerService = null;
1312
1313    static final int SEND_PENDING_BROADCAST = 1;
1314    static final int MCS_BOUND = 3;
1315    static final int END_COPY = 4;
1316    static final int INIT_COPY = 5;
1317    static final int MCS_UNBIND = 6;
1318    static final int START_CLEANING_PACKAGE = 7;
1319    static final int FIND_INSTALL_LOC = 8;
1320    static final int POST_INSTALL = 9;
1321    static final int MCS_RECONNECT = 10;
1322    static final int MCS_GIVE_UP = 11;
1323    static final int UPDATED_MEDIA_STATUS = 12;
1324    static final int WRITE_SETTINGS = 13;
1325    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1326    static final int PACKAGE_VERIFIED = 15;
1327    static final int CHECK_PENDING_VERIFICATION = 16;
1328    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1329    static final int INTENT_FILTER_VERIFIED = 18;
1330    static final int WRITE_PACKAGE_LIST = 19;
1331    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1332
1333    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1334
1335    // Delay time in millisecs
1336    static final int BROADCAST_DELAY = 10 * 1000;
1337
1338    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1339            2 * 60 * 60 * 1000L; /* two hours */
1340
1341    static UserManagerService sUserManager;
1342
1343    // Stores a list of users whose package restrictions file needs to be updated
1344    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1345
1346    final private DefaultContainerConnection mDefContainerConn =
1347            new DefaultContainerConnection();
1348    class DefaultContainerConnection implements ServiceConnection {
1349        public void onServiceConnected(ComponentName name, IBinder service) {
1350            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1351            final IMediaContainerService imcs = IMediaContainerService.Stub
1352                    .asInterface(Binder.allowBlocking(service));
1353            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1354        }
1355
1356        public void onServiceDisconnected(ComponentName name) {
1357            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1358        }
1359    }
1360
1361    // Recordkeeping of restore-after-install operations that are currently in flight
1362    // between the Package Manager and the Backup Manager
1363    static class PostInstallData {
1364        public InstallArgs args;
1365        public PackageInstalledInfo res;
1366
1367        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1368            args = _a;
1369            res = _r;
1370        }
1371    }
1372
1373    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1374    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1375
1376    // XML tags for backup/restore of various bits of state
1377    private static final String TAG_PREFERRED_BACKUP = "pa";
1378    private static final String TAG_DEFAULT_APPS = "da";
1379    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1380
1381    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1382    private static final String TAG_ALL_GRANTS = "rt-grants";
1383    private static final String TAG_GRANT = "grant";
1384    private static final String ATTR_PACKAGE_NAME = "pkg";
1385
1386    private static final String TAG_PERMISSION = "perm";
1387    private static final String ATTR_PERMISSION_NAME = "name";
1388    private static final String ATTR_IS_GRANTED = "g";
1389    private static final String ATTR_USER_SET = "set";
1390    private static final String ATTR_USER_FIXED = "fixed";
1391    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1392
1393    // System/policy permission grants are not backed up
1394    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1395            FLAG_PERMISSION_POLICY_FIXED
1396            | FLAG_PERMISSION_SYSTEM_FIXED
1397            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1398
1399    // And we back up these user-adjusted states
1400    private static final int USER_RUNTIME_GRANT_MASK =
1401            FLAG_PERMISSION_USER_SET
1402            | FLAG_PERMISSION_USER_FIXED
1403            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1404
1405    final @Nullable String mRequiredVerifierPackage;
1406    final @NonNull String mRequiredInstallerPackage;
1407    final @NonNull String mRequiredUninstallerPackage;
1408    final @Nullable String mSetupWizardPackage;
1409    final @Nullable String mStorageManagerPackage;
1410    final @NonNull String mServicesSystemSharedLibraryPackageName;
1411    final @NonNull String mSharedSystemSharedLibraryPackageName;
1412
1413    final boolean mPermissionReviewRequired;
1414
1415    private final PackageUsage mPackageUsage = new PackageUsage();
1416    private final CompilerStats mCompilerStats = new CompilerStats();
1417
1418    class PackageHandler extends Handler {
1419        private boolean mBound = false;
1420        final ArrayList<HandlerParams> mPendingInstalls =
1421            new ArrayList<HandlerParams>();
1422
1423        private boolean connectToService() {
1424            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1425                    " DefaultContainerService");
1426            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1427            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1428            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1429                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1430                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1431                mBound = true;
1432                return true;
1433            }
1434            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1435            return false;
1436        }
1437
1438        private void disconnectService() {
1439            mContainerService = null;
1440            mBound = false;
1441            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1442            mContext.unbindService(mDefContainerConn);
1443            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1444        }
1445
1446        PackageHandler(Looper looper) {
1447            super(looper);
1448        }
1449
1450        public void handleMessage(Message msg) {
1451            try {
1452                doHandleMessage(msg);
1453            } finally {
1454                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1455            }
1456        }
1457
1458        void doHandleMessage(Message msg) {
1459            switch (msg.what) {
1460                case INIT_COPY: {
1461                    HandlerParams params = (HandlerParams) msg.obj;
1462                    int idx = mPendingInstalls.size();
1463                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1464                    // If a bind was already initiated we dont really
1465                    // need to do anything. The pending install
1466                    // will be processed later on.
1467                    if (!mBound) {
1468                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1469                                System.identityHashCode(mHandler));
1470                        // If this is the only one pending we might
1471                        // have to bind to the service again.
1472                        if (!connectToService()) {
1473                            Slog.e(TAG, "Failed to bind to media container service");
1474                            params.serviceError();
1475                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1476                                    System.identityHashCode(mHandler));
1477                            if (params.traceMethod != null) {
1478                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1479                                        params.traceCookie);
1480                            }
1481                            return;
1482                        } else {
1483                            // Once we bind to the service, the first
1484                            // pending request will be processed.
1485                            mPendingInstalls.add(idx, params);
1486                        }
1487                    } else {
1488                        mPendingInstalls.add(idx, params);
1489                        // Already bound to the service. Just make
1490                        // sure we trigger off processing the first request.
1491                        if (idx == 0) {
1492                            mHandler.sendEmptyMessage(MCS_BOUND);
1493                        }
1494                    }
1495                    break;
1496                }
1497                case MCS_BOUND: {
1498                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1499                    if (msg.obj != null) {
1500                        mContainerService = (IMediaContainerService) msg.obj;
1501                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1502                                System.identityHashCode(mHandler));
1503                    }
1504                    if (mContainerService == null) {
1505                        if (!mBound) {
1506                            // Something seriously wrong since we are not bound and we are not
1507                            // waiting for connection. Bail out.
1508                            Slog.e(TAG, "Cannot bind to media container service");
1509                            for (HandlerParams params : mPendingInstalls) {
1510                                // Indicate service bind error
1511                                params.serviceError();
1512                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1513                                        System.identityHashCode(params));
1514                                if (params.traceMethod != null) {
1515                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1516                                            params.traceMethod, params.traceCookie);
1517                                }
1518                                return;
1519                            }
1520                            mPendingInstalls.clear();
1521                        } else {
1522                            Slog.w(TAG, "Waiting to connect to media container service");
1523                        }
1524                    } else if (mPendingInstalls.size() > 0) {
1525                        HandlerParams params = mPendingInstalls.get(0);
1526                        if (params != null) {
1527                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1528                                    System.identityHashCode(params));
1529                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1530                            if (params.startCopy()) {
1531                                // We are done...  look for more work or to
1532                                // go idle.
1533                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1534                                        "Checking for more work or unbind...");
1535                                // Delete pending install
1536                                if (mPendingInstalls.size() > 0) {
1537                                    mPendingInstalls.remove(0);
1538                                }
1539                                if (mPendingInstalls.size() == 0) {
1540                                    if (mBound) {
1541                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1542                                                "Posting delayed MCS_UNBIND");
1543                                        removeMessages(MCS_UNBIND);
1544                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1545                                        // Unbind after a little delay, to avoid
1546                                        // continual thrashing.
1547                                        sendMessageDelayed(ubmsg, 10000);
1548                                    }
1549                                } else {
1550                                    // There are more pending requests in queue.
1551                                    // Just post MCS_BOUND message to trigger processing
1552                                    // of next pending install.
1553                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1554                                            "Posting MCS_BOUND for next work");
1555                                    mHandler.sendEmptyMessage(MCS_BOUND);
1556                                }
1557                            }
1558                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1559                        }
1560                    } else {
1561                        // Should never happen ideally.
1562                        Slog.w(TAG, "Empty queue");
1563                    }
1564                    break;
1565                }
1566                case MCS_RECONNECT: {
1567                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1568                    if (mPendingInstalls.size() > 0) {
1569                        if (mBound) {
1570                            disconnectService();
1571                        }
1572                        if (!connectToService()) {
1573                            Slog.e(TAG, "Failed to bind to media container service");
1574                            for (HandlerParams params : mPendingInstalls) {
1575                                // Indicate service bind error
1576                                params.serviceError();
1577                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1578                                        System.identityHashCode(params));
1579                            }
1580                            mPendingInstalls.clear();
1581                        }
1582                    }
1583                    break;
1584                }
1585                case MCS_UNBIND: {
1586                    // If there is no actual work left, then time to unbind.
1587                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1588
1589                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1590                        if (mBound) {
1591                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1592
1593                            disconnectService();
1594                        }
1595                    } else if (mPendingInstalls.size() > 0) {
1596                        // There are more pending requests in queue.
1597                        // Just post MCS_BOUND message to trigger processing
1598                        // of next pending install.
1599                        mHandler.sendEmptyMessage(MCS_BOUND);
1600                    }
1601
1602                    break;
1603                }
1604                case MCS_GIVE_UP: {
1605                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1606                    HandlerParams params = mPendingInstalls.remove(0);
1607                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1608                            System.identityHashCode(params));
1609                    break;
1610                }
1611                case SEND_PENDING_BROADCAST: {
1612                    String packages[];
1613                    ArrayList<String> components[];
1614                    int size = 0;
1615                    int uids[];
1616                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1617                    synchronized (mPackages) {
1618                        if (mPendingBroadcasts == null) {
1619                            return;
1620                        }
1621                        size = mPendingBroadcasts.size();
1622                        if (size <= 0) {
1623                            // Nothing to be done. Just return
1624                            return;
1625                        }
1626                        packages = new String[size];
1627                        components = new ArrayList[size];
1628                        uids = new int[size];
1629                        int i = 0;  // filling out the above arrays
1630
1631                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1632                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1633                            Iterator<Map.Entry<String, ArrayList<String>>> it
1634                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1635                                            .entrySet().iterator();
1636                            while (it.hasNext() && i < size) {
1637                                Map.Entry<String, ArrayList<String>> ent = it.next();
1638                                packages[i] = ent.getKey();
1639                                components[i] = ent.getValue();
1640                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1641                                uids[i] = (ps != null)
1642                                        ? UserHandle.getUid(packageUserId, ps.appId)
1643                                        : -1;
1644                                i++;
1645                            }
1646                        }
1647                        size = i;
1648                        mPendingBroadcasts.clear();
1649                    }
1650                    // Send broadcasts
1651                    for (int i = 0; i < size; i++) {
1652                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1653                    }
1654                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1655                    break;
1656                }
1657                case START_CLEANING_PACKAGE: {
1658                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1659                    final String packageName = (String)msg.obj;
1660                    final int userId = msg.arg1;
1661                    final boolean andCode = msg.arg2 != 0;
1662                    synchronized (mPackages) {
1663                        if (userId == UserHandle.USER_ALL) {
1664                            int[] users = sUserManager.getUserIds();
1665                            for (int user : users) {
1666                                mSettings.addPackageToCleanLPw(
1667                                        new PackageCleanItem(user, packageName, andCode));
1668                            }
1669                        } else {
1670                            mSettings.addPackageToCleanLPw(
1671                                    new PackageCleanItem(userId, packageName, andCode));
1672                        }
1673                    }
1674                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1675                    startCleaningPackages();
1676                } break;
1677                case POST_INSTALL: {
1678                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1679
1680                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1681                    final boolean didRestore = (msg.arg2 != 0);
1682                    mRunningInstalls.delete(msg.arg1);
1683
1684                    if (data != null) {
1685                        InstallArgs args = data.args;
1686                        PackageInstalledInfo parentRes = data.res;
1687
1688                        final boolean grantPermissions = (args.installFlags
1689                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1690                        final boolean killApp = (args.installFlags
1691                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1692                        final boolean virtualPreload = ((args.installFlags
1693                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1694                        final String[] grantedPermissions = args.installGrantPermissions;
1695
1696                        // Handle the parent package
1697                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1698                                virtualPreload, grantedPermissions, didRestore,
1699                                args.installerPackageName, args.observer);
1700
1701                        // Handle the child packages
1702                        final int childCount = (parentRes.addedChildPackages != null)
1703                                ? parentRes.addedChildPackages.size() : 0;
1704                        for (int i = 0; i < childCount; i++) {
1705                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1706                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1707                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1708                                    args.installerPackageName, args.observer);
1709                        }
1710
1711                        // Log tracing if needed
1712                        if (args.traceMethod != null) {
1713                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1714                                    args.traceCookie);
1715                        }
1716                    } else {
1717                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1718                    }
1719
1720                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1721                } break;
1722                case UPDATED_MEDIA_STATUS: {
1723                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1724                    boolean reportStatus = msg.arg1 == 1;
1725                    boolean doGc = msg.arg2 == 1;
1726                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1727                    if (doGc) {
1728                        // Force a gc to clear up stale containers.
1729                        Runtime.getRuntime().gc();
1730                    }
1731                    if (msg.obj != null) {
1732                        @SuppressWarnings("unchecked")
1733                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1734                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1735                        // Unload containers
1736                        unloadAllContainers(args);
1737                    }
1738                    if (reportStatus) {
1739                        try {
1740                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1741                                    "Invoking StorageManagerService call back");
1742                            PackageHelper.getStorageManager().finishMediaUpdate();
1743                        } catch (RemoteException e) {
1744                            Log.e(TAG, "StorageManagerService not running?");
1745                        }
1746                    }
1747                } break;
1748                case WRITE_SETTINGS: {
1749                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1750                    synchronized (mPackages) {
1751                        removeMessages(WRITE_SETTINGS);
1752                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1753                        mSettings.writeLPr();
1754                        mDirtyUsers.clear();
1755                    }
1756                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1757                } break;
1758                case WRITE_PACKAGE_RESTRICTIONS: {
1759                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1760                    synchronized (mPackages) {
1761                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1762                        for (int userId : mDirtyUsers) {
1763                            mSettings.writePackageRestrictionsLPr(userId);
1764                        }
1765                        mDirtyUsers.clear();
1766                    }
1767                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1768                } break;
1769                case WRITE_PACKAGE_LIST: {
1770                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1771                    synchronized (mPackages) {
1772                        removeMessages(WRITE_PACKAGE_LIST);
1773                        mSettings.writePackageListLPr(msg.arg1);
1774                    }
1775                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1776                } break;
1777                case CHECK_PENDING_VERIFICATION: {
1778                    final int verificationId = msg.arg1;
1779                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1780
1781                    if ((state != null) && !state.timeoutExtended()) {
1782                        final InstallArgs args = state.getInstallArgs();
1783                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1784
1785                        Slog.i(TAG, "Verification timed out for " + originUri);
1786                        mPendingVerification.remove(verificationId);
1787
1788                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1789
1790                        final UserHandle user = args.getUser();
1791                        if (getDefaultVerificationResponse(user)
1792                                == PackageManager.VERIFICATION_ALLOW) {
1793                            Slog.i(TAG, "Continuing with installation of " + originUri);
1794                            state.setVerifierResponse(Binder.getCallingUid(),
1795                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1796                            broadcastPackageVerified(verificationId, originUri,
1797                                    PackageManager.VERIFICATION_ALLOW, user);
1798                            try {
1799                                ret = args.copyApk(mContainerService, true);
1800                            } catch (RemoteException e) {
1801                                Slog.e(TAG, "Could not contact the ContainerService");
1802                            }
1803                        } else {
1804                            broadcastPackageVerified(verificationId, originUri,
1805                                    PackageManager.VERIFICATION_REJECT, user);
1806                        }
1807
1808                        Trace.asyncTraceEnd(
1809                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1810
1811                        processPendingInstall(args, ret);
1812                        mHandler.sendEmptyMessage(MCS_UNBIND);
1813                    }
1814                    break;
1815                }
1816                case PACKAGE_VERIFIED: {
1817                    final int verificationId = msg.arg1;
1818
1819                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1820                    if (state == null) {
1821                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1822                        break;
1823                    }
1824
1825                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1826
1827                    state.setVerifierResponse(response.callerUid, response.code);
1828
1829                    if (state.isVerificationComplete()) {
1830                        mPendingVerification.remove(verificationId);
1831
1832                        final InstallArgs args = state.getInstallArgs();
1833                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1834
1835                        int ret;
1836                        if (state.isInstallAllowed()) {
1837                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1838                            broadcastPackageVerified(verificationId, originUri,
1839                                    response.code, state.getInstallArgs().getUser());
1840                            try {
1841                                ret = args.copyApk(mContainerService, true);
1842                            } catch (RemoteException e) {
1843                                Slog.e(TAG, "Could not contact the ContainerService");
1844                            }
1845                        } else {
1846                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1847                        }
1848
1849                        Trace.asyncTraceEnd(
1850                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1851
1852                        processPendingInstall(args, ret);
1853                        mHandler.sendEmptyMessage(MCS_UNBIND);
1854                    }
1855
1856                    break;
1857                }
1858                case START_INTENT_FILTER_VERIFICATIONS: {
1859                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1860                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1861                            params.replacing, params.pkg);
1862                    break;
1863                }
1864                case INTENT_FILTER_VERIFIED: {
1865                    final int verificationId = msg.arg1;
1866
1867                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1868                            verificationId);
1869                    if (state == null) {
1870                        Slog.w(TAG, "Invalid IntentFilter verification token "
1871                                + verificationId + " received");
1872                        break;
1873                    }
1874
1875                    final int userId = state.getUserId();
1876
1877                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1878                            "Processing IntentFilter verification with token:"
1879                            + verificationId + " and userId:" + userId);
1880
1881                    final IntentFilterVerificationResponse response =
1882                            (IntentFilterVerificationResponse) msg.obj;
1883
1884                    state.setVerifierResponse(response.callerUid, response.code);
1885
1886                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1887                            "IntentFilter verification with token:" + verificationId
1888                            + " and userId:" + userId
1889                            + " is settings verifier response with response code:"
1890                            + response.code);
1891
1892                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1893                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1894                                + response.getFailedDomainsString());
1895                    }
1896
1897                    if (state.isVerificationComplete()) {
1898                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1899                    } else {
1900                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1901                                "IntentFilter verification with token:" + verificationId
1902                                + " was not said to be complete");
1903                    }
1904
1905                    break;
1906                }
1907                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1908                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1909                            mInstantAppResolverConnection,
1910                            (InstantAppRequest) msg.obj,
1911                            mInstantAppInstallerActivity,
1912                            mHandler);
1913                }
1914            }
1915        }
1916    }
1917
1918    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1919            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1920            boolean launchedForRestore, String installerPackage,
1921            IPackageInstallObserver2 installObserver) {
1922        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1923            // Send the removed broadcasts
1924            if (res.removedInfo != null) {
1925                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1926            }
1927
1928            // Now that we successfully installed the package, grant runtime
1929            // permissions if requested before broadcasting the install. Also
1930            // for legacy apps in permission review mode we clear the permission
1931            // review flag which is used to emulate runtime permissions for
1932            // legacy apps.
1933            if (grantPermissions) {
1934                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1935            }
1936
1937            final boolean update = res.removedInfo != null
1938                    && res.removedInfo.removedPackage != null;
1939            final String installerPackageName =
1940                    res.installerPackageName != null
1941                            ? res.installerPackageName
1942                            : res.removedInfo != null
1943                                    ? res.removedInfo.installerPackageName
1944                                    : null;
1945
1946            // If this is the first time we have child packages for a disabled privileged
1947            // app that had no children, we grant requested runtime permissions to the new
1948            // children if the parent on the system image had them already granted.
1949            if (res.pkg.parentPackage != null) {
1950                synchronized (mPackages) {
1951                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1952                }
1953            }
1954
1955            synchronized (mPackages) {
1956                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1957            }
1958
1959            final String packageName = res.pkg.applicationInfo.packageName;
1960
1961            // Determine the set of users who are adding this package for
1962            // the first time vs. those who are seeing an update.
1963            int[] firstUsers = EMPTY_INT_ARRAY;
1964            int[] updateUsers = EMPTY_INT_ARRAY;
1965            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1966            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1967            for (int newUser : res.newUsers) {
1968                if (ps.getInstantApp(newUser)) {
1969                    continue;
1970                }
1971                if (allNewUsers) {
1972                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1973                    continue;
1974                }
1975                boolean isNew = true;
1976                for (int origUser : res.origUsers) {
1977                    if (origUser == newUser) {
1978                        isNew = false;
1979                        break;
1980                    }
1981                }
1982                if (isNew) {
1983                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1984                } else {
1985                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1986                }
1987            }
1988
1989            // Send installed broadcasts if the package is not a static shared lib.
1990            if (res.pkg.staticSharedLibName == null) {
1991                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1992
1993                // Send added for users that see the package for the first time
1994                // sendPackageAddedForNewUsers also deals with system apps
1995                int appId = UserHandle.getAppId(res.uid);
1996                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1997                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1998                        virtualPreload /*startReceiver*/, appId, firstUsers);
1999
2000                // Send added for users that don't see the package for the first time
2001                Bundle extras = new Bundle(1);
2002                extras.putInt(Intent.EXTRA_UID, res.uid);
2003                if (update) {
2004                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2005                }
2006                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2007                        extras, 0 /*flags*/,
2008                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2009                if (installerPackageName != null) {
2010                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2011                            extras, 0 /*flags*/,
2012                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2013                }
2014
2015                // Send replaced for users that don't see the package for the first time
2016                if (update) {
2017                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2018                            packageName, extras, 0 /*flags*/,
2019                            null /*targetPackage*/, null /*finishedReceiver*/,
2020                            updateUsers);
2021                    if (installerPackageName != null) {
2022                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2023                                extras, 0 /*flags*/,
2024                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2025                    }
2026                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2027                            null /*package*/, null /*extras*/, 0 /*flags*/,
2028                            packageName /*targetPackage*/,
2029                            null /*finishedReceiver*/, updateUsers);
2030                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2031                    // First-install and we did a restore, so we're responsible for the
2032                    // first-launch broadcast.
2033                    if (DEBUG_BACKUP) {
2034                        Slog.i(TAG, "Post-restore of " + packageName
2035                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2036                    }
2037                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2038                }
2039
2040                // Send broadcast package appeared if forward locked/external for all users
2041                // treat asec-hosted packages like removable media on upgrade
2042                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2043                    if (DEBUG_INSTALL) {
2044                        Slog.i(TAG, "upgrading pkg " + res.pkg
2045                                + " is ASEC-hosted -> AVAILABLE");
2046                    }
2047                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2048                    ArrayList<String> pkgList = new ArrayList<>(1);
2049                    pkgList.add(packageName);
2050                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2051                }
2052            }
2053
2054            // Work that needs to happen on first install within each user
2055            if (firstUsers != null && firstUsers.length > 0) {
2056                synchronized (mPackages) {
2057                    for (int userId : firstUsers) {
2058                        // If this app is a browser and it's newly-installed for some
2059                        // users, clear any default-browser state in those users. The
2060                        // app's nature doesn't depend on the user, so we can just check
2061                        // its browser nature in any user and generalize.
2062                        if (packageIsBrowser(packageName, userId)) {
2063                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2064                        }
2065
2066                        // We may also need to apply pending (restored) runtime
2067                        // permission grants within these users.
2068                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2069                    }
2070                }
2071            }
2072
2073            // Log current value of "unknown sources" setting
2074            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2075                    getUnknownSourcesSettings());
2076
2077            // Remove the replaced package's older resources safely now
2078            // We delete after a gc for applications  on sdcard.
2079            if (res.removedInfo != null && res.removedInfo.args != null) {
2080                Runtime.getRuntime().gc();
2081                synchronized (mInstallLock) {
2082                    res.removedInfo.args.doPostDeleteLI(true);
2083                }
2084            } else {
2085                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2086                // and not block here.
2087                VMRuntime.getRuntime().requestConcurrentGC();
2088            }
2089
2090            // Notify DexManager that the package was installed for new users.
2091            // The updated users should already be indexed and the package code paths
2092            // should not change.
2093            // Don't notify the manager for ephemeral apps as they are not expected to
2094            // survive long enough to benefit of background optimizations.
2095            for (int userId : firstUsers) {
2096                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2097                // There's a race currently where some install events may interleave with an uninstall.
2098                // This can lead to package info being null (b/36642664).
2099                if (info != null) {
2100                    mDexManager.notifyPackageInstalled(info, userId);
2101                }
2102            }
2103        }
2104
2105        // If someone is watching installs - notify them
2106        if (installObserver != null) {
2107            try {
2108                Bundle extras = extrasForInstallResult(res);
2109                installObserver.onPackageInstalled(res.name, res.returnCode,
2110                        res.returnMsg, extras);
2111            } catch (RemoteException e) {
2112                Slog.i(TAG, "Observer no longer exists.");
2113            }
2114        }
2115    }
2116
2117    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2118            PackageParser.Package pkg) {
2119        if (pkg.parentPackage == null) {
2120            return;
2121        }
2122        if (pkg.requestedPermissions == null) {
2123            return;
2124        }
2125        final PackageSetting disabledSysParentPs = mSettings
2126                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2127        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2128                || !disabledSysParentPs.isPrivileged()
2129                || (disabledSysParentPs.childPackageNames != null
2130                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2131            return;
2132        }
2133        final int[] allUserIds = sUserManager.getUserIds();
2134        final int permCount = pkg.requestedPermissions.size();
2135        for (int i = 0; i < permCount; i++) {
2136            String permission = pkg.requestedPermissions.get(i);
2137            BasePermission bp = mSettings.mPermissions.get(permission);
2138            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2139                continue;
2140            }
2141            for (int userId : allUserIds) {
2142                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2143                        permission, userId)) {
2144                    grantRuntimePermission(pkg.packageName, permission, userId);
2145                }
2146            }
2147        }
2148    }
2149
2150    private StorageEventListener mStorageListener = new StorageEventListener() {
2151        @Override
2152        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2153            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2154                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2155                    final String volumeUuid = vol.getFsUuid();
2156
2157                    // Clean up any users or apps that were removed or recreated
2158                    // while this volume was missing
2159                    sUserManager.reconcileUsers(volumeUuid);
2160                    reconcileApps(volumeUuid);
2161
2162                    // Clean up any install sessions that expired or were
2163                    // cancelled while this volume was missing
2164                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2165
2166                    loadPrivatePackages(vol);
2167
2168                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2169                    unloadPrivatePackages(vol);
2170                }
2171            }
2172
2173            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2174                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2175                    updateExternalMediaStatus(true, false);
2176                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2177                    updateExternalMediaStatus(false, false);
2178                }
2179            }
2180        }
2181
2182        @Override
2183        public void onVolumeForgotten(String fsUuid) {
2184            if (TextUtils.isEmpty(fsUuid)) {
2185                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2186                return;
2187            }
2188
2189            // Remove any apps installed on the forgotten volume
2190            synchronized (mPackages) {
2191                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2192                for (PackageSetting ps : packages) {
2193                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2194                    deletePackageVersioned(new VersionedPackage(ps.name,
2195                            PackageManager.VERSION_CODE_HIGHEST),
2196                            new LegacyPackageDeleteObserver(null).getBinder(),
2197                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2198                    // Try very hard to release any references to this package
2199                    // so we don't risk the system server being killed due to
2200                    // open FDs
2201                    AttributeCache.instance().removePackage(ps.name);
2202                }
2203
2204                mSettings.onVolumeForgotten(fsUuid);
2205                mSettings.writeLPr();
2206            }
2207        }
2208    };
2209
2210    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2211            String[] grantedPermissions) {
2212        for (int userId : userIds) {
2213            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2214        }
2215    }
2216
2217    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2218            String[] grantedPermissions) {
2219        PackageSetting ps = (PackageSetting) pkg.mExtras;
2220        if (ps == null) {
2221            return;
2222        }
2223
2224        PermissionsState permissionsState = ps.getPermissionsState();
2225
2226        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2227                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2228
2229        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2230                >= Build.VERSION_CODES.M;
2231
2232        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2233
2234        for (String permission : pkg.requestedPermissions) {
2235            final BasePermission bp;
2236            synchronized (mPackages) {
2237                bp = mSettings.mPermissions.get(permission);
2238            }
2239            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2240                    && (!instantApp || bp.isInstant())
2241                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2242                    && (grantedPermissions == null
2243                           || ArrayUtils.contains(grantedPermissions, permission))) {
2244                final int flags = permissionsState.getPermissionFlags(permission, userId);
2245                if (supportsRuntimePermissions) {
2246                    // Installer cannot change immutable permissions.
2247                    if ((flags & immutableFlags) == 0) {
2248                        grantRuntimePermission(pkg.packageName, permission, userId);
2249                    }
2250                } else if (mPermissionReviewRequired) {
2251                    // In permission review mode we clear the review flag when we
2252                    // are asked to install the app with all permissions granted.
2253                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2254                        updatePermissionFlags(permission, pkg.packageName,
2255                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2256                    }
2257                }
2258            }
2259        }
2260    }
2261
2262    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2263        Bundle extras = null;
2264        switch (res.returnCode) {
2265            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2266                extras = new Bundle();
2267                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2268                        res.origPermission);
2269                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2270                        res.origPackage);
2271                break;
2272            }
2273            case PackageManager.INSTALL_SUCCEEDED: {
2274                extras = new Bundle();
2275                extras.putBoolean(Intent.EXTRA_REPLACING,
2276                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2277                break;
2278            }
2279        }
2280        return extras;
2281    }
2282
2283    void scheduleWriteSettingsLocked() {
2284        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2285            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2286        }
2287    }
2288
2289    void scheduleWritePackageListLocked(int userId) {
2290        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2291            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2292            msg.arg1 = userId;
2293            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2294        }
2295    }
2296
2297    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2298        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2299        scheduleWritePackageRestrictionsLocked(userId);
2300    }
2301
2302    void scheduleWritePackageRestrictionsLocked(int userId) {
2303        final int[] userIds = (userId == UserHandle.USER_ALL)
2304                ? sUserManager.getUserIds() : new int[]{userId};
2305        for (int nextUserId : userIds) {
2306            if (!sUserManager.exists(nextUserId)) return;
2307            mDirtyUsers.add(nextUserId);
2308            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2309                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2310            }
2311        }
2312    }
2313
2314    public static PackageManagerService main(Context context, Installer installer,
2315            boolean factoryTest, boolean onlyCore) {
2316        // Self-check for initial settings.
2317        PackageManagerServiceCompilerMapping.checkProperties();
2318
2319        PackageManagerService m = new PackageManagerService(context, installer,
2320                factoryTest, onlyCore);
2321        m.enableSystemUserPackages();
2322        ServiceManager.addService("package", m);
2323        final PackageManagerNative pmn = m.new PackageManagerNative();
2324        ServiceManager.addService("package_native", pmn);
2325        return m;
2326    }
2327
2328    private void enableSystemUserPackages() {
2329        if (!UserManager.isSplitSystemUser()) {
2330            return;
2331        }
2332        // For system user, enable apps based on the following conditions:
2333        // - app is whitelisted or belong to one of these groups:
2334        //   -- system app which has no launcher icons
2335        //   -- system app which has INTERACT_ACROSS_USERS permission
2336        //   -- system IME app
2337        // - app is not in the blacklist
2338        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2339        Set<String> enableApps = new ArraySet<>();
2340        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2341                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2342                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2343        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2344        enableApps.addAll(wlApps);
2345        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2346                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2347        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2348        enableApps.removeAll(blApps);
2349        Log.i(TAG, "Applications installed for system user: " + enableApps);
2350        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2351                UserHandle.SYSTEM);
2352        final int allAppsSize = allAps.size();
2353        synchronized (mPackages) {
2354            for (int i = 0; i < allAppsSize; i++) {
2355                String pName = allAps.get(i);
2356                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2357                // Should not happen, but we shouldn't be failing if it does
2358                if (pkgSetting == null) {
2359                    continue;
2360                }
2361                boolean install = enableApps.contains(pName);
2362                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2363                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2364                            + " for system user");
2365                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2366                }
2367            }
2368            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2369        }
2370    }
2371
2372    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2373        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2374                Context.DISPLAY_SERVICE);
2375        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2376    }
2377
2378    /**
2379     * Requests that files preopted on a secondary system partition be copied to the data partition
2380     * if possible.  Note that the actual copying of the files is accomplished by init for security
2381     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2382     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2383     */
2384    private static void requestCopyPreoptedFiles() {
2385        final int WAIT_TIME_MS = 100;
2386        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2387        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2388            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2389            // We will wait for up to 100 seconds.
2390            final long timeStart = SystemClock.uptimeMillis();
2391            final long timeEnd = timeStart + 100 * 1000;
2392            long timeNow = timeStart;
2393            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2394                try {
2395                    Thread.sleep(WAIT_TIME_MS);
2396                } catch (InterruptedException e) {
2397                    // Do nothing
2398                }
2399                timeNow = SystemClock.uptimeMillis();
2400                if (timeNow > timeEnd) {
2401                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2402                    Slog.wtf(TAG, "cppreopt did not finish!");
2403                    break;
2404                }
2405            }
2406
2407            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2408        }
2409    }
2410
2411    public PackageManagerService(Context context, Installer installer,
2412            boolean factoryTest, boolean onlyCore) {
2413        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2414        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2415        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2416                SystemClock.uptimeMillis());
2417
2418        if (mSdkVersion <= 0) {
2419            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2420        }
2421
2422        mContext = context;
2423
2424        mPermissionReviewRequired = context.getResources().getBoolean(
2425                R.bool.config_permissionReviewRequired);
2426
2427        mFactoryTest = factoryTest;
2428        mOnlyCore = onlyCore;
2429        mMetrics = new DisplayMetrics();
2430        mSettings = new Settings(mPackages);
2431        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2432                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2433        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2434                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2435        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2436                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2437        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2438                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2439        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2440                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2441        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2442                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2443        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2444                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2445
2446        String separateProcesses = SystemProperties.get("debug.separate_processes");
2447        if (separateProcesses != null && separateProcesses.length() > 0) {
2448            if ("*".equals(separateProcesses)) {
2449                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2450                mSeparateProcesses = null;
2451                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2452            } else {
2453                mDefParseFlags = 0;
2454                mSeparateProcesses = separateProcesses.split(",");
2455                Slog.w(TAG, "Running with debug.separate_processes: "
2456                        + separateProcesses);
2457            }
2458        } else {
2459            mDefParseFlags = 0;
2460            mSeparateProcesses = null;
2461        }
2462
2463        mInstaller = installer;
2464        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2465                "*dexopt*");
2466        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2467                installer, mInstallLock);
2468        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2469                dexManagerListener);
2470        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2471
2472        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2473                FgThread.get().getLooper());
2474
2475        getDefaultDisplayMetrics(context, mMetrics);
2476
2477        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2478        SystemConfig systemConfig = SystemConfig.getInstance();
2479        mGlobalGids = systemConfig.getGlobalGids();
2480        mSystemPermissions = systemConfig.getSystemPermissions();
2481        mAvailableFeatures = systemConfig.getAvailableFeatures();
2482        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2483
2484        mProtectedPackages = new ProtectedPackages(mContext);
2485
2486        synchronized (mInstallLock) {
2487        // writer
2488        synchronized (mPackages) {
2489            mHandlerThread = new ServiceThread(TAG,
2490                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2491            mHandlerThread.start();
2492            mHandler = new PackageHandler(mHandlerThread.getLooper());
2493            mProcessLoggingHandler = new ProcessLoggingHandler();
2494            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2495
2496            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2497            mInstantAppRegistry = new InstantAppRegistry(this);
2498
2499            File dataDir = Environment.getDataDirectory();
2500            mAppInstallDir = new File(dataDir, "app");
2501            mAppLib32InstallDir = new File(dataDir, "app-lib");
2502            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2503            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2504            sUserManager = new UserManagerService(context, this,
2505                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2506
2507            // Propagate permission configuration in to package manager.
2508            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2509                    = systemConfig.getPermissions();
2510            for (int i=0; i<permConfig.size(); i++) {
2511                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2512                BasePermission bp = mSettings.mPermissions.get(perm.name);
2513                if (bp == null) {
2514                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2515                    mSettings.mPermissions.put(perm.name, bp);
2516                }
2517                if (perm.gids != null) {
2518                    bp.setGids(perm.gids, perm.perUser);
2519                }
2520            }
2521
2522            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2523            final int builtInLibCount = libConfig.size();
2524            for (int i = 0; i < builtInLibCount; i++) {
2525                String name = libConfig.keyAt(i);
2526                String path = libConfig.valueAt(i);
2527                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2528                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2529            }
2530
2531            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2532
2533            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2534            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2535            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2536
2537            // Clean up orphaned packages for which the code path doesn't exist
2538            // and they are an update to a system app - caused by bug/32321269
2539            final int packageSettingCount = mSettings.mPackages.size();
2540            for (int i = packageSettingCount - 1; i >= 0; i--) {
2541                PackageSetting ps = mSettings.mPackages.valueAt(i);
2542                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2543                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2544                    mSettings.mPackages.removeAt(i);
2545                    mSettings.enableSystemPackageLPw(ps.name);
2546                }
2547            }
2548
2549            if (mFirstBoot) {
2550                requestCopyPreoptedFiles();
2551            }
2552
2553            String customResolverActivity = Resources.getSystem().getString(
2554                    R.string.config_customResolverActivity);
2555            if (TextUtils.isEmpty(customResolverActivity)) {
2556                customResolverActivity = null;
2557            } else {
2558                mCustomResolverComponentName = ComponentName.unflattenFromString(
2559                        customResolverActivity);
2560            }
2561
2562            long startTime = SystemClock.uptimeMillis();
2563
2564            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2565                    startTime);
2566
2567            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2568            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2569
2570            if (bootClassPath == null) {
2571                Slog.w(TAG, "No BOOTCLASSPATH found!");
2572            }
2573
2574            if (systemServerClassPath == null) {
2575                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2576            }
2577
2578            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2579
2580            final VersionInfo ver = mSettings.getInternalVersion();
2581            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2582            if (mIsUpgrade) {
2583                logCriticalInfo(Log.INFO,
2584                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2585            }
2586
2587            // when upgrading from pre-M, promote system app permissions from install to runtime
2588            mPromoteSystemApps =
2589                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2590
2591            // When upgrading from pre-N, we need to handle package extraction like first boot,
2592            // as there is no profiling data available.
2593            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2594
2595            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2596
2597            // save off the names of pre-existing system packages prior to scanning; we don't
2598            // want to automatically grant runtime permissions for new system apps
2599            if (mPromoteSystemApps) {
2600                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2601                while (pkgSettingIter.hasNext()) {
2602                    PackageSetting ps = pkgSettingIter.next();
2603                    if (isSystemApp(ps)) {
2604                        mExistingSystemPackages.add(ps.name);
2605                    }
2606                }
2607            }
2608
2609            mCacheDir = preparePackageParserCache(mIsUpgrade);
2610
2611            // Set flag to monitor and not change apk file paths when
2612            // scanning install directories.
2613            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2614
2615            if (mIsUpgrade || mFirstBoot) {
2616                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2617            }
2618
2619            // Collect vendor overlay packages. (Do this before scanning any apps.)
2620            // For security and version matching reason, only consider
2621            // overlay packages if they reside in the right directory.
2622            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2623                    | PackageParser.PARSE_IS_SYSTEM
2624                    | PackageParser.PARSE_IS_SYSTEM_DIR
2625                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2626
2627            mParallelPackageParserCallback.findStaticOverlayPackages();
2628
2629            // Find base frameworks (resource packages without code).
2630            scanDirTracedLI(frameworkDir, mDefParseFlags
2631                    | PackageParser.PARSE_IS_SYSTEM
2632                    | PackageParser.PARSE_IS_SYSTEM_DIR
2633                    | PackageParser.PARSE_IS_PRIVILEGED,
2634                    scanFlags | SCAN_NO_DEX, 0);
2635
2636            // Collected privileged system packages.
2637            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2638            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2639                    | PackageParser.PARSE_IS_SYSTEM
2640                    | PackageParser.PARSE_IS_SYSTEM_DIR
2641                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2642
2643            // Collect ordinary system packages.
2644            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2645            scanDirTracedLI(systemAppDir, mDefParseFlags
2646                    | PackageParser.PARSE_IS_SYSTEM
2647                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2648
2649            // Collect all vendor packages.
2650            File vendorAppDir = new File("/vendor/app");
2651            try {
2652                vendorAppDir = vendorAppDir.getCanonicalFile();
2653            } catch (IOException e) {
2654                // failed to look up canonical path, continue with original one
2655            }
2656            scanDirTracedLI(vendorAppDir, mDefParseFlags
2657                    | PackageParser.PARSE_IS_SYSTEM
2658                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2659
2660            // Collect all OEM packages.
2661            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2662            scanDirTracedLI(oemAppDir, mDefParseFlags
2663                    | PackageParser.PARSE_IS_SYSTEM
2664                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2665
2666            // Prune any system packages that no longer exist.
2667            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2668            // Stub packages must either be replaced with full versions in the /data
2669            // partition or be disabled.
2670            final List<String> stubSystemApps = new ArrayList<>();
2671            if (!mOnlyCore) {
2672                // do this first before mucking with mPackages for the "expecting better" case
2673                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2674                while (pkgIterator.hasNext()) {
2675                    final PackageParser.Package pkg = pkgIterator.next();
2676                    if (pkg.isStub) {
2677                        stubSystemApps.add(pkg.packageName);
2678                    }
2679                }
2680
2681                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2682                while (psit.hasNext()) {
2683                    PackageSetting ps = psit.next();
2684
2685                    /*
2686                     * If this is not a system app, it can't be a
2687                     * disable system app.
2688                     */
2689                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2690                        continue;
2691                    }
2692
2693                    /*
2694                     * If the package is scanned, it's not erased.
2695                     */
2696                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2697                    if (scannedPkg != null) {
2698                        /*
2699                         * If the system app is both scanned and in the
2700                         * disabled packages list, then it must have been
2701                         * added via OTA. Remove it from the currently
2702                         * scanned package so the previously user-installed
2703                         * application can be scanned.
2704                         */
2705                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2706                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2707                                    + ps.name + "; removing system app.  Last known codePath="
2708                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2709                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2710                                    + scannedPkg.mVersionCode);
2711                            removePackageLI(scannedPkg, true);
2712                            mExpectingBetter.put(ps.name, ps.codePath);
2713                        }
2714
2715                        continue;
2716                    }
2717
2718                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2719                        psit.remove();
2720                        logCriticalInfo(Log.WARN, "System package " + ps.name
2721                                + " no longer exists; it's data will be wiped");
2722                        // Actual deletion of code and data will be handled by later
2723                        // reconciliation step
2724                    } else {
2725                        // we still have a disabled system package, but, it still might have
2726                        // been removed. check the code path still exists and check there's
2727                        // still a package. the latter can happen if an OTA keeps the same
2728                        // code path, but, changes the package name.
2729                        final PackageSetting disabledPs =
2730                                mSettings.getDisabledSystemPkgLPr(ps.name);
2731                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2732                                || disabledPs.pkg == null) {
2733                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2734                        }
2735                    }
2736                }
2737            }
2738
2739            //look for any incomplete package installations
2740            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2741            for (int i = 0; i < deletePkgsList.size(); i++) {
2742                // Actual deletion of code and data will be handled by later
2743                // reconciliation step
2744                final String packageName = deletePkgsList.get(i).name;
2745                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2746                synchronized (mPackages) {
2747                    mSettings.removePackageLPw(packageName);
2748                }
2749            }
2750
2751            //delete tmp files
2752            deleteTempPackageFiles();
2753
2754            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2755
2756            // Remove any shared userIDs that have no associated packages
2757            mSettings.pruneSharedUsersLPw();
2758            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2759            final int systemPackagesCount = mPackages.size();
2760            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2761                    + " ms, packageCount: " + systemPackagesCount
2762                    + " , timePerPackage: "
2763                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2764                    + " , cached: " + cachedSystemApps);
2765            if (mIsUpgrade && systemPackagesCount > 0) {
2766                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2767                        ((int) systemScanTime) / systemPackagesCount);
2768            }
2769            if (!mOnlyCore) {
2770                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2771                        SystemClock.uptimeMillis());
2772                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2773
2774                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2775                        | PackageParser.PARSE_FORWARD_LOCK,
2776                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2777
2778                // Remove disable package settings for updated system apps that were
2779                // removed via an OTA. If the update is no longer present, remove the
2780                // app completely. Otherwise, revoke their system privileges.
2781                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2782                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2783                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2784
2785                    final String msg;
2786                    if (deletedPkg == null) {
2787                        // should have found an update, but, we didn't; remove everything
2788                        msg = "Updated system package " + deletedAppName
2789                                + " no longer exists; removing its data";
2790                        // Actual deletion of code and data will be handled by later
2791                        // reconciliation step
2792                    } else {
2793                        // found an update; revoke system privileges
2794                        msg = "Updated system package + " + deletedAppName
2795                                + " no longer exists; revoking system privileges";
2796
2797                        // Don't do anything if a stub is removed from the system image. If
2798                        // we were to remove the uncompressed version from the /data partition,
2799                        // this is where it'd be done.
2800
2801                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2802                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2803                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2804                    }
2805                    logCriticalInfo(Log.WARN, msg);
2806                }
2807
2808                /*
2809                 * Make sure all system apps that we expected to appear on
2810                 * the userdata partition actually showed up. If they never
2811                 * appeared, crawl back and revive the system version.
2812                 */
2813                for (int i = 0; i < mExpectingBetter.size(); i++) {
2814                    final String packageName = mExpectingBetter.keyAt(i);
2815                    if (!mPackages.containsKey(packageName)) {
2816                        final File scanFile = mExpectingBetter.valueAt(i);
2817
2818                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2819                                + " but never showed up; reverting to system");
2820
2821                        int reparseFlags = mDefParseFlags;
2822                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2823                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2824                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2825                                    | PackageParser.PARSE_IS_PRIVILEGED;
2826                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2827                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2828                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2829                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2830                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2831                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2832                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2833                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2834                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2835                        } else {
2836                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2837                            continue;
2838                        }
2839
2840                        mSettings.enableSystemPackageLPw(packageName);
2841
2842                        try {
2843                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2844                        } catch (PackageManagerException e) {
2845                            Slog.e(TAG, "Failed to parse original system package: "
2846                                    + e.getMessage());
2847                        }
2848                    }
2849                }
2850
2851                // Uncompress and install any stubbed system applications.
2852                // This must be done last to ensure all stubs are replaced or disabled.
2853                decompressSystemApplications(stubSystemApps, scanFlags);
2854
2855                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2856                                - cachedSystemApps;
2857
2858                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2859                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2860                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2861                        + " ms, packageCount: " + dataPackagesCount
2862                        + " , timePerPackage: "
2863                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2864                        + " , cached: " + cachedNonSystemApps);
2865                if (mIsUpgrade && dataPackagesCount > 0) {
2866                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2867                            ((int) dataScanTime) / dataPackagesCount);
2868                }
2869            }
2870            mExpectingBetter.clear();
2871
2872            // Resolve the storage manager.
2873            mStorageManagerPackage = getStorageManagerPackageName();
2874
2875            // Resolve protected action filters. Only the setup wizard is allowed to
2876            // have a high priority filter for these actions.
2877            mSetupWizardPackage = getSetupWizardPackageName();
2878            if (mProtectedFilters.size() > 0) {
2879                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2880                    Slog.i(TAG, "No setup wizard;"
2881                        + " All protected intents capped to priority 0");
2882                }
2883                for (ActivityIntentInfo filter : mProtectedFilters) {
2884                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2885                        if (DEBUG_FILTERS) {
2886                            Slog.i(TAG, "Found setup wizard;"
2887                                + " allow priority " + filter.getPriority() + ";"
2888                                + " package: " + filter.activity.info.packageName
2889                                + " activity: " + filter.activity.className
2890                                + " priority: " + filter.getPriority());
2891                        }
2892                        // skip setup wizard; allow it to keep the high priority filter
2893                        continue;
2894                    }
2895                    if (DEBUG_FILTERS) {
2896                        Slog.i(TAG, "Protected action; cap priority to 0;"
2897                                + " package: " + filter.activity.info.packageName
2898                                + " activity: " + filter.activity.className
2899                                + " origPrio: " + filter.getPriority());
2900                    }
2901                    filter.setPriority(0);
2902                }
2903            }
2904            mDeferProtectedFilters = false;
2905            mProtectedFilters.clear();
2906
2907            // Now that we know all of the shared libraries, update all clients to have
2908            // the correct library paths.
2909            updateAllSharedLibrariesLPw(null);
2910
2911            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2912                // NOTE: We ignore potential failures here during a system scan (like
2913                // the rest of the commands above) because there's precious little we
2914                // can do about it. A settings error is reported, though.
2915                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2916            }
2917
2918            // Now that we know all the packages we are keeping,
2919            // read and update their last usage times.
2920            mPackageUsage.read(mPackages);
2921            mCompilerStats.read();
2922
2923            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2924                    SystemClock.uptimeMillis());
2925            Slog.i(TAG, "Time to scan packages: "
2926                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2927                    + " seconds");
2928
2929            // If the platform SDK has changed since the last time we booted,
2930            // we need to re-grant app permission to catch any new ones that
2931            // appear.  This is really a hack, and means that apps can in some
2932            // cases get permissions that the user didn't initially explicitly
2933            // allow...  it would be nice to have some better way to handle
2934            // this situation.
2935            int updateFlags = UPDATE_PERMISSIONS_ALL;
2936            if (ver.sdkVersion != mSdkVersion) {
2937                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2938                        + mSdkVersion + "; regranting permissions for internal storage");
2939                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2940            }
2941            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2942            ver.sdkVersion = mSdkVersion;
2943
2944            // If this is the first boot or an update from pre-M, and it is a normal
2945            // boot, then we need to initialize the default preferred apps across
2946            // all defined users.
2947            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2948                for (UserInfo user : sUserManager.getUsers(true)) {
2949                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2950                    applyFactoryDefaultBrowserLPw(user.id);
2951                    primeDomainVerificationsLPw(user.id);
2952                }
2953            }
2954
2955            // Prepare storage for system user really early during boot,
2956            // since core system apps like SettingsProvider and SystemUI
2957            // can't wait for user to start
2958            final int storageFlags;
2959            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2960                storageFlags = StorageManager.FLAG_STORAGE_DE;
2961            } else {
2962                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2963            }
2964            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2965                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2966                    true /* onlyCoreApps */);
2967            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2968                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2969                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2970                traceLog.traceBegin("AppDataFixup");
2971                try {
2972                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2973                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2974                } catch (InstallerException e) {
2975                    Slog.w(TAG, "Trouble fixing GIDs", e);
2976                }
2977                traceLog.traceEnd();
2978
2979                traceLog.traceBegin("AppDataPrepare");
2980                if (deferPackages == null || deferPackages.isEmpty()) {
2981                    return;
2982                }
2983                int count = 0;
2984                for (String pkgName : deferPackages) {
2985                    PackageParser.Package pkg = null;
2986                    synchronized (mPackages) {
2987                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2988                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2989                            pkg = ps.pkg;
2990                        }
2991                    }
2992                    if (pkg != null) {
2993                        synchronized (mInstallLock) {
2994                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2995                                    true /* maybeMigrateAppData */);
2996                        }
2997                        count++;
2998                    }
2999                }
3000                traceLog.traceEnd();
3001                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3002            }, "prepareAppData");
3003
3004            // If this is first boot after an OTA, and a normal boot, then
3005            // we need to clear code cache directories.
3006            // Note that we do *not* clear the application profiles. These remain valid
3007            // across OTAs and are used to drive profile verification (post OTA) and
3008            // profile compilation (without waiting to collect a fresh set of profiles).
3009            if (mIsUpgrade && !onlyCore) {
3010                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3011                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3012                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3013                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3014                        // No apps are running this early, so no need to freeze
3015                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3016                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3017                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3018                    }
3019                }
3020                ver.fingerprint = Build.FINGERPRINT;
3021            }
3022
3023            checkDefaultBrowser();
3024
3025            // clear only after permissions and other defaults have been updated
3026            mExistingSystemPackages.clear();
3027            mPromoteSystemApps = false;
3028
3029            // All the changes are done during package scanning.
3030            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3031
3032            // can downgrade to reader
3033            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3034            mSettings.writeLPr();
3035            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3036            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3037                    SystemClock.uptimeMillis());
3038
3039            if (!mOnlyCore) {
3040                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3041                mRequiredInstallerPackage = getRequiredInstallerLPr();
3042                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3043                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3044                if (mIntentFilterVerifierComponent != null) {
3045                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3046                            mIntentFilterVerifierComponent);
3047                } else {
3048                    mIntentFilterVerifier = null;
3049                }
3050                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3051                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3052                        SharedLibraryInfo.VERSION_UNDEFINED);
3053                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3054                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3055                        SharedLibraryInfo.VERSION_UNDEFINED);
3056            } else {
3057                mRequiredVerifierPackage = null;
3058                mRequiredInstallerPackage = null;
3059                mRequiredUninstallerPackage = null;
3060                mIntentFilterVerifierComponent = null;
3061                mIntentFilterVerifier = null;
3062                mServicesSystemSharedLibraryPackageName = null;
3063                mSharedSystemSharedLibraryPackageName = null;
3064            }
3065
3066            mInstallerService = new PackageInstallerService(context, this);
3067            mArtManagerService = new ArtManagerService(this);
3068            final Pair<ComponentName, String> instantAppResolverComponent =
3069                    getInstantAppResolverLPr();
3070            if (instantAppResolverComponent != null) {
3071                if (DEBUG_EPHEMERAL) {
3072                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3073                }
3074                mInstantAppResolverConnection = new EphemeralResolverConnection(
3075                        mContext, instantAppResolverComponent.first,
3076                        instantAppResolverComponent.second);
3077                mInstantAppResolverSettingsComponent =
3078                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3079            } else {
3080                mInstantAppResolverConnection = null;
3081                mInstantAppResolverSettingsComponent = null;
3082            }
3083            updateInstantAppInstallerLocked(null);
3084
3085            // Read and update the usage of dex files.
3086            // Do this at the end of PM init so that all the packages have their
3087            // data directory reconciled.
3088            // At this point we know the code paths of the packages, so we can validate
3089            // the disk file and build the internal cache.
3090            // The usage file is expected to be small so loading and verifying it
3091            // should take a fairly small time compare to the other activities (e.g. package
3092            // scanning).
3093            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3094            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3095            for (int userId : currentUserIds) {
3096                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3097            }
3098            mDexManager.load(userPackages);
3099            if (mIsUpgrade) {
3100                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3101                        (int) (SystemClock.uptimeMillis() - startTime));
3102            }
3103        } // synchronized (mPackages)
3104        } // synchronized (mInstallLock)
3105
3106        // Now after opening every single application zip, make sure they
3107        // are all flushed.  Not really needed, but keeps things nice and
3108        // tidy.
3109        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3110        Runtime.getRuntime().gc();
3111        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3112
3113        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3114        FallbackCategoryProvider.loadFallbacks();
3115        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3116
3117        // The initial scanning above does many calls into installd while
3118        // holding the mPackages lock, but we're mostly interested in yelling
3119        // once we have a booted system.
3120        mInstaller.setWarnIfHeld(mPackages);
3121
3122        // Expose private service for system components to use.
3123        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3124        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3125    }
3126
3127    /**
3128     * Uncompress and install stub applications.
3129     * <p>In order to save space on the system partition, some applications are shipped in a
3130     * compressed form. In addition the compressed bits for the full application, the
3131     * system image contains a tiny stub comprised of only the Android manifest.
3132     * <p>During the first boot, attempt to uncompress and install the full application. If
3133     * the application can't be installed for any reason, disable the stub and prevent
3134     * uncompressing the full application during future boots.
3135     * <p>In order to forcefully attempt an installation of a full application, go to app
3136     * settings and enable the application.
3137     */
3138    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3139        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3140            final String pkgName = stubSystemApps.get(i);
3141            // skip if the system package is already disabled
3142            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3143                stubSystemApps.remove(i);
3144                continue;
3145            }
3146            // skip if the package isn't installed (?!); this should never happen
3147            final PackageParser.Package pkg = mPackages.get(pkgName);
3148            if (pkg == null) {
3149                stubSystemApps.remove(i);
3150                continue;
3151            }
3152            // skip if the package has been disabled by the user
3153            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3154            if (ps != null) {
3155                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3156                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3157                    stubSystemApps.remove(i);
3158                    continue;
3159                }
3160            }
3161
3162            if (DEBUG_COMPRESSION) {
3163                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3164            }
3165
3166            // uncompress the binary to its eventual destination on /data
3167            final File scanFile = decompressPackage(pkg);
3168            if (scanFile == null) {
3169                continue;
3170            }
3171
3172            // install the package to replace the stub on /system
3173            try {
3174                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3175                removePackageLI(pkg, true /*chatty*/);
3176                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3177                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3178                        UserHandle.USER_SYSTEM, "android");
3179                stubSystemApps.remove(i);
3180                continue;
3181            } catch (PackageManagerException e) {
3182                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3183            }
3184
3185            // any failed attempt to install the package will be cleaned up later
3186        }
3187
3188        // disable any stub still left; these failed to install the full application
3189        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3190            final String pkgName = stubSystemApps.get(i);
3191            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3192            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3193                    UserHandle.USER_SYSTEM, "android");
3194            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3195        }
3196    }
3197
3198    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3199        if (DEBUG_COMPRESSION) {
3200            Slog.i(TAG, "Decompress file"
3201                    + "; src: " + srcFile.getAbsolutePath()
3202                    + ", dst: " + dstFile.getAbsolutePath());
3203        }
3204        try (
3205                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3206                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3207        ) {
3208            Streams.copy(fileIn, fileOut);
3209            Os.chmod(dstFile.getAbsolutePath(), 0644);
3210            return PackageManager.INSTALL_SUCCEEDED;
3211        } catch (IOException e) {
3212            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3213                    + "; src: " + srcFile.getAbsolutePath()
3214                    + ", dst: " + dstFile.getAbsolutePath());
3215        }
3216        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3217    }
3218
3219    private File[] getCompressedFiles(String codePath) {
3220        final File stubCodePath = new File(codePath);
3221        final String stubName = stubCodePath.getName();
3222
3223        // The layout of a compressed package on a given partition is as follows :
3224        //
3225        // Compressed artifacts:
3226        //
3227        // /partition/ModuleName/foo.gz
3228        // /partation/ModuleName/bar.gz
3229        //
3230        // Stub artifact:
3231        //
3232        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3233        //
3234        // In other words, stub is on the same partition as the compressed artifacts
3235        // and in a directory that's suffixed with "-Stub".
3236        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3237        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3238            return null;
3239        }
3240
3241        final File stubParentDir = stubCodePath.getParentFile();
3242        if (stubParentDir == null) {
3243            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3244            return null;
3245        }
3246
3247        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3248        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3249            @Override
3250            public boolean accept(File dir, String name) {
3251                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3252            }
3253        });
3254
3255        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3256            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3257        }
3258
3259        return files;
3260    }
3261
3262    private boolean compressedFileExists(String codePath) {
3263        final File[] compressedFiles = getCompressedFiles(codePath);
3264        return compressedFiles != null && compressedFiles.length > 0;
3265    }
3266
3267    /**
3268     * Decompresses the given package on the system image onto
3269     * the /data partition.
3270     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3271     */
3272    private File decompressPackage(PackageParser.Package pkg) {
3273        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3274        if (compressedFiles == null || compressedFiles.length == 0) {
3275            if (DEBUG_COMPRESSION) {
3276                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3277            }
3278            return null;
3279        }
3280        final File dstCodePath =
3281                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3282        int ret = PackageManager.INSTALL_SUCCEEDED;
3283        try {
3284            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3285            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3286            for (File srcFile : compressedFiles) {
3287                final String srcFileName = srcFile.getName();
3288                final String dstFileName = srcFileName.substring(
3289                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3290                final File dstFile = new File(dstCodePath, dstFileName);
3291                ret = decompressFile(srcFile, dstFile);
3292                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3293                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3294                            + "; pkg: " + pkg.packageName
3295                            + ", file: " + dstFileName);
3296                    break;
3297                }
3298            }
3299        } catch (ErrnoException e) {
3300            logCriticalInfo(Log.ERROR, "Failed to decompress"
3301                    + "; pkg: " + pkg.packageName
3302                    + ", err: " + e.errno);
3303        }
3304        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3305            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3306            NativeLibraryHelper.Handle handle = null;
3307            try {
3308                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3309                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3310                        null /*abiOverride*/);
3311            } catch (IOException e) {
3312                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3313                        + "; pkg: " + pkg.packageName);
3314                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3315            } finally {
3316                IoUtils.closeQuietly(handle);
3317            }
3318        }
3319        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3320            if (dstCodePath == null || !dstCodePath.exists()) {
3321                return null;
3322            }
3323            removeCodePathLI(dstCodePath);
3324            return null;
3325        }
3326
3327        return dstCodePath;
3328    }
3329
3330    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3331        // we're only interested in updating the installer appliction when 1) it's not
3332        // already set or 2) the modified package is the installer
3333        if (mInstantAppInstallerActivity != null
3334                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3335                        .equals(modifiedPackage)) {
3336            return;
3337        }
3338        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3339    }
3340
3341    private static File preparePackageParserCache(boolean isUpgrade) {
3342        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3343            return null;
3344        }
3345
3346        // Disable package parsing on eng builds to allow for faster incremental development.
3347        if (Build.IS_ENG) {
3348            return null;
3349        }
3350
3351        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3352            Slog.i(TAG, "Disabling package parser cache due to system property.");
3353            return null;
3354        }
3355
3356        // The base directory for the package parser cache lives under /data/system/.
3357        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3358                "package_cache");
3359        if (cacheBaseDir == null) {
3360            return null;
3361        }
3362
3363        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3364        // This also serves to "GC" unused entries when the package cache version changes (which
3365        // can only happen during upgrades).
3366        if (isUpgrade) {
3367            FileUtils.deleteContents(cacheBaseDir);
3368        }
3369
3370
3371        // Return the versioned package cache directory. This is something like
3372        // "/data/system/package_cache/1"
3373        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3374
3375        // The following is a workaround to aid development on non-numbered userdebug
3376        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3377        // the system partition is newer.
3378        //
3379        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3380        // that starts with "eng." to signify that this is an engineering build and not
3381        // destined for release.
3382        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3383            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3384
3385            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3386            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3387            // in general and should not be used for production changes. In this specific case,
3388            // we know that they will work.
3389            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3390            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3391                FileUtils.deleteContents(cacheBaseDir);
3392                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3393            }
3394        }
3395
3396        return cacheDir;
3397    }
3398
3399    @Override
3400    public boolean isFirstBoot() {
3401        // allow instant applications
3402        return mFirstBoot;
3403    }
3404
3405    @Override
3406    public boolean isOnlyCoreApps() {
3407        // allow instant applications
3408        return mOnlyCore;
3409    }
3410
3411    @Override
3412    public boolean isUpgrade() {
3413        // allow instant applications
3414        return mIsUpgrade;
3415    }
3416
3417    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3418        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3419
3420        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3421                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3422                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3423        if (matches.size() == 1) {
3424            return matches.get(0).getComponentInfo().packageName;
3425        } else if (matches.size() == 0) {
3426            Log.e(TAG, "There should probably be a verifier, but, none were found");
3427            return null;
3428        }
3429        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3430    }
3431
3432    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3433        synchronized (mPackages) {
3434            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3435            if (libraryEntry == null) {
3436                throw new IllegalStateException("Missing required shared library:" + name);
3437            }
3438            return libraryEntry.apk;
3439        }
3440    }
3441
3442    private @NonNull String getRequiredInstallerLPr() {
3443        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3444        intent.addCategory(Intent.CATEGORY_DEFAULT);
3445        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3446
3447        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3448                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3449                UserHandle.USER_SYSTEM);
3450        if (matches.size() == 1) {
3451            ResolveInfo resolveInfo = matches.get(0);
3452            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3453                throw new RuntimeException("The installer must be a privileged app");
3454            }
3455            return matches.get(0).getComponentInfo().packageName;
3456        } else {
3457            throw new RuntimeException("There must be exactly one installer; found " + matches);
3458        }
3459    }
3460
3461    private @NonNull String getRequiredUninstallerLPr() {
3462        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3463        intent.addCategory(Intent.CATEGORY_DEFAULT);
3464        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3465
3466        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3467                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3468                UserHandle.USER_SYSTEM);
3469        if (resolveInfo == null ||
3470                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3471            throw new RuntimeException("There must be exactly one uninstaller; found "
3472                    + resolveInfo);
3473        }
3474        return resolveInfo.getComponentInfo().packageName;
3475    }
3476
3477    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3478        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3479
3480        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3481                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3482                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3483        ResolveInfo best = null;
3484        final int N = matches.size();
3485        for (int i = 0; i < N; i++) {
3486            final ResolveInfo cur = matches.get(i);
3487            final String packageName = cur.getComponentInfo().packageName;
3488            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3489                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3490                continue;
3491            }
3492
3493            if (best == null || cur.priority > best.priority) {
3494                best = cur;
3495            }
3496        }
3497
3498        if (best != null) {
3499            return best.getComponentInfo().getComponentName();
3500        }
3501        Slog.w(TAG, "Intent filter verifier not found");
3502        return null;
3503    }
3504
3505    @Override
3506    public @Nullable ComponentName getInstantAppResolverComponent() {
3507        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3508            return null;
3509        }
3510        synchronized (mPackages) {
3511            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3512            if (instantAppResolver == null) {
3513                return null;
3514            }
3515            return instantAppResolver.first;
3516        }
3517    }
3518
3519    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3520        final String[] packageArray =
3521                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3522        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3523            if (DEBUG_EPHEMERAL) {
3524                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3525            }
3526            return null;
3527        }
3528
3529        final int callingUid = Binder.getCallingUid();
3530        final int resolveFlags =
3531                MATCH_DIRECT_BOOT_AWARE
3532                | MATCH_DIRECT_BOOT_UNAWARE
3533                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3534        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3535        final Intent resolverIntent = new Intent(actionName);
3536        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3537                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3538        // temporarily look for the old action
3539        if (resolvers.size() == 0) {
3540            if (DEBUG_EPHEMERAL) {
3541                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3542            }
3543            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3544            resolverIntent.setAction(actionName);
3545            resolvers = queryIntentServicesInternal(resolverIntent, null,
3546                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3547        }
3548        final int N = resolvers.size();
3549        if (N == 0) {
3550            if (DEBUG_EPHEMERAL) {
3551                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3552            }
3553            return null;
3554        }
3555
3556        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3557        for (int i = 0; i < N; i++) {
3558            final ResolveInfo info = resolvers.get(i);
3559
3560            if (info.serviceInfo == null) {
3561                continue;
3562            }
3563
3564            final String packageName = info.serviceInfo.packageName;
3565            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3566                if (DEBUG_EPHEMERAL) {
3567                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3568                            + " pkg: " + packageName + ", info:" + info);
3569                }
3570                continue;
3571            }
3572
3573            if (DEBUG_EPHEMERAL) {
3574                Slog.v(TAG, "Ephemeral resolver found;"
3575                        + " pkg: " + packageName + ", info:" + info);
3576            }
3577            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3578        }
3579        if (DEBUG_EPHEMERAL) {
3580            Slog.v(TAG, "Ephemeral resolver NOT found");
3581        }
3582        return null;
3583    }
3584
3585    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3586        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3587        intent.addCategory(Intent.CATEGORY_DEFAULT);
3588        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3589
3590        final int resolveFlags =
3591                MATCH_DIRECT_BOOT_AWARE
3592                | MATCH_DIRECT_BOOT_UNAWARE
3593                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3594        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3595                resolveFlags, UserHandle.USER_SYSTEM);
3596        // temporarily look for the old action
3597        if (matches.isEmpty()) {
3598            if (DEBUG_EPHEMERAL) {
3599                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3600            }
3601            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3602            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3603                    resolveFlags, UserHandle.USER_SYSTEM);
3604        }
3605        Iterator<ResolveInfo> iter = matches.iterator();
3606        while (iter.hasNext()) {
3607            final ResolveInfo rInfo = iter.next();
3608            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3609            if (ps != null) {
3610                final PermissionsState permissionsState = ps.getPermissionsState();
3611                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3612                    continue;
3613                }
3614            }
3615            iter.remove();
3616        }
3617        if (matches.size() == 0) {
3618            return null;
3619        } else if (matches.size() == 1) {
3620            return (ActivityInfo) matches.get(0).getComponentInfo();
3621        } else {
3622            throw new RuntimeException(
3623                    "There must be at most one ephemeral installer; found " + matches);
3624        }
3625    }
3626
3627    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3628            @NonNull ComponentName resolver) {
3629        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3630                .addCategory(Intent.CATEGORY_DEFAULT)
3631                .setPackage(resolver.getPackageName());
3632        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3633        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3634                UserHandle.USER_SYSTEM);
3635        // temporarily look for the old action
3636        if (matches.isEmpty()) {
3637            if (DEBUG_EPHEMERAL) {
3638                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3639            }
3640            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3641            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3642                    UserHandle.USER_SYSTEM);
3643        }
3644        if (matches.isEmpty()) {
3645            return null;
3646        }
3647        return matches.get(0).getComponentInfo().getComponentName();
3648    }
3649
3650    private void primeDomainVerificationsLPw(int userId) {
3651        if (DEBUG_DOMAIN_VERIFICATION) {
3652            Slog.d(TAG, "Priming domain verifications in user " + userId);
3653        }
3654
3655        SystemConfig systemConfig = SystemConfig.getInstance();
3656        ArraySet<String> packages = systemConfig.getLinkedApps();
3657
3658        for (String packageName : packages) {
3659            PackageParser.Package pkg = mPackages.get(packageName);
3660            if (pkg != null) {
3661                if (!pkg.isSystemApp()) {
3662                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3663                    continue;
3664                }
3665
3666                ArraySet<String> domains = null;
3667                for (PackageParser.Activity a : pkg.activities) {
3668                    for (ActivityIntentInfo filter : a.intents) {
3669                        if (hasValidDomains(filter)) {
3670                            if (domains == null) {
3671                                domains = new ArraySet<String>();
3672                            }
3673                            domains.addAll(filter.getHostsList());
3674                        }
3675                    }
3676                }
3677
3678                if (domains != null && domains.size() > 0) {
3679                    if (DEBUG_DOMAIN_VERIFICATION) {
3680                        Slog.v(TAG, "      + " + packageName);
3681                    }
3682                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3683                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3684                    // and then 'always' in the per-user state actually used for intent resolution.
3685                    final IntentFilterVerificationInfo ivi;
3686                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3687                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3688                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3689                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3690                } else {
3691                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3692                            + "' does not handle web links");
3693                }
3694            } else {
3695                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3696            }
3697        }
3698
3699        scheduleWritePackageRestrictionsLocked(userId);
3700        scheduleWriteSettingsLocked();
3701    }
3702
3703    private void applyFactoryDefaultBrowserLPw(int userId) {
3704        // The default browser app's package name is stored in a string resource,
3705        // with a product-specific overlay used for vendor customization.
3706        String browserPkg = mContext.getResources().getString(
3707                com.android.internal.R.string.default_browser);
3708        if (!TextUtils.isEmpty(browserPkg)) {
3709            // non-empty string => required to be a known package
3710            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3711            if (ps == null) {
3712                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3713                browserPkg = null;
3714            } else {
3715                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3716            }
3717        }
3718
3719        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3720        // default.  If there's more than one, just leave everything alone.
3721        if (browserPkg == null) {
3722            calculateDefaultBrowserLPw(userId);
3723        }
3724    }
3725
3726    private void calculateDefaultBrowserLPw(int userId) {
3727        List<String> allBrowsers = resolveAllBrowserApps(userId);
3728        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3729        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3730    }
3731
3732    private List<String> resolveAllBrowserApps(int userId) {
3733        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3734        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3735                PackageManager.MATCH_ALL, userId);
3736
3737        final int count = list.size();
3738        List<String> result = new ArrayList<String>(count);
3739        for (int i=0; i<count; i++) {
3740            ResolveInfo info = list.get(i);
3741            if (info.activityInfo == null
3742                    || !info.handleAllWebDataURI
3743                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3744                    || result.contains(info.activityInfo.packageName)) {
3745                continue;
3746            }
3747            result.add(info.activityInfo.packageName);
3748        }
3749
3750        return result;
3751    }
3752
3753    private boolean packageIsBrowser(String packageName, int userId) {
3754        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3755                PackageManager.MATCH_ALL, userId);
3756        final int N = list.size();
3757        for (int i = 0; i < N; i++) {
3758            ResolveInfo info = list.get(i);
3759            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3760                return true;
3761            }
3762        }
3763        return false;
3764    }
3765
3766    private void checkDefaultBrowser() {
3767        final int myUserId = UserHandle.myUserId();
3768        final String packageName = getDefaultBrowserPackageName(myUserId);
3769        if (packageName != null) {
3770            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3771            if (info == null) {
3772                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3773                synchronized (mPackages) {
3774                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3775                }
3776            }
3777        }
3778    }
3779
3780    @Override
3781    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3782            throws RemoteException {
3783        try {
3784            return super.onTransact(code, data, reply, flags);
3785        } catch (RuntimeException e) {
3786            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3787                Slog.wtf(TAG, "Package Manager Crash", e);
3788            }
3789            throw e;
3790        }
3791    }
3792
3793    static int[] appendInts(int[] cur, int[] add) {
3794        if (add == null) return cur;
3795        if (cur == null) return add;
3796        final int N = add.length;
3797        for (int i=0; i<N; i++) {
3798            cur = appendInt(cur, add[i]);
3799        }
3800        return cur;
3801    }
3802
3803    /**
3804     * Returns whether or not a full application can see an instant application.
3805     * <p>
3806     * Currently, there are three cases in which this can occur:
3807     * <ol>
3808     * <li>The calling application is a "special" process. The special
3809     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3810     *     and {@code 0}</li>
3811     * <li>The calling application has the permission
3812     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3813     * <li>The calling application is the default launcher on the
3814     *     system partition.</li>
3815     * </ol>
3816     */
3817    private boolean canViewInstantApps(int callingUid, int userId) {
3818        if (callingUid == Process.SYSTEM_UID
3819                || callingUid == Process.SHELL_UID
3820                || callingUid == Process.ROOT_UID) {
3821            return true;
3822        }
3823        if (mContext.checkCallingOrSelfPermission(
3824                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3825            return true;
3826        }
3827        if (mContext.checkCallingOrSelfPermission(
3828                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3829            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3830            if (homeComponent != null
3831                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3832                return true;
3833            }
3834        }
3835        return false;
3836    }
3837
3838    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3839        if (!sUserManager.exists(userId)) return null;
3840        if (ps == null) {
3841            return null;
3842        }
3843        PackageParser.Package p = ps.pkg;
3844        if (p == null) {
3845            return null;
3846        }
3847        final int callingUid = Binder.getCallingUid();
3848        // Filter out ephemeral app metadata:
3849        //   * The system/shell/root can see metadata for any app
3850        //   * An installed app can see metadata for 1) other installed apps
3851        //     and 2) ephemeral apps that have explicitly interacted with it
3852        //   * Ephemeral apps can only see their own data and exposed installed apps
3853        //   * Holding a signature permission allows seeing instant apps
3854        if (filterAppAccessLPr(ps, callingUid, userId)) {
3855            return null;
3856        }
3857
3858        final PermissionsState permissionsState = ps.getPermissionsState();
3859
3860        // Compute GIDs only if requested
3861        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3862                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3863        // Compute granted permissions only if package has requested permissions
3864        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3865                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3866        final PackageUserState state = ps.readUserState(userId);
3867
3868        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3869                && ps.isSystem()) {
3870            flags |= MATCH_ANY_USER;
3871        }
3872
3873        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3874                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3875
3876        if (packageInfo == null) {
3877            return null;
3878        }
3879
3880        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3881                resolveExternalPackageNameLPr(p);
3882
3883        return packageInfo;
3884    }
3885
3886    @Override
3887    public void checkPackageStartable(String packageName, int userId) {
3888        final int callingUid = Binder.getCallingUid();
3889        if (getInstantAppPackageName(callingUid) != null) {
3890            throw new SecurityException("Instant applications don't have access to this method");
3891        }
3892        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3893        synchronized (mPackages) {
3894            final PackageSetting ps = mSettings.mPackages.get(packageName);
3895            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3896                throw new SecurityException("Package " + packageName + " was not found!");
3897            }
3898
3899            if (!ps.getInstalled(userId)) {
3900                throw new SecurityException(
3901                        "Package " + packageName + " was not installed for user " + userId + "!");
3902            }
3903
3904            if (mSafeMode && !ps.isSystem()) {
3905                throw new SecurityException("Package " + packageName + " not a system app!");
3906            }
3907
3908            if (mFrozenPackages.contains(packageName)) {
3909                throw new SecurityException("Package " + packageName + " is currently frozen!");
3910            }
3911
3912            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3913                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3914            }
3915        }
3916    }
3917
3918    @Override
3919    public boolean isPackageAvailable(String packageName, int userId) {
3920        if (!sUserManager.exists(userId)) return false;
3921        final int callingUid = Binder.getCallingUid();
3922        enforceCrossUserPermission(callingUid, userId,
3923                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3924        synchronized (mPackages) {
3925            PackageParser.Package p = mPackages.get(packageName);
3926            if (p != null) {
3927                final PackageSetting ps = (PackageSetting) p.mExtras;
3928                if (filterAppAccessLPr(ps, callingUid, userId)) {
3929                    return false;
3930                }
3931                if (ps != null) {
3932                    final PackageUserState state = ps.readUserState(userId);
3933                    if (state != null) {
3934                        return PackageParser.isAvailable(state);
3935                    }
3936                }
3937            }
3938        }
3939        return false;
3940    }
3941
3942    @Override
3943    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3944        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3945                flags, Binder.getCallingUid(), userId);
3946    }
3947
3948    @Override
3949    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3950            int flags, int userId) {
3951        return getPackageInfoInternal(versionedPackage.getPackageName(),
3952                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3953    }
3954
3955    /**
3956     * Important: The provided filterCallingUid is used exclusively to filter out packages
3957     * that can be seen based on user state. It's typically the original caller uid prior
3958     * to clearing. Because it can only be provided by trusted code, it's value can be
3959     * trusted and will be used as-is; unlike userId which will be validated by this method.
3960     */
3961    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3962            int flags, int filterCallingUid, int userId) {
3963        if (!sUserManager.exists(userId)) return null;
3964        flags = updateFlagsForPackage(flags, userId, packageName);
3965        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3966                false /* requireFullPermission */, false /* checkShell */, "get package info");
3967
3968        // reader
3969        synchronized (mPackages) {
3970            // Normalize package name to handle renamed packages and static libs
3971            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3972
3973            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3974            if (matchFactoryOnly) {
3975                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3976                if (ps != null) {
3977                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3978                        return null;
3979                    }
3980                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3981                        return null;
3982                    }
3983                    return generatePackageInfo(ps, flags, userId);
3984                }
3985            }
3986
3987            PackageParser.Package p = mPackages.get(packageName);
3988            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3989                return null;
3990            }
3991            if (DEBUG_PACKAGE_INFO)
3992                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3993            if (p != null) {
3994                final PackageSetting ps = (PackageSetting) p.mExtras;
3995                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3996                    return null;
3997                }
3998                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3999                    return null;
4000                }
4001                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4002            }
4003            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4004                final PackageSetting ps = mSettings.mPackages.get(packageName);
4005                if (ps == null) return null;
4006                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4007                    return null;
4008                }
4009                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4010                    return null;
4011                }
4012                return generatePackageInfo(ps, flags, userId);
4013            }
4014        }
4015        return null;
4016    }
4017
4018    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4019        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4020            return true;
4021        }
4022        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4023            return true;
4024        }
4025        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4026            return true;
4027        }
4028        return false;
4029    }
4030
4031    private boolean isComponentVisibleToInstantApp(
4032            @Nullable ComponentName component, @ComponentType int type) {
4033        if (type == TYPE_ACTIVITY) {
4034            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4035            return activity != null
4036                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4037                    : false;
4038        } else if (type == TYPE_RECEIVER) {
4039            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4040            return activity != null
4041                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4042                    : false;
4043        } else if (type == TYPE_SERVICE) {
4044            final PackageParser.Service service = mServices.mServices.get(component);
4045            return service != null
4046                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4047                    : false;
4048        } else if (type == TYPE_PROVIDER) {
4049            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4050            return provider != null
4051                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4052                    : false;
4053        } else if (type == TYPE_UNKNOWN) {
4054            return isComponentVisibleToInstantApp(component);
4055        }
4056        return false;
4057    }
4058
4059    /**
4060     * Returns whether or not access to the application should be filtered.
4061     * <p>
4062     * Access may be limited based upon whether the calling or target applications
4063     * are instant applications.
4064     *
4065     * @see #canAccessInstantApps(int)
4066     */
4067    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4068            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4069        // if we're in an isolated process, get the real calling UID
4070        if (Process.isIsolated(callingUid)) {
4071            callingUid = mIsolatedOwners.get(callingUid);
4072        }
4073        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4074        final boolean callerIsInstantApp = instantAppPkgName != null;
4075        if (ps == null) {
4076            if (callerIsInstantApp) {
4077                // pretend the application exists, but, needs to be filtered
4078                return true;
4079            }
4080            return false;
4081        }
4082        // if the target and caller are the same application, don't filter
4083        if (isCallerSameApp(ps.name, callingUid)) {
4084            return false;
4085        }
4086        if (callerIsInstantApp) {
4087            // request for a specific component; if it hasn't been explicitly exposed, filter
4088            if (component != null) {
4089                return !isComponentVisibleToInstantApp(component, componentType);
4090            }
4091            // request for application; if no components have been explicitly exposed, filter
4092            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4093        }
4094        if (ps.getInstantApp(userId)) {
4095            // caller can see all components of all instant applications, don't filter
4096            if (canViewInstantApps(callingUid, userId)) {
4097                return false;
4098            }
4099            // request for a specific instant application component, filter
4100            if (component != null) {
4101                return true;
4102            }
4103            // request for an instant application; if the caller hasn't been granted access, filter
4104            return !mInstantAppRegistry.isInstantAccessGranted(
4105                    userId, UserHandle.getAppId(callingUid), ps.appId);
4106        }
4107        return false;
4108    }
4109
4110    /**
4111     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4112     */
4113    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4114        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4115    }
4116
4117    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4118            int flags) {
4119        // Callers can access only the libs they depend on, otherwise they need to explicitly
4120        // ask for the shared libraries given the caller is allowed to access all static libs.
4121        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4122            // System/shell/root get to see all static libs
4123            final int appId = UserHandle.getAppId(uid);
4124            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4125                    || appId == Process.ROOT_UID) {
4126                return false;
4127            }
4128        }
4129
4130        // No package means no static lib as it is always on internal storage
4131        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4132            return false;
4133        }
4134
4135        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4136                ps.pkg.staticSharedLibVersion);
4137        if (libEntry == null) {
4138            return false;
4139        }
4140
4141        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4142        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4143        if (uidPackageNames == null) {
4144            return true;
4145        }
4146
4147        for (String uidPackageName : uidPackageNames) {
4148            if (ps.name.equals(uidPackageName)) {
4149                return false;
4150            }
4151            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4152            if (uidPs != null) {
4153                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4154                        libEntry.info.getName());
4155                if (index < 0) {
4156                    continue;
4157                }
4158                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4159                    return false;
4160                }
4161            }
4162        }
4163        return true;
4164    }
4165
4166    @Override
4167    public String[] currentToCanonicalPackageNames(String[] names) {
4168        final int callingUid = Binder.getCallingUid();
4169        if (getInstantAppPackageName(callingUid) != null) {
4170            return names;
4171        }
4172        final String[] out = new String[names.length];
4173        // reader
4174        synchronized (mPackages) {
4175            final int callingUserId = UserHandle.getUserId(callingUid);
4176            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4177            for (int i=names.length-1; i>=0; i--) {
4178                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4179                boolean translateName = false;
4180                if (ps != null && ps.realName != null) {
4181                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4182                    translateName = !targetIsInstantApp
4183                            || canViewInstantApps
4184                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4185                                    UserHandle.getAppId(callingUid), ps.appId);
4186                }
4187                out[i] = translateName ? ps.realName : names[i];
4188            }
4189        }
4190        return out;
4191    }
4192
4193    @Override
4194    public String[] canonicalToCurrentPackageNames(String[] names) {
4195        final int callingUid = Binder.getCallingUid();
4196        if (getInstantAppPackageName(callingUid) != null) {
4197            return names;
4198        }
4199        final String[] out = new String[names.length];
4200        // reader
4201        synchronized (mPackages) {
4202            final int callingUserId = UserHandle.getUserId(callingUid);
4203            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4204            for (int i=names.length-1; i>=0; i--) {
4205                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4206                boolean translateName = false;
4207                if (cur != null) {
4208                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4209                    final boolean targetIsInstantApp =
4210                            ps != null && ps.getInstantApp(callingUserId);
4211                    translateName = !targetIsInstantApp
4212                            || canViewInstantApps
4213                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4214                                    UserHandle.getAppId(callingUid), ps.appId);
4215                }
4216                out[i] = translateName ? cur : names[i];
4217            }
4218        }
4219        return out;
4220    }
4221
4222    @Override
4223    public int getPackageUid(String packageName, int flags, int userId) {
4224        if (!sUserManager.exists(userId)) return -1;
4225        final int callingUid = Binder.getCallingUid();
4226        flags = updateFlagsForPackage(flags, userId, packageName);
4227        enforceCrossUserPermission(callingUid, userId,
4228                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4229
4230        // reader
4231        synchronized (mPackages) {
4232            final PackageParser.Package p = mPackages.get(packageName);
4233            if (p != null && p.isMatch(flags)) {
4234                PackageSetting ps = (PackageSetting) p.mExtras;
4235                if (filterAppAccessLPr(ps, callingUid, userId)) {
4236                    return -1;
4237                }
4238                return UserHandle.getUid(userId, p.applicationInfo.uid);
4239            }
4240            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4241                final PackageSetting ps = mSettings.mPackages.get(packageName);
4242                if (ps != null && ps.isMatch(flags)
4243                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4244                    return UserHandle.getUid(userId, ps.appId);
4245                }
4246            }
4247        }
4248
4249        return -1;
4250    }
4251
4252    @Override
4253    public int[] getPackageGids(String packageName, int flags, int userId) {
4254        if (!sUserManager.exists(userId)) return null;
4255        final int callingUid = Binder.getCallingUid();
4256        flags = updateFlagsForPackage(flags, userId, packageName);
4257        enforceCrossUserPermission(callingUid, userId,
4258                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4259
4260        // reader
4261        synchronized (mPackages) {
4262            final PackageParser.Package p = mPackages.get(packageName);
4263            if (p != null && p.isMatch(flags)) {
4264                PackageSetting ps = (PackageSetting) p.mExtras;
4265                if (filterAppAccessLPr(ps, callingUid, userId)) {
4266                    return null;
4267                }
4268                // TODO: Shouldn't this be checking for package installed state for userId and
4269                // return null?
4270                return ps.getPermissionsState().computeGids(userId);
4271            }
4272            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4273                final PackageSetting ps = mSettings.mPackages.get(packageName);
4274                if (ps != null && ps.isMatch(flags)
4275                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4276                    return ps.getPermissionsState().computeGids(userId);
4277                }
4278            }
4279        }
4280
4281        return null;
4282    }
4283
4284    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4285        if (bp.perm != null) {
4286            return PackageParser.generatePermissionInfo(bp.perm, flags);
4287        }
4288        PermissionInfo pi = new PermissionInfo();
4289        pi.name = bp.name;
4290        pi.packageName = bp.sourcePackage;
4291        pi.nonLocalizedLabel = bp.name;
4292        pi.protectionLevel = bp.protectionLevel;
4293        return pi;
4294    }
4295
4296    @Override
4297    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4298        final int callingUid = Binder.getCallingUid();
4299        if (getInstantAppPackageName(callingUid) != null) {
4300            return null;
4301        }
4302        // reader
4303        synchronized (mPackages) {
4304            final BasePermission p = mSettings.mPermissions.get(name);
4305            if (p == null) {
4306                return null;
4307            }
4308            // If the caller is an app that targets pre 26 SDK drop protection flags.
4309            PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4310            if (permissionInfo != null) {
4311                final int protectionLevel = adjustPermissionProtectionFlagsLPr(
4312                        permissionInfo.protectionLevel, packageName, callingUid);
4313                if (permissionInfo.protectionLevel != protectionLevel) {
4314                    // If we return different protection level, don't use the cached info
4315                    if (p.perm != null && p.perm.info == permissionInfo) {
4316                        permissionInfo = new PermissionInfo(permissionInfo);
4317                    }
4318                    permissionInfo.protectionLevel = protectionLevel;
4319                }
4320            }
4321            return permissionInfo;
4322        }
4323    }
4324
4325    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4326            String packageName, int uid) {
4327        // Signature permission flags area always reported
4328        final int protectionLevelMasked = protectionLevel
4329                & (PermissionInfo.PROTECTION_NORMAL
4330                | PermissionInfo.PROTECTION_DANGEROUS
4331                | PermissionInfo.PROTECTION_SIGNATURE);
4332        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4333            return protectionLevel;
4334        }
4335
4336        // System sees all flags.
4337        final int appId = UserHandle.getAppId(uid);
4338        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4339                || appId == Process.SHELL_UID) {
4340            return protectionLevel;
4341        }
4342
4343        // Normalize package name to handle renamed packages and static libs
4344        packageName = resolveInternalPackageNameLPr(packageName,
4345                PackageManager.VERSION_CODE_HIGHEST);
4346
4347        // Apps that target O see flags for all protection levels.
4348        final PackageSetting ps = mSettings.mPackages.get(packageName);
4349        if (ps == null) {
4350            return protectionLevel;
4351        }
4352        if (ps.appId != appId) {
4353            return protectionLevel;
4354        }
4355
4356        final PackageParser.Package pkg = mPackages.get(packageName);
4357        if (pkg == null) {
4358            return protectionLevel;
4359        }
4360        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4361            return protectionLevelMasked;
4362        }
4363
4364        return protectionLevel;
4365    }
4366
4367    @Override
4368    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4369            int flags) {
4370        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4371            return null;
4372        }
4373        // reader
4374        synchronized (mPackages) {
4375            if (group != null && !mPermissionGroups.containsKey(group)) {
4376                // This is thrown as NameNotFoundException
4377                return null;
4378            }
4379
4380            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4381            for (BasePermission p : mSettings.mPermissions.values()) {
4382                if (group == null) {
4383                    if (p.perm == null || p.perm.info.group == null) {
4384                        out.add(generatePermissionInfo(p, flags));
4385                    }
4386                } else {
4387                    if (p.perm != null && group.equals(p.perm.info.group)) {
4388                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4389                    }
4390                }
4391            }
4392            return new ParceledListSlice<>(out);
4393        }
4394    }
4395
4396    @Override
4397    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4398        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4399            return null;
4400        }
4401        // reader
4402        synchronized (mPackages) {
4403            return PackageParser.generatePermissionGroupInfo(
4404                    mPermissionGroups.get(name), flags);
4405        }
4406    }
4407
4408    @Override
4409    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4410        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4411            return ParceledListSlice.emptyList();
4412        }
4413        // reader
4414        synchronized (mPackages) {
4415            final int N = mPermissionGroups.size();
4416            ArrayList<PermissionGroupInfo> out
4417                    = new ArrayList<PermissionGroupInfo>(N);
4418            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4419                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4420            }
4421            return new ParceledListSlice<>(out);
4422        }
4423    }
4424
4425    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4426            int filterCallingUid, int userId) {
4427        if (!sUserManager.exists(userId)) return null;
4428        PackageSetting ps = mSettings.mPackages.get(packageName);
4429        if (ps != null) {
4430            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4431                return null;
4432            }
4433            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4434                return null;
4435            }
4436            if (ps.pkg == null) {
4437                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4438                if (pInfo != null) {
4439                    return pInfo.applicationInfo;
4440                }
4441                return null;
4442            }
4443            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4444                    ps.readUserState(userId), userId);
4445            if (ai != null) {
4446                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4447            }
4448            return ai;
4449        }
4450        return null;
4451    }
4452
4453    @Override
4454    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4455        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4456    }
4457
4458    /**
4459     * Important: The provided filterCallingUid is used exclusively to filter out applications
4460     * that can be seen based on user state. It's typically the original caller uid prior
4461     * to clearing. Because it can only be provided by trusted code, it's value can be
4462     * trusted and will be used as-is; unlike userId which will be validated by this method.
4463     */
4464    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4465            int filterCallingUid, int userId) {
4466        if (!sUserManager.exists(userId)) return null;
4467        flags = updateFlagsForApplication(flags, userId, packageName);
4468        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4469                false /* requireFullPermission */, false /* checkShell */, "get application info");
4470
4471        // writer
4472        synchronized (mPackages) {
4473            // Normalize package name to handle renamed packages and static libs
4474            packageName = resolveInternalPackageNameLPr(packageName,
4475                    PackageManager.VERSION_CODE_HIGHEST);
4476
4477            PackageParser.Package p = mPackages.get(packageName);
4478            if (DEBUG_PACKAGE_INFO) Log.v(
4479                    TAG, "getApplicationInfo " + packageName
4480                    + ": " + p);
4481            if (p != null) {
4482                PackageSetting ps = mSettings.mPackages.get(packageName);
4483                if (ps == null) return null;
4484                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4485                    return null;
4486                }
4487                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4488                    return null;
4489                }
4490                // Note: isEnabledLP() does not apply here - always return info
4491                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4492                        p, flags, ps.readUserState(userId), userId);
4493                if (ai != null) {
4494                    ai.packageName = resolveExternalPackageNameLPr(p);
4495                }
4496                return ai;
4497            }
4498            if ("android".equals(packageName)||"system".equals(packageName)) {
4499                return mAndroidApplication;
4500            }
4501            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4502                // Already generates the external package name
4503                return generateApplicationInfoFromSettingsLPw(packageName,
4504                        flags, filterCallingUid, userId);
4505            }
4506        }
4507        return null;
4508    }
4509
4510    private String normalizePackageNameLPr(String packageName) {
4511        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4512        return normalizedPackageName != null ? normalizedPackageName : packageName;
4513    }
4514
4515    @Override
4516    public void deletePreloadsFileCache() {
4517        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4518            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4519        }
4520        File dir = Environment.getDataPreloadsFileCacheDirectory();
4521        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4522        FileUtils.deleteContents(dir);
4523    }
4524
4525    @Override
4526    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4527            final int storageFlags, final IPackageDataObserver observer) {
4528        mContext.enforceCallingOrSelfPermission(
4529                android.Manifest.permission.CLEAR_APP_CACHE, null);
4530        mHandler.post(() -> {
4531            boolean success = false;
4532            try {
4533                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4534                success = true;
4535            } catch (IOException e) {
4536                Slog.w(TAG, e);
4537            }
4538            if (observer != null) {
4539                try {
4540                    observer.onRemoveCompleted(null, success);
4541                } catch (RemoteException e) {
4542                    Slog.w(TAG, e);
4543                }
4544            }
4545        });
4546    }
4547
4548    @Override
4549    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4550            final int storageFlags, final IntentSender pi) {
4551        mContext.enforceCallingOrSelfPermission(
4552                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4553        mHandler.post(() -> {
4554            boolean success = false;
4555            try {
4556                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4557                success = true;
4558            } catch (IOException e) {
4559                Slog.w(TAG, e);
4560            }
4561            if (pi != null) {
4562                try {
4563                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4564                } catch (SendIntentException e) {
4565                    Slog.w(TAG, e);
4566                }
4567            }
4568        });
4569    }
4570
4571    /**
4572     * Blocking call to clear various types of cached data across the system
4573     * until the requested bytes are available.
4574     */
4575    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4576        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4577        final File file = storage.findPathForUuid(volumeUuid);
4578        if (file.getUsableSpace() >= bytes) return;
4579
4580        if (ENABLE_FREE_CACHE_V2) {
4581            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4582                    volumeUuid);
4583            final boolean aggressive = (storageFlags
4584                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4585            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4586
4587            // 1. Pre-flight to determine if we have any chance to succeed
4588            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4589            if (internalVolume && (aggressive || SystemProperties
4590                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4591                deletePreloadsFileCache();
4592                if (file.getUsableSpace() >= bytes) return;
4593            }
4594
4595            // 3. Consider parsed APK data (aggressive only)
4596            if (internalVolume && aggressive) {
4597                FileUtils.deleteContents(mCacheDir);
4598                if (file.getUsableSpace() >= bytes) return;
4599            }
4600
4601            // 4. Consider cached app data (above quotas)
4602            try {
4603                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4604                        Installer.FLAG_FREE_CACHE_V2);
4605            } catch (InstallerException ignored) {
4606            }
4607            if (file.getUsableSpace() >= bytes) return;
4608
4609            // 5. Consider shared libraries with refcount=0 and age>min cache period
4610            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4611                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4612                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4613                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4614                return;
4615            }
4616
4617            // 6. Consider dexopt output (aggressive only)
4618            // TODO: Implement
4619
4620            // 7. Consider installed instant apps unused longer than min cache period
4621            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4622                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4623                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4624                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4625                return;
4626            }
4627
4628            // 8. Consider cached app data (below quotas)
4629            try {
4630                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4631                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4632            } catch (InstallerException ignored) {
4633            }
4634            if (file.getUsableSpace() >= bytes) return;
4635
4636            // 9. Consider DropBox entries
4637            // TODO: Implement
4638
4639            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4640            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4641                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4642                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4643                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4644                return;
4645            }
4646        } else {
4647            try {
4648                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4649            } catch (InstallerException ignored) {
4650            }
4651            if (file.getUsableSpace() >= bytes) return;
4652        }
4653
4654        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4655    }
4656
4657    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4658            throws IOException {
4659        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4660        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4661
4662        List<VersionedPackage> packagesToDelete = null;
4663        final long now = System.currentTimeMillis();
4664
4665        synchronized (mPackages) {
4666            final int[] allUsers = sUserManager.getUserIds();
4667            final int libCount = mSharedLibraries.size();
4668            for (int i = 0; i < libCount; i++) {
4669                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4670                if (versionedLib == null) {
4671                    continue;
4672                }
4673                final int versionCount = versionedLib.size();
4674                for (int j = 0; j < versionCount; j++) {
4675                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4676                    // Skip packages that are not static shared libs.
4677                    if (!libInfo.isStatic()) {
4678                        break;
4679                    }
4680                    // Important: We skip static shared libs used for some user since
4681                    // in such a case we need to keep the APK on the device. The check for
4682                    // a lib being used for any user is performed by the uninstall call.
4683                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4684                    // Resolve the package name - we use synthetic package names internally
4685                    final String internalPackageName = resolveInternalPackageNameLPr(
4686                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4687                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4688                    // Skip unused static shared libs cached less than the min period
4689                    // to prevent pruning a lib needed by a subsequently installed package.
4690                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4691                        continue;
4692                    }
4693                    if (packagesToDelete == null) {
4694                        packagesToDelete = new ArrayList<>();
4695                    }
4696                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4697                            declaringPackage.getVersionCode()));
4698                }
4699            }
4700        }
4701
4702        if (packagesToDelete != null) {
4703            final int packageCount = packagesToDelete.size();
4704            for (int i = 0; i < packageCount; i++) {
4705                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4706                // Delete the package synchronously (will fail of the lib used for any user).
4707                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4708                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4709                                == PackageManager.DELETE_SUCCEEDED) {
4710                    if (volume.getUsableSpace() >= neededSpace) {
4711                        return true;
4712                    }
4713                }
4714            }
4715        }
4716
4717        return false;
4718    }
4719
4720    /**
4721     * Update given flags based on encryption status of current user.
4722     */
4723    private int updateFlags(int flags, int userId) {
4724        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4725                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4726            // Caller expressed an explicit opinion about what encryption
4727            // aware/unaware components they want to see, so fall through and
4728            // give them what they want
4729        } else {
4730            // Caller expressed no opinion, so match based on user state
4731            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4732                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4733            } else {
4734                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4735            }
4736        }
4737        return flags;
4738    }
4739
4740    private UserManagerInternal getUserManagerInternal() {
4741        if (mUserManagerInternal == null) {
4742            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4743        }
4744        return mUserManagerInternal;
4745    }
4746
4747    private DeviceIdleController.LocalService getDeviceIdleController() {
4748        if (mDeviceIdleController == null) {
4749            mDeviceIdleController =
4750                    LocalServices.getService(DeviceIdleController.LocalService.class);
4751        }
4752        return mDeviceIdleController;
4753    }
4754
4755    /**
4756     * Update given flags when being used to request {@link PackageInfo}.
4757     */
4758    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4759        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4760        boolean triaged = true;
4761        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4762                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4763            // Caller is asking for component details, so they'd better be
4764            // asking for specific encryption matching behavior, or be triaged
4765            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4766                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4767                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4768                triaged = false;
4769            }
4770        }
4771        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4772                | PackageManager.MATCH_SYSTEM_ONLY
4773                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4774            triaged = false;
4775        }
4776        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4777            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4778                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4779                    + Debug.getCallers(5));
4780        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4781                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4782            // If the caller wants all packages and has a restricted profile associated with it,
4783            // then match all users. This is to make sure that launchers that need to access work
4784            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4785            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4786            flags |= PackageManager.MATCH_ANY_USER;
4787        }
4788        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4789            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4790                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4791        }
4792        return updateFlags(flags, userId);
4793    }
4794
4795    /**
4796     * Update given flags when being used to request {@link ApplicationInfo}.
4797     */
4798    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4799        return updateFlagsForPackage(flags, userId, cookie);
4800    }
4801
4802    /**
4803     * Update given flags when being used to request {@link ComponentInfo}.
4804     */
4805    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4806        if (cookie instanceof Intent) {
4807            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4808                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4809            }
4810        }
4811
4812        boolean triaged = true;
4813        // Caller is asking for component details, so they'd better be
4814        // asking for specific encryption matching behavior, or be triaged
4815        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4816                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4817                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4818            triaged = false;
4819        }
4820        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4821            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4822                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4823        }
4824
4825        return updateFlags(flags, userId);
4826    }
4827
4828    /**
4829     * Update given intent when being used to request {@link ResolveInfo}.
4830     */
4831    private Intent updateIntentForResolve(Intent intent) {
4832        if (intent.getSelector() != null) {
4833            intent = intent.getSelector();
4834        }
4835        if (DEBUG_PREFERRED) {
4836            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4837        }
4838        return intent;
4839    }
4840
4841    /**
4842     * Update given flags when being used to request {@link ResolveInfo}.
4843     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4844     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4845     * flag set. However, this flag is only honoured in three circumstances:
4846     * <ul>
4847     * <li>when called from a system process</li>
4848     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4849     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4850     * action and a {@code android.intent.category.BROWSABLE} category</li>
4851     * </ul>
4852     */
4853    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4854        return updateFlagsForResolve(flags, userId, intent, callingUid,
4855                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4856    }
4857    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4858            boolean wantInstantApps) {
4859        return updateFlagsForResolve(flags, userId, intent, callingUid,
4860                wantInstantApps, false /*onlyExposedExplicitly*/);
4861    }
4862    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4863            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4864        // Safe mode means we shouldn't match any third-party components
4865        if (mSafeMode) {
4866            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4867        }
4868        if (getInstantAppPackageName(callingUid) != null) {
4869            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4870            if (onlyExposedExplicitly) {
4871                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4872            }
4873            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4874            flags |= PackageManager.MATCH_INSTANT;
4875        } else {
4876            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4877            final boolean allowMatchInstant =
4878                    (wantInstantApps
4879                            && Intent.ACTION_VIEW.equals(intent.getAction())
4880                            && hasWebURI(intent))
4881                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4882            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4883                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4884            if (!allowMatchInstant) {
4885                flags &= ~PackageManager.MATCH_INSTANT;
4886            }
4887        }
4888        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4889    }
4890
4891    @Override
4892    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4893        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4894    }
4895
4896    /**
4897     * Important: The provided filterCallingUid is used exclusively to filter out activities
4898     * that can be seen based on user state. It's typically the original caller uid prior
4899     * to clearing. Because it can only be provided by trusted code, it's value can be
4900     * trusted and will be used as-is; unlike userId which will be validated by this method.
4901     */
4902    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4903            int filterCallingUid, int userId) {
4904        if (!sUserManager.exists(userId)) return null;
4905        flags = updateFlagsForComponent(flags, userId, component);
4906        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4907                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4908        synchronized (mPackages) {
4909            PackageParser.Activity a = mActivities.mActivities.get(component);
4910
4911            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4912            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4913                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4914                if (ps == null) return null;
4915                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4916                    return null;
4917                }
4918                return PackageParser.generateActivityInfo(
4919                        a, flags, ps.readUserState(userId), userId);
4920            }
4921            if (mResolveComponentName.equals(component)) {
4922                return PackageParser.generateActivityInfo(
4923                        mResolveActivity, flags, new PackageUserState(), userId);
4924            }
4925        }
4926        return null;
4927    }
4928
4929    @Override
4930    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4931            String resolvedType) {
4932        synchronized (mPackages) {
4933            if (component.equals(mResolveComponentName)) {
4934                // The resolver supports EVERYTHING!
4935                return true;
4936            }
4937            final int callingUid = Binder.getCallingUid();
4938            final int callingUserId = UserHandle.getUserId(callingUid);
4939            PackageParser.Activity a = mActivities.mActivities.get(component);
4940            if (a == null) {
4941                return false;
4942            }
4943            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4944            if (ps == null) {
4945                return false;
4946            }
4947            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4948                return false;
4949            }
4950            for (int i=0; i<a.intents.size(); i++) {
4951                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4952                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4953                    return true;
4954                }
4955            }
4956            return false;
4957        }
4958    }
4959
4960    @Override
4961    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4962        if (!sUserManager.exists(userId)) return null;
4963        final int callingUid = Binder.getCallingUid();
4964        flags = updateFlagsForComponent(flags, userId, component);
4965        enforceCrossUserPermission(callingUid, userId,
4966                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4967        synchronized (mPackages) {
4968            PackageParser.Activity a = mReceivers.mActivities.get(component);
4969            if (DEBUG_PACKAGE_INFO) Log.v(
4970                TAG, "getReceiverInfo " + component + ": " + a);
4971            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4972                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4973                if (ps == null) return null;
4974                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4975                    return null;
4976                }
4977                return PackageParser.generateActivityInfo(
4978                        a, flags, ps.readUserState(userId), userId);
4979            }
4980        }
4981        return null;
4982    }
4983
4984    @Override
4985    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4986            int flags, int userId) {
4987        if (!sUserManager.exists(userId)) return null;
4988        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4989        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4990            return null;
4991        }
4992
4993        flags = updateFlagsForPackage(flags, userId, null);
4994
4995        final boolean canSeeStaticLibraries =
4996                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4997                        == PERMISSION_GRANTED
4998                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4999                        == PERMISSION_GRANTED
5000                || canRequestPackageInstallsInternal(packageName,
5001                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
5002                        false  /* throwIfPermNotDeclared*/)
5003                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
5004                        == PERMISSION_GRANTED;
5005
5006        synchronized (mPackages) {
5007            List<SharedLibraryInfo> result = null;
5008
5009            final int libCount = mSharedLibraries.size();
5010            for (int i = 0; i < libCount; i++) {
5011                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5012                if (versionedLib == null) {
5013                    continue;
5014                }
5015
5016                final int versionCount = versionedLib.size();
5017                for (int j = 0; j < versionCount; j++) {
5018                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5019                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5020                        break;
5021                    }
5022                    final long identity = Binder.clearCallingIdentity();
5023                    try {
5024                        PackageInfo packageInfo = getPackageInfoVersioned(
5025                                libInfo.getDeclaringPackage(), flags
5026                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5027                        if (packageInfo == null) {
5028                            continue;
5029                        }
5030                    } finally {
5031                        Binder.restoreCallingIdentity(identity);
5032                    }
5033
5034                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5035                            libInfo.getVersion(), libInfo.getType(),
5036                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5037                            flags, userId));
5038
5039                    if (result == null) {
5040                        result = new ArrayList<>();
5041                    }
5042                    result.add(resLibInfo);
5043                }
5044            }
5045
5046            return result != null ? new ParceledListSlice<>(result) : null;
5047        }
5048    }
5049
5050    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5051            SharedLibraryInfo libInfo, int flags, int userId) {
5052        List<VersionedPackage> versionedPackages = null;
5053        final int packageCount = mSettings.mPackages.size();
5054        for (int i = 0; i < packageCount; i++) {
5055            PackageSetting ps = mSettings.mPackages.valueAt(i);
5056
5057            if (ps == null) {
5058                continue;
5059            }
5060
5061            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5062                continue;
5063            }
5064
5065            final String libName = libInfo.getName();
5066            if (libInfo.isStatic()) {
5067                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5068                if (libIdx < 0) {
5069                    continue;
5070                }
5071                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5072                    continue;
5073                }
5074                if (versionedPackages == null) {
5075                    versionedPackages = new ArrayList<>();
5076                }
5077                // If the dependent is a static shared lib, use the public package name
5078                String dependentPackageName = ps.name;
5079                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5080                    dependentPackageName = ps.pkg.manifestPackageName;
5081                }
5082                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5083            } else if (ps.pkg != null) {
5084                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5085                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5086                    if (versionedPackages == null) {
5087                        versionedPackages = new ArrayList<>();
5088                    }
5089                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5090                }
5091            }
5092        }
5093
5094        return versionedPackages;
5095    }
5096
5097    @Override
5098    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5099        if (!sUserManager.exists(userId)) return null;
5100        final int callingUid = Binder.getCallingUid();
5101        flags = updateFlagsForComponent(flags, userId, component);
5102        enforceCrossUserPermission(callingUid, userId,
5103                false /* requireFullPermission */, false /* checkShell */, "get service info");
5104        synchronized (mPackages) {
5105            PackageParser.Service s = mServices.mServices.get(component);
5106            if (DEBUG_PACKAGE_INFO) Log.v(
5107                TAG, "getServiceInfo " + component + ": " + s);
5108            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5109                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5110                if (ps == null) return null;
5111                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5112                    return null;
5113                }
5114                return PackageParser.generateServiceInfo(
5115                        s, flags, ps.readUserState(userId), userId);
5116            }
5117        }
5118        return null;
5119    }
5120
5121    @Override
5122    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5123        if (!sUserManager.exists(userId)) return null;
5124        final int callingUid = Binder.getCallingUid();
5125        flags = updateFlagsForComponent(flags, userId, component);
5126        enforceCrossUserPermission(callingUid, userId,
5127                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5128        synchronized (mPackages) {
5129            PackageParser.Provider p = mProviders.mProviders.get(component);
5130            if (DEBUG_PACKAGE_INFO) Log.v(
5131                TAG, "getProviderInfo " + component + ": " + p);
5132            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5133                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5134                if (ps == null) return null;
5135                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5136                    return null;
5137                }
5138                return PackageParser.generateProviderInfo(
5139                        p, flags, ps.readUserState(userId), userId);
5140            }
5141        }
5142        return null;
5143    }
5144
5145    @Override
5146    public String[] getSystemSharedLibraryNames() {
5147        // allow instant applications
5148        synchronized (mPackages) {
5149            Set<String> libs = null;
5150            final int libCount = mSharedLibraries.size();
5151            for (int i = 0; i < libCount; i++) {
5152                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5153                if (versionedLib == null) {
5154                    continue;
5155                }
5156                final int versionCount = versionedLib.size();
5157                for (int j = 0; j < versionCount; j++) {
5158                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5159                    if (!libEntry.info.isStatic()) {
5160                        if (libs == null) {
5161                            libs = new ArraySet<>();
5162                        }
5163                        libs.add(libEntry.info.getName());
5164                        break;
5165                    }
5166                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5167                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5168                            UserHandle.getUserId(Binder.getCallingUid()),
5169                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5170                        if (libs == null) {
5171                            libs = new ArraySet<>();
5172                        }
5173                        libs.add(libEntry.info.getName());
5174                        break;
5175                    }
5176                }
5177            }
5178
5179            if (libs != null) {
5180                String[] libsArray = new String[libs.size()];
5181                libs.toArray(libsArray);
5182                return libsArray;
5183            }
5184
5185            return null;
5186        }
5187    }
5188
5189    @Override
5190    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5191        // allow instant applications
5192        synchronized (mPackages) {
5193            return mServicesSystemSharedLibraryPackageName;
5194        }
5195    }
5196
5197    @Override
5198    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5199        // allow instant applications
5200        synchronized (mPackages) {
5201            return mSharedSystemSharedLibraryPackageName;
5202        }
5203    }
5204
5205    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5206        for (int i = userList.length - 1; i >= 0; --i) {
5207            final int userId = userList[i];
5208            // don't add instant app to the list of updates
5209            if (pkgSetting.getInstantApp(userId)) {
5210                continue;
5211            }
5212            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5213            if (changedPackages == null) {
5214                changedPackages = new SparseArray<>();
5215                mChangedPackages.put(userId, changedPackages);
5216            }
5217            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5218            if (sequenceNumbers == null) {
5219                sequenceNumbers = new HashMap<>();
5220                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5221            }
5222            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5223            if (sequenceNumber != null) {
5224                changedPackages.remove(sequenceNumber);
5225            }
5226            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5227            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5228        }
5229        mChangedPackagesSequenceNumber++;
5230    }
5231
5232    @Override
5233    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5234        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5235            return null;
5236        }
5237        synchronized (mPackages) {
5238            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5239                return null;
5240            }
5241            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5242            if (changedPackages == null) {
5243                return null;
5244            }
5245            final List<String> packageNames =
5246                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5247            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5248                final String packageName = changedPackages.get(i);
5249                if (packageName != null) {
5250                    packageNames.add(packageName);
5251                }
5252            }
5253            return packageNames.isEmpty()
5254                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5255        }
5256    }
5257
5258    @Override
5259    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5260        // allow instant applications
5261        ArrayList<FeatureInfo> res;
5262        synchronized (mAvailableFeatures) {
5263            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5264            res.addAll(mAvailableFeatures.values());
5265        }
5266        final FeatureInfo fi = new FeatureInfo();
5267        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5268                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5269        res.add(fi);
5270
5271        return new ParceledListSlice<>(res);
5272    }
5273
5274    @Override
5275    public boolean hasSystemFeature(String name, int version) {
5276        // allow instant applications
5277        synchronized (mAvailableFeatures) {
5278            final FeatureInfo feat = mAvailableFeatures.get(name);
5279            if (feat == null) {
5280                return false;
5281            } else {
5282                return feat.version >= version;
5283            }
5284        }
5285    }
5286
5287    @Override
5288    public int checkPermission(String permName, String pkgName, int userId) {
5289        if (!sUserManager.exists(userId)) {
5290            return PackageManager.PERMISSION_DENIED;
5291        }
5292        final int callingUid = Binder.getCallingUid();
5293
5294        synchronized (mPackages) {
5295            final PackageParser.Package p = mPackages.get(pkgName);
5296            if (p != null && p.mExtras != null) {
5297                final PackageSetting ps = (PackageSetting) p.mExtras;
5298                if (filterAppAccessLPr(ps, callingUid, userId)) {
5299                    return PackageManager.PERMISSION_DENIED;
5300                }
5301                final boolean instantApp = ps.getInstantApp(userId);
5302                final PermissionsState permissionsState = ps.getPermissionsState();
5303                if (permissionsState.hasPermission(permName, userId)) {
5304                    if (instantApp) {
5305                        BasePermission bp = mSettings.mPermissions.get(permName);
5306                        if (bp != null && bp.isInstant()) {
5307                            return PackageManager.PERMISSION_GRANTED;
5308                        }
5309                    } else {
5310                        return PackageManager.PERMISSION_GRANTED;
5311                    }
5312                }
5313                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5314                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5315                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5316                    return PackageManager.PERMISSION_GRANTED;
5317                }
5318            }
5319        }
5320
5321        return PackageManager.PERMISSION_DENIED;
5322    }
5323
5324    @Override
5325    public int checkUidPermission(String permName, int uid) {
5326        final int callingUid = Binder.getCallingUid();
5327        final int callingUserId = UserHandle.getUserId(callingUid);
5328        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5329        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5330        final int userId = UserHandle.getUserId(uid);
5331        if (!sUserManager.exists(userId)) {
5332            return PackageManager.PERMISSION_DENIED;
5333        }
5334
5335        synchronized (mPackages) {
5336            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5337            if (obj != null) {
5338                if (obj instanceof SharedUserSetting) {
5339                    if (isCallerInstantApp) {
5340                        return PackageManager.PERMISSION_DENIED;
5341                    }
5342                } else if (obj instanceof PackageSetting) {
5343                    final PackageSetting ps = (PackageSetting) obj;
5344                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5345                        return PackageManager.PERMISSION_DENIED;
5346                    }
5347                }
5348                final SettingBase settingBase = (SettingBase) obj;
5349                final PermissionsState permissionsState = settingBase.getPermissionsState();
5350                if (permissionsState.hasPermission(permName, userId)) {
5351                    if (isUidInstantApp) {
5352                        BasePermission bp = mSettings.mPermissions.get(permName);
5353                        if (bp != null && bp.isInstant()) {
5354                            return PackageManager.PERMISSION_GRANTED;
5355                        }
5356                    } else {
5357                        return PackageManager.PERMISSION_GRANTED;
5358                    }
5359                }
5360                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5361                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5362                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5363                    return PackageManager.PERMISSION_GRANTED;
5364                }
5365            } else {
5366                ArraySet<String> perms = mSystemPermissions.get(uid);
5367                if (perms != null) {
5368                    if (perms.contains(permName)) {
5369                        return PackageManager.PERMISSION_GRANTED;
5370                    }
5371                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5372                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5373                        return PackageManager.PERMISSION_GRANTED;
5374                    }
5375                }
5376            }
5377        }
5378
5379        return PackageManager.PERMISSION_DENIED;
5380    }
5381
5382    @Override
5383    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5384        if (UserHandle.getCallingUserId() != userId) {
5385            mContext.enforceCallingPermission(
5386                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5387                    "isPermissionRevokedByPolicy for user " + userId);
5388        }
5389
5390        if (checkPermission(permission, packageName, userId)
5391                == PackageManager.PERMISSION_GRANTED) {
5392            return false;
5393        }
5394
5395        final int callingUid = Binder.getCallingUid();
5396        if (getInstantAppPackageName(callingUid) != null) {
5397            if (!isCallerSameApp(packageName, callingUid)) {
5398                return false;
5399            }
5400        } else {
5401            if (isInstantApp(packageName, userId)) {
5402                return false;
5403            }
5404        }
5405
5406        final long identity = Binder.clearCallingIdentity();
5407        try {
5408            final int flags = getPermissionFlags(permission, packageName, userId);
5409            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5410        } finally {
5411            Binder.restoreCallingIdentity(identity);
5412        }
5413    }
5414
5415    @Override
5416    public String getPermissionControllerPackageName() {
5417        synchronized (mPackages) {
5418            return mRequiredInstallerPackage;
5419        }
5420    }
5421
5422    /**
5423     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5424     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5425     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5426     * @param message the message to log on security exception
5427     */
5428    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5429            boolean checkShell, String message) {
5430        if (userId < 0) {
5431            throw new IllegalArgumentException("Invalid userId " + userId);
5432        }
5433        if (checkShell) {
5434            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5435        }
5436        if (userId == UserHandle.getUserId(callingUid)) return;
5437        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5438            if (requireFullPermission) {
5439                mContext.enforceCallingOrSelfPermission(
5440                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5441            } else {
5442                try {
5443                    mContext.enforceCallingOrSelfPermission(
5444                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5445                } catch (SecurityException se) {
5446                    mContext.enforceCallingOrSelfPermission(
5447                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5448                }
5449            }
5450        }
5451    }
5452
5453    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5454        if (callingUid == Process.SHELL_UID) {
5455            if (userHandle >= 0
5456                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5457                throw new SecurityException("Shell does not have permission to access user "
5458                        + userHandle);
5459            } else if (userHandle < 0) {
5460                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5461                        + Debug.getCallers(3));
5462            }
5463        }
5464    }
5465
5466    private BasePermission findPermissionTreeLP(String permName) {
5467        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5468            if (permName.startsWith(bp.name) &&
5469                    permName.length() > bp.name.length() &&
5470                    permName.charAt(bp.name.length()) == '.') {
5471                return bp;
5472            }
5473        }
5474        return null;
5475    }
5476
5477    private BasePermission checkPermissionTreeLP(String permName) {
5478        if (permName != null) {
5479            BasePermission bp = findPermissionTreeLP(permName);
5480            if (bp != null) {
5481                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5482                    return bp;
5483                }
5484                throw new SecurityException("Calling uid "
5485                        + Binder.getCallingUid()
5486                        + " is not allowed to add to permission tree "
5487                        + bp.name + " owned by uid " + bp.uid);
5488            }
5489        }
5490        throw new SecurityException("No permission tree found for " + permName);
5491    }
5492
5493    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5494        if (s1 == null) {
5495            return s2 == null;
5496        }
5497        if (s2 == null) {
5498            return false;
5499        }
5500        if (s1.getClass() != s2.getClass()) {
5501            return false;
5502        }
5503        return s1.equals(s2);
5504    }
5505
5506    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5507        if (pi1.icon != pi2.icon) return false;
5508        if (pi1.logo != pi2.logo) return false;
5509        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5510        if (!compareStrings(pi1.name, pi2.name)) return false;
5511        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5512        // We'll take care of setting this one.
5513        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5514        // These are not currently stored in settings.
5515        //if (!compareStrings(pi1.group, pi2.group)) return false;
5516        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5517        //if (pi1.labelRes != pi2.labelRes) return false;
5518        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5519        return true;
5520    }
5521
5522    int permissionInfoFootprint(PermissionInfo info) {
5523        int size = info.name.length();
5524        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5525        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5526        return size;
5527    }
5528
5529    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5530        int size = 0;
5531        for (BasePermission perm : mSettings.mPermissions.values()) {
5532            if (perm.uid == tree.uid) {
5533                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5534            }
5535        }
5536        return size;
5537    }
5538
5539    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5540        // We calculate the max size of permissions defined by this uid and throw
5541        // if that plus the size of 'info' would exceed our stated maximum.
5542        if (tree.uid != Process.SYSTEM_UID) {
5543            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5544            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5545                throw new SecurityException("Permission tree size cap exceeded");
5546            }
5547        }
5548    }
5549
5550    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5551        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5552            throw new SecurityException("Instant apps can't add permissions");
5553        }
5554        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5555            throw new SecurityException("Label must be specified in permission");
5556        }
5557        BasePermission tree = checkPermissionTreeLP(info.name);
5558        BasePermission bp = mSettings.mPermissions.get(info.name);
5559        boolean added = bp == null;
5560        boolean changed = true;
5561        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5562        if (added) {
5563            enforcePermissionCapLocked(info, tree);
5564            bp = new BasePermission(info.name, tree.sourcePackage,
5565                    BasePermission.TYPE_DYNAMIC);
5566        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5567            throw new SecurityException(
5568                    "Not allowed to modify non-dynamic permission "
5569                    + info.name);
5570        } else {
5571            if (bp.protectionLevel == fixedLevel
5572                    && bp.perm.owner.equals(tree.perm.owner)
5573                    && bp.uid == tree.uid
5574                    && comparePermissionInfos(bp.perm.info, info)) {
5575                changed = false;
5576            }
5577        }
5578        bp.protectionLevel = fixedLevel;
5579        info = new PermissionInfo(info);
5580        info.protectionLevel = fixedLevel;
5581        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5582        bp.perm.info.packageName = tree.perm.info.packageName;
5583        bp.uid = tree.uid;
5584        if (added) {
5585            mSettings.mPermissions.put(info.name, bp);
5586        }
5587        if (changed) {
5588            if (!async) {
5589                mSettings.writeLPr();
5590            } else {
5591                scheduleWriteSettingsLocked();
5592            }
5593        }
5594        return added;
5595    }
5596
5597    @Override
5598    public boolean addPermission(PermissionInfo info) {
5599        synchronized (mPackages) {
5600            return addPermissionLocked(info, false);
5601        }
5602    }
5603
5604    @Override
5605    public boolean addPermissionAsync(PermissionInfo info) {
5606        synchronized (mPackages) {
5607            return addPermissionLocked(info, true);
5608        }
5609    }
5610
5611    @Override
5612    public void removePermission(String name) {
5613        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5614            throw new SecurityException("Instant applications don't have access to this method");
5615        }
5616        synchronized (mPackages) {
5617            checkPermissionTreeLP(name);
5618            BasePermission bp = mSettings.mPermissions.get(name);
5619            if (bp != null) {
5620                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5621                    throw new SecurityException(
5622                            "Not allowed to modify non-dynamic permission "
5623                            + name);
5624                }
5625                mSettings.mPermissions.remove(name);
5626                mSettings.writeLPr();
5627            }
5628        }
5629    }
5630
5631    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5632            PackageParser.Package pkg, BasePermission bp) {
5633        int index = pkg.requestedPermissions.indexOf(bp.name);
5634        if (index == -1) {
5635            throw new SecurityException("Package " + pkg.packageName
5636                    + " has not requested permission " + bp.name);
5637        }
5638        if (!bp.isRuntime() && !bp.isDevelopment()) {
5639            throw new SecurityException("Permission " + bp.name
5640                    + " is not a changeable permission type");
5641        }
5642    }
5643
5644    @Override
5645    public void grantRuntimePermission(String packageName, String name, final int userId) {
5646        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5647    }
5648
5649    private void grantRuntimePermission(String packageName, String name, final int userId,
5650            boolean overridePolicy) {
5651        if (!sUserManager.exists(userId)) {
5652            Log.e(TAG, "No such user:" + userId);
5653            return;
5654        }
5655        final int callingUid = Binder.getCallingUid();
5656
5657        mContext.enforceCallingOrSelfPermission(
5658                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5659                "grantRuntimePermission");
5660
5661        enforceCrossUserPermission(callingUid, userId,
5662                true /* requireFullPermission */, true /* checkShell */,
5663                "grantRuntimePermission");
5664
5665        final int uid;
5666        final PackageSetting ps;
5667
5668        synchronized (mPackages) {
5669            final PackageParser.Package pkg = mPackages.get(packageName);
5670            if (pkg == null) {
5671                throw new IllegalArgumentException("Unknown package: " + packageName);
5672            }
5673            final BasePermission bp = mSettings.mPermissions.get(name);
5674            if (bp == null) {
5675                throw new IllegalArgumentException("Unknown permission: " + name);
5676            }
5677            ps = (PackageSetting) pkg.mExtras;
5678            if (ps == null
5679                    || filterAppAccessLPr(ps, callingUid, userId)) {
5680                throw new IllegalArgumentException("Unknown package: " + packageName);
5681            }
5682
5683            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5684
5685            // If a permission review is required for legacy apps we represent
5686            // their permissions as always granted runtime ones since we need
5687            // to keep the review required permission flag per user while an
5688            // install permission's state is shared across all users.
5689            if (mPermissionReviewRequired
5690                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5691                    && bp.isRuntime()) {
5692                return;
5693            }
5694
5695            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5696
5697            final PermissionsState permissionsState = ps.getPermissionsState();
5698
5699            final int flags = permissionsState.getPermissionFlags(name, userId);
5700            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5701                throw new SecurityException("Cannot grant system fixed permission "
5702                        + name + " for package " + packageName);
5703            }
5704            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5705                throw new SecurityException("Cannot grant policy fixed permission "
5706                        + name + " for package " + packageName);
5707            }
5708
5709            if (bp.isDevelopment()) {
5710                // Development permissions must be handled specially, since they are not
5711                // normal runtime permissions.  For now they apply to all users.
5712                if (permissionsState.grantInstallPermission(bp) !=
5713                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5714                    scheduleWriteSettingsLocked();
5715                }
5716                return;
5717            }
5718
5719            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5720                throw new SecurityException("Cannot grant non-ephemeral permission"
5721                        + name + " for package " + packageName);
5722            }
5723
5724            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5725                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5726                return;
5727            }
5728
5729            final int result = permissionsState.grantRuntimePermission(bp, userId);
5730            switch (result) {
5731                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5732                    return;
5733                }
5734
5735                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5736                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5737                    mHandler.post(new Runnable() {
5738                        @Override
5739                        public void run() {
5740                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5741                        }
5742                    });
5743                }
5744                break;
5745            }
5746
5747            if (bp.isRuntime()) {
5748                logPermissionGranted(mContext, name, packageName);
5749            }
5750
5751            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5752
5753            // Not critical if that is lost - app has to request again.
5754            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5755        }
5756
5757        // Only need to do this if user is initialized. Otherwise it's a new user
5758        // and there are no processes running as the user yet and there's no need
5759        // to make an expensive call to remount processes for the changed permissions.
5760        if (READ_EXTERNAL_STORAGE.equals(name)
5761                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5762            final long token = Binder.clearCallingIdentity();
5763            try {
5764                if (sUserManager.isInitialized(userId)) {
5765                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5766                            StorageManagerInternal.class);
5767                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5768                }
5769            } finally {
5770                Binder.restoreCallingIdentity(token);
5771            }
5772        }
5773    }
5774
5775    @Override
5776    public void revokeRuntimePermission(String packageName, String name, int userId) {
5777        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5778    }
5779
5780    private void revokeRuntimePermission(String packageName, String name, int userId,
5781            boolean overridePolicy) {
5782        if (!sUserManager.exists(userId)) {
5783            Log.e(TAG, "No such user:" + userId);
5784            return;
5785        }
5786
5787        mContext.enforceCallingOrSelfPermission(
5788                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5789                "revokeRuntimePermission");
5790
5791        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5792                true /* requireFullPermission */, true /* checkShell */,
5793                "revokeRuntimePermission");
5794
5795        final int appId;
5796
5797        synchronized (mPackages) {
5798            final PackageParser.Package pkg = mPackages.get(packageName);
5799            if (pkg == null) {
5800                throw new IllegalArgumentException("Unknown package: " + packageName);
5801            }
5802            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5803            if (ps == null
5804                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5805                throw new IllegalArgumentException("Unknown package: " + packageName);
5806            }
5807            final BasePermission bp = mSettings.mPermissions.get(name);
5808            if (bp == null) {
5809                throw new IllegalArgumentException("Unknown permission: " + name);
5810            }
5811
5812            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5813
5814            // If a permission review is required for legacy apps we represent
5815            // their permissions as always granted runtime ones since we need
5816            // to keep the review required permission flag per user while an
5817            // install permission's state is shared across all users.
5818            if (mPermissionReviewRequired
5819                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5820                    && bp.isRuntime()) {
5821                return;
5822            }
5823
5824            final PermissionsState permissionsState = ps.getPermissionsState();
5825
5826            final int flags = permissionsState.getPermissionFlags(name, userId);
5827            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5828                throw new SecurityException("Cannot revoke system fixed permission "
5829                        + name + " for package " + packageName);
5830            }
5831            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5832                throw new SecurityException("Cannot revoke policy fixed permission "
5833                        + name + " for package " + packageName);
5834            }
5835
5836            if (bp.isDevelopment()) {
5837                // Development permissions must be handled specially, since they are not
5838                // normal runtime permissions.  For now they apply to all users.
5839                if (permissionsState.revokeInstallPermission(bp) !=
5840                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5841                    scheduleWriteSettingsLocked();
5842                }
5843                return;
5844            }
5845
5846            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5847                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5848                return;
5849            }
5850
5851            if (bp.isRuntime()) {
5852                logPermissionRevoked(mContext, name, packageName);
5853            }
5854
5855            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5856
5857            // Critical, after this call app should never have the permission.
5858            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5859
5860            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5861        }
5862
5863        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5864    }
5865
5866    /**
5867     * Get the first event id for the permission.
5868     *
5869     * <p>There are four events for each permission: <ul>
5870     *     <li>Request permission: first id + 0</li>
5871     *     <li>Grant permission: first id + 1</li>
5872     *     <li>Request for permission denied: first id + 2</li>
5873     *     <li>Revoke permission: first id + 3</li>
5874     * </ul></p>
5875     *
5876     * @param name name of the permission
5877     *
5878     * @return The first event id for the permission
5879     */
5880    private static int getBaseEventId(@NonNull String name) {
5881        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5882
5883        if (eventIdIndex == -1) {
5884            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5885                    || Build.IS_USER) {
5886                Log.i(TAG, "Unknown permission " + name);
5887
5888                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5889            } else {
5890                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5891                //
5892                // Also update
5893                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5894                // - metrics_constants.proto
5895                throw new IllegalStateException("Unknown permission " + name);
5896            }
5897        }
5898
5899        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5900    }
5901
5902    /**
5903     * Log that a permission was revoked.
5904     *
5905     * @param context Context of the caller
5906     * @param name name of the permission
5907     * @param packageName package permission if for
5908     */
5909    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5910            @NonNull String packageName) {
5911        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5912    }
5913
5914    /**
5915     * Log that a permission request was granted.
5916     *
5917     * @param context Context of the caller
5918     * @param name name of the permission
5919     * @param packageName package permission if for
5920     */
5921    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5922            @NonNull String packageName) {
5923        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5924    }
5925
5926    @Override
5927    public void resetRuntimePermissions() {
5928        mContext.enforceCallingOrSelfPermission(
5929                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5930                "revokeRuntimePermission");
5931
5932        int callingUid = Binder.getCallingUid();
5933        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5934            mContext.enforceCallingOrSelfPermission(
5935                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5936                    "resetRuntimePermissions");
5937        }
5938
5939        synchronized (mPackages) {
5940            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5941            for (int userId : UserManagerService.getInstance().getUserIds()) {
5942                final int packageCount = mPackages.size();
5943                for (int i = 0; i < packageCount; i++) {
5944                    PackageParser.Package pkg = mPackages.valueAt(i);
5945                    if (!(pkg.mExtras instanceof PackageSetting)) {
5946                        continue;
5947                    }
5948                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5949                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5950                }
5951            }
5952        }
5953    }
5954
5955    @Override
5956    public int getPermissionFlags(String name, String packageName, int userId) {
5957        if (!sUserManager.exists(userId)) {
5958            return 0;
5959        }
5960
5961        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5962
5963        final int callingUid = Binder.getCallingUid();
5964        enforceCrossUserPermission(callingUid, userId,
5965                true /* requireFullPermission */, false /* checkShell */,
5966                "getPermissionFlags");
5967
5968        synchronized (mPackages) {
5969            final PackageParser.Package pkg = mPackages.get(packageName);
5970            if (pkg == null) {
5971                return 0;
5972            }
5973            final BasePermission bp = mSettings.mPermissions.get(name);
5974            if (bp == null) {
5975                return 0;
5976            }
5977            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5978            if (ps == null
5979                    || filterAppAccessLPr(ps, callingUid, userId)) {
5980                return 0;
5981            }
5982            PermissionsState permissionsState = ps.getPermissionsState();
5983            return permissionsState.getPermissionFlags(name, userId);
5984        }
5985    }
5986
5987    @Override
5988    public void updatePermissionFlags(String name, String packageName, int flagMask,
5989            int flagValues, int userId) {
5990        if (!sUserManager.exists(userId)) {
5991            return;
5992        }
5993
5994        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5995
5996        final int callingUid = Binder.getCallingUid();
5997        enforceCrossUserPermission(callingUid, userId,
5998                true /* requireFullPermission */, true /* checkShell */,
5999                "updatePermissionFlags");
6000
6001        // Only the system can change these flags and nothing else.
6002        if (getCallingUid() != Process.SYSTEM_UID) {
6003            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6004            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6005            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
6006            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
6007            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
6008        }
6009
6010        synchronized (mPackages) {
6011            final PackageParser.Package pkg = mPackages.get(packageName);
6012            if (pkg == null) {
6013                throw new IllegalArgumentException("Unknown package: " + packageName);
6014            }
6015            final PackageSetting ps = (PackageSetting) pkg.mExtras;
6016            if (ps == null
6017                    || filterAppAccessLPr(ps, callingUid, userId)) {
6018                throw new IllegalArgumentException("Unknown package: " + packageName);
6019            }
6020
6021            final BasePermission bp = mSettings.mPermissions.get(name);
6022            if (bp == null) {
6023                throw new IllegalArgumentException("Unknown permission: " + name);
6024            }
6025
6026            PermissionsState permissionsState = ps.getPermissionsState();
6027
6028            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
6029
6030            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
6031                // Install and runtime permissions are stored in different places,
6032                // so figure out what permission changed and persist the change.
6033                if (permissionsState.getInstallPermissionState(name) != null) {
6034                    scheduleWriteSettingsLocked();
6035                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
6036                        || hadState) {
6037                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6038                }
6039            }
6040        }
6041    }
6042
6043    /**
6044     * Update the permission flags for all packages and runtime permissions of a user in order
6045     * to allow device or profile owner to remove POLICY_FIXED.
6046     */
6047    @Override
6048    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
6049        if (!sUserManager.exists(userId)) {
6050            return;
6051        }
6052
6053        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
6054
6055        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6056                true /* requireFullPermission */, true /* checkShell */,
6057                "updatePermissionFlagsForAllApps");
6058
6059        // Only the system can change system fixed flags.
6060        if (getCallingUid() != Process.SYSTEM_UID) {
6061            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6062            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6063        }
6064
6065        synchronized (mPackages) {
6066            boolean changed = false;
6067            final int packageCount = mPackages.size();
6068            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6069                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6070                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6071                if (ps == null) {
6072                    continue;
6073                }
6074                PermissionsState permissionsState = ps.getPermissionsState();
6075                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6076                        userId, flagMask, flagValues);
6077            }
6078            if (changed) {
6079                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6080            }
6081        }
6082    }
6083
6084    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6085        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6086                != PackageManager.PERMISSION_GRANTED
6087            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6088                != PackageManager.PERMISSION_GRANTED) {
6089            throw new SecurityException(message + " requires "
6090                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6091                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6092        }
6093    }
6094
6095    @Override
6096    public boolean shouldShowRequestPermissionRationale(String permissionName,
6097            String packageName, int userId) {
6098        if (UserHandle.getCallingUserId() != userId) {
6099            mContext.enforceCallingPermission(
6100                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6101                    "canShowRequestPermissionRationale for user " + userId);
6102        }
6103
6104        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6105        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6106            return false;
6107        }
6108
6109        if (checkPermission(permissionName, packageName, userId)
6110                == PackageManager.PERMISSION_GRANTED) {
6111            return false;
6112        }
6113
6114        final int flags;
6115
6116        final long identity = Binder.clearCallingIdentity();
6117        try {
6118            flags = getPermissionFlags(permissionName,
6119                    packageName, userId);
6120        } finally {
6121            Binder.restoreCallingIdentity(identity);
6122        }
6123
6124        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6125                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6126                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6127
6128        if ((flags & fixedFlags) != 0) {
6129            return false;
6130        }
6131
6132        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6133    }
6134
6135    @Override
6136    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6137        mContext.enforceCallingOrSelfPermission(
6138                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6139                "addOnPermissionsChangeListener");
6140
6141        synchronized (mPackages) {
6142            mOnPermissionChangeListeners.addListenerLocked(listener);
6143        }
6144    }
6145
6146    @Override
6147    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6148        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6149            throw new SecurityException("Instant applications don't have access to this method");
6150        }
6151        synchronized (mPackages) {
6152            mOnPermissionChangeListeners.removeListenerLocked(listener);
6153        }
6154    }
6155
6156    @Override
6157    public boolean isProtectedBroadcast(String actionName) {
6158        // allow instant applications
6159        synchronized (mProtectedBroadcasts) {
6160            if (mProtectedBroadcasts.contains(actionName)) {
6161                return true;
6162            } else if (actionName != null) {
6163                // TODO: remove these terrible hacks
6164                if (actionName.startsWith("android.net.netmon.lingerExpired")
6165                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6166                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6167                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6168                    return true;
6169                }
6170            }
6171        }
6172        return false;
6173    }
6174
6175    @Override
6176    public int checkSignatures(String pkg1, String pkg2) {
6177        synchronized (mPackages) {
6178            final PackageParser.Package p1 = mPackages.get(pkg1);
6179            final PackageParser.Package p2 = mPackages.get(pkg2);
6180            if (p1 == null || p1.mExtras == null
6181                    || p2 == null || p2.mExtras == null) {
6182                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6183            }
6184            final int callingUid = Binder.getCallingUid();
6185            final int callingUserId = UserHandle.getUserId(callingUid);
6186            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6187            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6188            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6189                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6190                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6191            }
6192            return compareSignatures(p1.mSignatures, p2.mSignatures);
6193        }
6194    }
6195
6196    @Override
6197    public int checkUidSignatures(int uid1, int uid2) {
6198        final int callingUid = Binder.getCallingUid();
6199        final int callingUserId = UserHandle.getUserId(callingUid);
6200        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6201        // Map to base uids.
6202        uid1 = UserHandle.getAppId(uid1);
6203        uid2 = UserHandle.getAppId(uid2);
6204        // reader
6205        synchronized (mPackages) {
6206            Signature[] s1;
6207            Signature[] s2;
6208            Object obj = mSettings.getUserIdLPr(uid1);
6209            if (obj != null) {
6210                if (obj instanceof SharedUserSetting) {
6211                    if (isCallerInstantApp) {
6212                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6213                    }
6214                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6215                } else if (obj instanceof PackageSetting) {
6216                    final PackageSetting ps = (PackageSetting) obj;
6217                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6218                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6219                    }
6220                    s1 = ps.signatures.mSignatures;
6221                } else {
6222                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6223                }
6224            } else {
6225                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6226            }
6227            obj = mSettings.getUserIdLPr(uid2);
6228            if (obj != null) {
6229                if (obj instanceof SharedUserSetting) {
6230                    if (isCallerInstantApp) {
6231                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6232                    }
6233                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6234                } else if (obj instanceof PackageSetting) {
6235                    final PackageSetting ps = (PackageSetting) obj;
6236                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6237                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6238                    }
6239                    s2 = ps.signatures.mSignatures;
6240                } else {
6241                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6242                }
6243            } else {
6244                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6245            }
6246            return compareSignatures(s1, s2);
6247        }
6248    }
6249
6250    /**
6251     * This method should typically only be used when granting or revoking
6252     * permissions, since the app may immediately restart after this call.
6253     * <p>
6254     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6255     * guard your work against the app being relaunched.
6256     */
6257    private void killUid(int appId, int userId, String reason) {
6258        final long identity = Binder.clearCallingIdentity();
6259        try {
6260            IActivityManager am = ActivityManager.getService();
6261            if (am != null) {
6262                try {
6263                    am.killUid(appId, userId, reason);
6264                } catch (RemoteException e) {
6265                    /* ignore - same process */
6266                }
6267            }
6268        } finally {
6269            Binder.restoreCallingIdentity(identity);
6270        }
6271    }
6272
6273    /**
6274     * Compares two sets of signatures. Returns:
6275     * <br />
6276     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6277     * <br />
6278     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6279     * <br />
6280     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6281     * <br />
6282     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6283     * <br />
6284     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6285     */
6286    static int compareSignatures(Signature[] s1, Signature[] s2) {
6287        if (s1 == null) {
6288            return s2 == null
6289                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6290                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6291        }
6292
6293        if (s2 == null) {
6294            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6295        }
6296
6297        if (s1.length != s2.length) {
6298            return PackageManager.SIGNATURE_NO_MATCH;
6299        }
6300
6301        // Since both signature sets are of size 1, we can compare without HashSets.
6302        if (s1.length == 1) {
6303            return s1[0].equals(s2[0]) ?
6304                    PackageManager.SIGNATURE_MATCH :
6305                    PackageManager.SIGNATURE_NO_MATCH;
6306        }
6307
6308        ArraySet<Signature> set1 = new ArraySet<Signature>();
6309        for (Signature sig : s1) {
6310            set1.add(sig);
6311        }
6312        ArraySet<Signature> set2 = new ArraySet<Signature>();
6313        for (Signature sig : s2) {
6314            set2.add(sig);
6315        }
6316        // Make sure s2 contains all signatures in s1.
6317        if (set1.equals(set2)) {
6318            return PackageManager.SIGNATURE_MATCH;
6319        }
6320        return PackageManager.SIGNATURE_NO_MATCH;
6321    }
6322
6323    /**
6324     * If the database version for this type of package (internal storage or
6325     * external storage) is less than the version where package signatures
6326     * were updated, return true.
6327     */
6328    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6329        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6330        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6331    }
6332
6333    /**
6334     * Used for backward compatibility to make sure any packages with
6335     * certificate chains get upgraded to the new style. {@code existingSigs}
6336     * will be in the old format (since they were stored on disk from before the
6337     * system upgrade) and {@code scannedSigs} will be in the newer format.
6338     */
6339    private int compareSignaturesCompat(PackageSignatures existingSigs,
6340            PackageParser.Package scannedPkg) {
6341        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6342            return PackageManager.SIGNATURE_NO_MATCH;
6343        }
6344
6345        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6346        for (Signature sig : existingSigs.mSignatures) {
6347            existingSet.add(sig);
6348        }
6349        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6350        for (Signature sig : scannedPkg.mSignatures) {
6351            try {
6352                Signature[] chainSignatures = sig.getChainSignatures();
6353                for (Signature chainSig : chainSignatures) {
6354                    scannedCompatSet.add(chainSig);
6355                }
6356            } catch (CertificateEncodingException e) {
6357                scannedCompatSet.add(sig);
6358            }
6359        }
6360        /*
6361         * Make sure the expanded scanned set contains all signatures in the
6362         * existing one.
6363         */
6364        if (scannedCompatSet.equals(existingSet)) {
6365            // Migrate the old signatures to the new scheme.
6366            existingSigs.assignSignatures(scannedPkg.mSignatures);
6367            // The new KeySets will be re-added later in the scanning process.
6368            synchronized (mPackages) {
6369                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6370            }
6371            return PackageManager.SIGNATURE_MATCH;
6372        }
6373        return PackageManager.SIGNATURE_NO_MATCH;
6374    }
6375
6376    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6377        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6378        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6379    }
6380
6381    private int compareSignaturesRecover(PackageSignatures existingSigs,
6382            PackageParser.Package scannedPkg) {
6383        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6384            return PackageManager.SIGNATURE_NO_MATCH;
6385        }
6386
6387        String msg = null;
6388        try {
6389            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6390                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6391                        + scannedPkg.packageName);
6392                return PackageManager.SIGNATURE_MATCH;
6393            }
6394        } catch (CertificateException e) {
6395            msg = e.getMessage();
6396        }
6397
6398        logCriticalInfo(Log.INFO,
6399                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6400        return PackageManager.SIGNATURE_NO_MATCH;
6401    }
6402
6403    @Override
6404    public List<String> getAllPackages() {
6405        final int callingUid = Binder.getCallingUid();
6406        final int callingUserId = UserHandle.getUserId(callingUid);
6407        synchronized (mPackages) {
6408            if (canViewInstantApps(callingUid, callingUserId)) {
6409                return new ArrayList<String>(mPackages.keySet());
6410            }
6411            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6412            final List<String> result = new ArrayList<>();
6413            if (instantAppPkgName != null) {
6414                // caller is an instant application; filter unexposed applications
6415                for (PackageParser.Package pkg : mPackages.values()) {
6416                    if (!pkg.visibleToInstantApps) {
6417                        continue;
6418                    }
6419                    result.add(pkg.packageName);
6420                }
6421            } else {
6422                // caller is a normal application; filter instant applications
6423                for (PackageParser.Package pkg : mPackages.values()) {
6424                    final PackageSetting ps =
6425                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6426                    if (ps != null
6427                            && ps.getInstantApp(callingUserId)
6428                            && !mInstantAppRegistry.isInstantAccessGranted(
6429                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6430                        continue;
6431                    }
6432                    result.add(pkg.packageName);
6433                }
6434            }
6435            return result;
6436        }
6437    }
6438
6439    @Override
6440    public String[] getPackagesForUid(int uid) {
6441        final int callingUid = Binder.getCallingUid();
6442        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6443        final int userId = UserHandle.getUserId(uid);
6444        uid = UserHandle.getAppId(uid);
6445        // reader
6446        synchronized (mPackages) {
6447            Object obj = mSettings.getUserIdLPr(uid);
6448            if (obj instanceof SharedUserSetting) {
6449                if (isCallerInstantApp) {
6450                    return null;
6451                }
6452                final SharedUserSetting sus = (SharedUserSetting) obj;
6453                final int N = sus.packages.size();
6454                String[] res = new String[N];
6455                final Iterator<PackageSetting> it = sus.packages.iterator();
6456                int i = 0;
6457                while (it.hasNext()) {
6458                    PackageSetting ps = it.next();
6459                    if (ps.getInstalled(userId)) {
6460                        res[i++] = ps.name;
6461                    } else {
6462                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6463                    }
6464                }
6465                return res;
6466            } else if (obj instanceof PackageSetting) {
6467                final PackageSetting ps = (PackageSetting) obj;
6468                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6469                    return new String[]{ps.name};
6470                }
6471            }
6472        }
6473        return null;
6474    }
6475
6476    @Override
6477    public String getNameForUid(int uid) {
6478        final int callingUid = Binder.getCallingUid();
6479        if (getInstantAppPackageName(callingUid) != null) {
6480            return null;
6481        }
6482        synchronized (mPackages) {
6483            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6484            if (obj instanceof SharedUserSetting) {
6485                final SharedUserSetting sus = (SharedUserSetting) obj;
6486                return sus.name + ":" + sus.userId;
6487            } else if (obj instanceof PackageSetting) {
6488                final PackageSetting ps = (PackageSetting) obj;
6489                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6490                    return null;
6491                }
6492                return ps.name;
6493            }
6494            return null;
6495        }
6496    }
6497
6498    @Override
6499    public String[] getNamesForUids(int[] uids) {
6500        if (uids == null || uids.length == 0) {
6501            return null;
6502        }
6503        final int callingUid = Binder.getCallingUid();
6504        if (getInstantAppPackageName(callingUid) != null) {
6505            return null;
6506        }
6507        final String[] names = new String[uids.length];
6508        synchronized (mPackages) {
6509            for (int i = uids.length - 1; i >= 0; i--) {
6510                final int uid = uids[i];
6511                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6512                if (obj instanceof SharedUserSetting) {
6513                    final SharedUserSetting sus = (SharedUserSetting) obj;
6514                    names[i] = "shared:" + sus.name;
6515                } else if (obj instanceof PackageSetting) {
6516                    final PackageSetting ps = (PackageSetting) obj;
6517                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6518                        names[i] = null;
6519                    } else {
6520                        names[i] = ps.name;
6521                    }
6522                } else {
6523                    names[i] = null;
6524                }
6525            }
6526        }
6527        return names;
6528    }
6529
6530    @Override
6531    public int getUidForSharedUser(String sharedUserName) {
6532        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6533            return -1;
6534        }
6535        if (sharedUserName == null) {
6536            return -1;
6537        }
6538        // reader
6539        synchronized (mPackages) {
6540            SharedUserSetting suid;
6541            try {
6542                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6543                if (suid != null) {
6544                    return suid.userId;
6545                }
6546            } catch (PackageManagerException ignore) {
6547                // can't happen, but, still need to catch it
6548            }
6549            return -1;
6550        }
6551    }
6552
6553    @Override
6554    public int getFlagsForUid(int uid) {
6555        final int callingUid = Binder.getCallingUid();
6556        if (getInstantAppPackageName(callingUid) != null) {
6557            return 0;
6558        }
6559        synchronized (mPackages) {
6560            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6561            if (obj instanceof SharedUserSetting) {
6562                final SharedUserSetting sus = (SharedUserSetting) obj;
6563                return sus.pkgFlags;
6564            } else if (obj instanceof PackageSetting) {
6565                final PackageSetting ps = (PackageSetting) obj;
6566                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6567                    return 0;
6568                }
6569                return ps.pkgFlags;
6570            }
6571        }
6572        return 0;
6573    }
6574
6575    @Override
6576    public int getPrivateFlagsForUid(int uid) {
6577        final int callingUid = Binder.getCallingUid();
6578        if (getInstantAppPackageName(callingUid) != null) {
6579            return 0;
6580        }
6581        synchronized (mPackages) {
6582            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6583            if (obj instanceof SharedUserSetting) {
6584                final SharedUserSetting sus = (SharedUserSetting) obj;
6585                return sus.pkgPrivateFlags;
6586            } else if (obj instanceof PackageSetting) {
6587                final PackageSetting ps = (PackageSetting) obj;
6588                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6589                    return 0;
6590                }
6591                return ps.pkgPrivateFlags;
6592            }
6593        }
6594        return 0;
6595    }
6596
6597    @Override
6598    public boolean isUidPrivileged(int uid) {
6599        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6600            return false;
6601        }
6602        uid = UserHandle.getAppId(uid);
6603        // reader
6604        synchronized (mPackages) {
6605            Object obj = mSettings.getUserIdLPr(uid);
6606            if (obj instanceof SharedUserSetting) {
6607                final SharedUserSetting sus = (SharedUserSetting) obj;
6608                final Iterator<PackageSetting> it = sus.packages.iterator();
6609                while (it.hasNext()) {
6610                    if (it.next().isPrivileged()) {
6611                        return true;
6612                    }
6613                }
6614            } else if (obj instanceof PackageSetting) {
6615                final PackageSetting ps = (PackageSetting) obj;
6616                return ps.isPrivileged();
6617            }
6618        }
6619        return false;
6620    }
6621
6622    @Override
6623    public String[] getAppOpPermissionPackages(String permissionName) {
6624        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6625            return null;
6626        }
6627        synchronized (mPackages) {
6628            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6629            if (pkgs == null) {
6630                return null;
6631            }
6632            return pkgs.toArray(new String[pkgs.size()]);
6633        }
6634    }
6635
6636    @Override
6637    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6638            int flags, int userId) {
6639        return resolveIntentInternal(
6640                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6641    }
6642
6643    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6644            int flags, int userId, boolean resolveForStart) {
6645        try {
6646            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6647
6648            if (!sUserManager.exists(userId)) return null;
6649            final int callingUid = Binder.getCallingUid();
6650            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6651            enforceCrossUserPermission(callingUid, userId,
6652                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6653
6654            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6655            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6656                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6657            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6658
6659            final ResolveInfo bestChoice =
6660                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6661            return bestChoice;
6662        } finally {
6663            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6664        }
6665    }
6666
6667    @Override
6668    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6669        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6670            throw new SecurityException(
6671                    "findPersistentPreferredActivity can only be run by the system");
6672        }
6673        if (!sUserManager.exists(userId)) {
6674            return null;
6675        }
6676        final int callingUid = Binder.getCallingUid();
6677        intent = updateIntentForResolve(intent);
6678        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6679        final int flags = updateFlagsForResolve(
6680                0, userId, intent, callingUid, false /*includeInstantApps*/);
6681        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6682                userId);
6683        synchronized (mPackages) {
6684            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6685                    userId);
6686        }
6687    }
6688
6689    @Override
6690    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6691            IntentFilter filter, int match, ComponentName activity) {
6692        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6693            return;
6694        }
6695        final int userId = UserHandle.getCallingUserId();
6696        if (DEBUG_PREFERRED) {
6697            Log.v(TAG, "setLastChosenActivity intent=" + intent
6698                + " resolvedType=" + resolvedType
6699                + " flags=" + flags
6700                + " filter=" + filter
6701                + " match=" + match
6702                + " activity=" + activity);
6703            filter.dump(new PrintStreamPrinter(System.out), "    ");
6704        }
6705        intent.setComponent(null);
6706        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6707                userId);
6708        // Find any earlier preferred or last chosen entries and nuke them
6709        findPreferredActivity(intent, resolvedType,
6710                flags, query, 0, false, true, false, userId);
6711        // Add the new activity as the last chosen for this filter
6712        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6713                "Setting last chosen");
6714    }
6715
6716    @Override
6717    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6718        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6719            return null;
6720        }
6721        final int userId = UserHandle.getCallingUserId();
6722        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6723        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6724                userId);
6725        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6726                false, false, false, userId);
6727    }
6728
6729    /**
6730     * Returns whether or not instant apps have been disabled remotely.
6731     */
6732    private boolean isEphemeralDisabled() {
6733        return mEphemeralAppsDisabled;
6734    }
6735
6736    private boolean isInstantAppAllowed(
6737            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6738            boolean skipPackageCheck) {
6739        if (mInstantAppResolverConnection == null) {
6740            return false;
6741        }
6742        if (mInstantAppInstallerActivity == null) {
6743            return false;
6744        }
6745        if (intent.getComponent() != null) {
6746            return false;
6747        }
6748        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6749            return false;
6750        }
6751        if (!skipPackageCheck && intent.getPackage() != null) {
6752            return false;
6753        }
6754        final boolean isWebUri = hasWebURI(intent);
6755        if (!isWebUri || intent.getData().getHost() == null) {
6756            return false;
6757        }
6758        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6759        // Or if there's already an ephemeral app installed that handles the action
6760        synchronized (mPackages) {
6761            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6762            for (int n = 0; n < count; n++) {
6763                final ResolveInfo info = resolvedActivities.get(n);
6764                final String packageName = info.activityInfo.packageName;
6765                final PackageSetting ps = mSettings.mPackages.get(packageName);
6766                if (ps != null) {
6767                    // only check domain verification status if the app is not a browser
6768                    if (!info.handleAllWebDataURI) {
6769                        // Try to get the status from User settings first
6770                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6771                        final int status = (int) (packedStatus >> 32);
6772                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6773                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6774                            if (DEBUG_EPHEMERAL) {
6775                                Slog.v(TAG, "DENY instant app;"
6776                                    + " pkg: " + packageName + ", status: " + status);
6777                            }
6778                            return false;
6779                        }
6780                    }
6781                    if (ps.getInstantApp(userId)) {
6782                        if (DEBUG_EPHEMERAL) {
6783                            Slog.v(TAG, "DENY instant app installed;"
6784                                    + " pkg: " + packageName);
6785                        }
6786                        return false;
6787                    }
6788                }
6789            }
6790        }
6791        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6792        return true;
6793    }
6794
6795    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6796            Intent origIntent, String resolvedType, String callingPackage,
6797            Bundle verificationBundle, int userId) {
6798        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6799                new InstantAppRequest(responseObj, origIntent, resolvedType,
6800                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6801        mHandler.sendMessage(msg);
6802    }
6803
6804    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6805            int flags, List<ResolveInfo> query, int userId) {
6806        if (query != null) {
6807            final int N = query.size();
6808            if (N == 1) {
6809                return query.get(0);
6810            } else if (N > 1) {
6811                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6812                // If there is more than one activity with the same priority,
6813                // then let the user decide between them.
6814                ResolveInfo r0 = query.get(0);
6815                ResolveInfo r1 = query.get(1);
6816                if (DEBUG_INTENT_MATCHING || debug) {
6817                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6818                            + r1.activityInfo.name + "=" + r1.priority);
6819                }
6820                // If the first activity has a higher priority, or a different
6821                // default, then it is always desirable to pick it.
6822                if (r0.priority != r1.priority
6823                        || r0.preferredOrder != r1.preferredOrder
6824                        || r0.isDefault != r1.isDefault) {
6825                    return query.get(0);
6826                }
6827                // If we have saved a preference for a preferred activity for
6828                // this Intent, use that.
6829                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6830                        flags, query, r0.priority, true, false, debug, userId);
6831                if (ri != null) {
6832                    return ri;
6833                }
6834                // If we have an ephemeral app, use it
6835                for (int i = 0; i < N; i++) {
6836                    ri = query.get(i);
6837                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6838                        final String packageName = ri.activityInfo.packageName;
6839                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6840                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6841                        final int status = (int)(packedStatus >> 32);
6842                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6843                            return ri;
6844                        }
6845                    }
6846                }
6847                ri = new ResolveInfo(mResolveInfo);
6848                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6849                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6850                // If all of the options come from the same package, show the application's
6851                // label and icon instead of the generic resolver's.
6852                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6853                // and then throw away the ResolveInfo itself, meaning that the caller loses
6854                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6855                // a fallback for this case; we only set the target package's resources on
6856                // the ResolveInfo, not the ActivityInfo.
6857                final String intentPackage = intent.getPackage();
6858                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6859                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6860                    ri.resolvePackageName = intentPackage;
6861                    if (userNeedsBadging(userId)) {
6862                        ri.noResourceId = true;
6863                    } else {
6864                        ri.icon = appi.icon;
6865                    }
6866                    ri.iconResourceId = appi.icon;
6867                    ri.labelRes = appi.labelRes;
6868                }
6869                ri.activityInfo.applicationInfo = new ApplicationInfo(
6870                        ri.activityInfo.applicationInfo);
6871                if (userId != 0) {
6872                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6873                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6874                }
6875                // Make sure that the resolver is displayable in car mode
6876                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6877                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6878                return ri;
6879            }
6880        }
6881        return null;
6882    }
6883
6884    /**
6885     * Return true if the given list is not empty and all of its contents have
6886     * an activityInfo with the given package name.
6887     */
6888    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6889        if (ArrayUtils.isEmpty(list)) {
6890            return false;
6891        }
6892        for (int i = 0, N = list.size(); i < N; i++) {
6893            final ResolveInfo ri = list.get(i);
6894            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6895            if (ai == null || !packageName.equals(ai.packageName)) {
6896                return false;
6897            }
6898        }
6899        return true;
6900    }
6901
6902    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6903            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6904        final int N = query.size();
6905        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6906                .get(userId);
6907        // Get the list of persistent preferred activities that handle the intent
6908        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6909        List<PersistentPreferredActivity> pprefs = ppir != null
6910                ? ppir.queryIntent(intent, resolvedType,
6911                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6912                        userId)
6913                : null;
6914        if (pprefs != null && pprefs.size() > 0) {
6915            final int M = pprefs.size();
6916            for (int i=0; i<M; i++) {
6917                final PersistentPreferredActivity ppa = pprefs.get(i);
6918                if (DEBUG_PREFERRED || debug) {
6919                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6920                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6921                            + "\n  component=" + ppa.mComponent);
6922                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6923                }
6924                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6925                        flags | MATCH_DISABLED_COMPONENTS, userId);
6926                if (DEBUG_PREFERRED || debug) {
6927                    Slog.v(TAG, "Found persistent preferred activity:");
6928                    if (ai != null) {
6929                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6930                    } else {
6931                        Slog.v(TAG, "  null");
6932                    }
6933                }
6934                if (ai == null) {
6935                    // This previously registered persistent preferred activity
6936                    // component is no longer known. Ignore it and do NOT remove it.
6937                    continue;
6938                }
6939                for (int j=0; j<N; j++) {
6940                    final ResolveInfo ri = query.get(j);
6941                    if (!ri.activityInfo.applicationInfo.packageName
6942                            .equals(ai.applicationInfo.packageName)) {
6943                        continue;
6944                    }
6945                    if (!ri.activityInfo.name.equals(ai.name)) {
6946                        continue;
6947                    }
6948                    //  Found a persistent preference that can handle the intent.
6949                    if (DEBUG_PREFERRED || debug) {
6950                        Slog.v(TAG, "Returning persistent preferred activity: " +
6951                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6952                    }
6953                    return ri;
6954                }
6955            }
6956        }
6957        return null;
6958    }
6959
6960    // TODO: handle preferred activities missing while user has amnesia
6961    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6962            List<ResolveInfo> query, int priority, boolean always,
6963            boolean removeMatches, boolean debug, int userId) {
6964        if (!sUserManager.exists(userId)) return null;
6965        final int callingUid = Binder.getCallingUid();
6966        flags = updateFlagsForResolve(
6967                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6968        intent = updateIntentForResolve(intent);
6969        // writer
6970        synchronized (mPackages) {
6971            // Try to find a matching persistent preferred activity.
6972            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6973                    debug, userId);
6974
6975            // If a persistent preferred activity matched, use it.
6976            if (pri != null) {
6977                return pri;
6978            }
6979
6980            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6981            // Get the list of preferred activities that handle the intent
6982            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6983            List<PreferredActivity> prefs = pir != null
6984                    ? pir.queryIntent(intent, resolvedType,
6985                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6986                            userId)
6987                    : null;
6988            if (prefs != null && prefs.size() > 0) {
6989                boolean changed = false;
6990                try {
6991                    // First figure out how good the original match set is.
6992                    // We will only allow preferred activities that came
6993                    // from the same match quality.
6994                    int match = 0;
6995
6996                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6997
6998                    final int N = query.size();
6999                    for (int j=0; j<N; j++) {
7000                        final ResolveInfo ri = query.get(j);
7001                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
7002                                + ": 0x" + Integer.toHexString(match));
7003                        if (ri.match > match) {
7004                            match = ri.match;
7005                        }
7006                    }
7007
7008                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
7009                            + Integer.toHexString(match));
7010
7011                    match &= IntentFilter.MATCH_CATEGORY_MASK;
7012                    final int M = prefs.size();
7013                    for (int i=0; i<M; i++) {
7014                        final PreferredActivity pa = prefs.get(i);
7015                        if (DEBUG_PREFERRED || debug) {
7016                            Slog.v(TAG, "Checking PreferredActivity ds="
7017                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
7018                                    + "\n  component=" + pa.mPref.mComponent);
7019                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7020                        }
7021                        if (pa.mPref.mMatch != match) {
7022                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
7023                                    + Integer.toHexString(pa.mPref.mMatch));
7024                            continue;
7025                        }
7026                        // If it's not an "always" type preferred activity and that's what we're
7027                        // looking for, skip it.
7028                        if (always && !pa.mPref.mAlways) {
7029                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
7030                            continue;
7031                        }
7032                        final ActivityInfo ai = getActivityInfo(
7033                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
7034                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
7035                                userId);
7036                        if (DEBUG_PREFERRED || debug) {
7037                            Slog.v(TAG, "Found preferred activity:");
7038                            if (ai != null) {
7039                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7040                            } else {
7041                                Slog.v(TAG, "  null");
7042                            }
7043                        }
7044                        if (ai == null) {
7045                            // This previously registered preferred activity
7046                            // component is no longer known.  Most likely an update
7047                            // to the app was installed and in the new version this
7048                            // component no longer exists.  Clean it up by removing
7049                            // it from the preferred activities list, and skip it.
7050                            Slog.w(TAG, "Removing dangling preferred activity: "
7051                                    + pa.mPref.mComponent);
7052                            pir.removeFilter(pa);
7053                            changed = true;
7054                            continue;
7055                        }
7056                        for (int j=0; j<N; j++) {
7057                            final ResolveInfo ri = query.get(j);
7058                            if (!ri.activityInfo.applicationInfo.packageName
7059                                    .equals(ai.applicationInfo.packageName)) {
7060                                continue;
7061                            }
7062                            if (!ri.activityInfo.name.equals(ai.name)) {
7063                                continue;
7064                            }
7065
7066                            if (removeMatches) {
7067                                pir.removeFilter(pa);
7068                                changed = true;
7069                                if (DEBUG_PREFERRED) {
7070                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7071                                }
7072                                break;
7073                            }
7074
7075                            // Okay we found a previously set preferred or last chosen app.
7076                            // If the result set is different from when this
7077                            // was created, and is not a subset of the preferred set, we need to
7078                            // clear it and re-ask the user their preference, if we're looking for
7079                            // an "always" type entry.
7080                            if (always && !pa.mPref.sameSet(query)) {
7081                                if (pa.mPref.isSuperset(query)) {
7082                                    // some components of the set are no longer present in
7083                                    // the query, but the preferred activity can still be reused
7084                                    if (DEBUG_PREFERRED) {
7085                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
7086                                                + " still valid as only non-preferred components"
7087                                                + " were removed for " + intent + " type "
7088                                                + resolvedType);
7089                                    }
7090                                    // remove obsolete components and re-add the up-to-date filter
7091                                    PreferredActivity freshPa = new PreferredActivity(pa,
7092                                            pa.mPref.mMatch,
7093                                            pa.mPref.discardObsoleteComponents(query),
7094                                            pa.mPref.mComponent,
7095                                            pa.mPref.mAlways);
7096                                    pir.removeFilter(pa);
7097                                    pir.addFilter(freshPa);
7098                                    changed = true;
7099                                } else {
7100                                    Slog.i(TAG,
7101                                            "Result set changed, dropping preferred activity for "
7102                                                    + intent + " type " + resolvedType);
7103                                    if (DEBUG_PREFERRED) {
7104                                        Slog.v(TAG, "Removing preferred activity since set changed "
7105                                                + pa.mPref.mComponent);
7106                                    }
7107                                    pir.removeFilter(pa);
7108                                    // Re-add the filter as a "last chosen" entry (!always)
7109                                    PreferredActivity lastChosen = new PreferredActivity(
7110                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7111                                    pir.addFilter(lastChosen);
7112                                    changed = true;
7113                                    return null;
7114                                }
7115                            }
7116
7117                            // Yay! Either the set matched or we're looking for the last chosen
7118                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7119                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7120                            return ri;
7121                        }
7122                    }
7123                } finally {
7124                    if (changed) {
7125                        if (DEBUG_PREFERRED) {
7126                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7127                        }
7128                        scheduleWritePackageRestrictionsLocked(userId);
7129                    }
7130                }
7131            }
7132        }
7133        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7134        return null;
7135    }
7136
7137    /*
7138     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7139     */
7140    @Override
7141    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7142            int targetUserId) {
7143        mContext.enforceCallingOrSelfPermission(
7144                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7145        List<CrossProfileIntentFilter> matches =
7146                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7147        if (matches != null) {
7148            int size = matches.size();
7149            for (int i = 0; i < size; i++) {
7150                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7151            }
7152        }
7153        if (hasWebURI(intent)) {
7154            // cross-profile app linking works only towards the parent.
7155            final int callingUid = Binder.getCallingUid();
7156            final UserInfo parent = getProfileParent(sourceUserId);
7157            synchronized(mPackages) {
7158                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7159                        false /*includeInstantApps*/);
7160                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7161                        intent, resolvedType, flags, sourceUserId, parent.id);
7162                return xpDomainInfo != null;
7163            }
7164        }
7165        return false;
7166    }
7167
7168    private UserInfo getProfileParent(int userId) {
7169        final long identity = Binder.clearCallingIdentity();
7170        try {
7171            return sUserManager.getProfileParent(userId);
7172        } finally {
7173            Binder.restoreCallingIdentity(identity);
7174        }
7175    }
7176
7177    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7178            String resolvedType, int userId) {
7179        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7180        if (resolver != null) {
7181            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7182        }
7183        return null;
7184    }
7185
7186    @Override
7187    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7188            String resolvedType, int flags, int userId) {
7189        try {
7190            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7191
7192            return new ParceledListSlice<>(
7193                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7194        } finally {
7195            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7196        }
7197    }
7198
7199    /**
7200     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7201     * instant, returns {@code null}.
7202     */
7203    private String getInstantAppPackageName(int callingUid) {
7204        synchronized (mPackages) {
7205            // If the caller is an isolated app use the owner's uid for the lookup.
7206            if (Process.isIsolated(callingUid)) {
7207                callingUid = mIsolatedOwners.get(callingUid);
7208            }
7209            final int appId = UserHandle.getAppId(callingUid);
7210            final Object obj = mSettings.getUserIdLPr(appId);
7211            if (obj instanceof PackageSetting) {
7212                final PackageSetting ps = (PackageSetting) obj;
7213                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7214                return isInstantApp ? ps.pkg.packageName : null;
7215            }
7216        }
7217        return null;
7218    }
7219
7220    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7221            String resolvedType, int flags, int userId) {
7222        return queryIntentActivitiesInternal(
7223                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7224                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7225    }
7226
7227    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7228            String resolvedType, int flags, int filterCallingUid, int userId,
7229            boolean resolveForStart, boolean allowDynamicSplits) {
7230        if (!sUserManager.exists(userId)) return Collections.emptyList();
7231        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7232        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7233                false /* requireFullPermission */, false /* checkShell */,
7234                "query intent activities");
7235        final String pkgName = intent.getPackage();
7236        ComponentName comp = intent.getComponent();
7237        if (comp == null) {
7238            if (intent.getSelector() != null) {
7239                intent = intent.getSelector();
7240                comp = intent.getComponent();
7241            }
7242        }
7243
7244        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7245                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7246        if (comp != null) {
7247            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7248            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7249            if (ai != null) {
7250                // When specifying an explicit component, we prevent the activity from being
7251                // used when either 1) the calling package is normal and the activity is within
7252                // an ephemeral application or 2) the calling package is ephemeral and the
7253                // activity is not visible to ephemeral applications.
7254                final boolean matchInstantApp =
7255                        (flags & PackageManager.MATCH_INSTANT) != 0;
7256                final boolean matchVisibleToInstantAppOnly =
7257                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7258                final boolean matchExplicitlyVisibleOnly =
7259                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7260                final boolean isCallerInstantApp =
7261                        instantAppPkgName != null;
7262                final boolean isTargetSameInstantApp =
7263                        comp.getPackageName().equals(instantAppPkgName);
7264                final boolean isTargetInstantApp =
7265                        (ai.applicationInfo.privateFlags
7266                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7267                final boolean isTargetVisibleToInstantApp =
7268                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7269                final boolean isTargetExplicitlyVisibleToInstantApp =
7270                        isTargetVisibleToInstantApp
7271                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7272                final boolean isTargetHiddenFromInstantApp =
7273                        !isTargetVisibleToInstantApp
7274                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7275                final boolean blockResolution =
7276                        !isTargetSameInstantApp
7277                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7278                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7279                                        && isTargetHiddenFromInstantApp));
7280                if (!blockResolution) {
7281                    final ResolveInfo ri = new ResolveInfo();
7282                    ri.activityInfo = ai;
7283                    list.add(ri);
7284                }
7285            }
7286            return applyPostResolutionFilter(
7287                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7288        }
7289
7290        // reader
7291        boolean sortResult = false;
7292        boolean addEphemeral = false;
7293        List<ResolveInfo> result;
7294        final boolean ephemeralDisabled = isEphemeralDisabled();
7295        synchronized (mPackages) {
7296            if (pkgName == null) {
7297                List<CrossProfileIntentFilter> matchingFilters =
7298                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7299                // Check for results that need to skip the current profile.
7300                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7301                        resolvedType, flags, userId);
7302                if (xpResolveInfo != null) {
7303                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7304                    xpResult.add(xpResolveInfo);
7305                    return applyPostResolutionFilter(
7306                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7307                            allowDynamicSplits, filterCallingUid, userId);
7308                }
7309
7310                // Check for results in the current profile.
7311                result = filterIfNotSystemUser(mActivities.queryIntent(
7312                        intent, resolvedType, flags, userId), userId);
7313                addEphemeral = !ephemeralDisabled
7314                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7315                // Check for cross profile results.
7316                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7317                xpResolveInfo = queryCrossProfileIntents(
7318                        matchingFilters, intent, resolvedType, flags, userId,
7319                        hasNonNegativePriorityResult);
7320                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7321                    boolean isVisibleToUser = filterIfNotSystemUser(
7322                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7323                    if (isVisibleToUser) {
7324                        result.add(xpResolveInfo);
7325                        sortResult = true;
7326                    }
7327                }
7328                if (hasWebURI(intent)) {
7329                    CrossProfileDomainInfo xpDomainInfo = null;
7330                    final UserInfo parent = getProfileParent(userId);
7331                    if (parent != null) {
7332                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7333                                flags, userId, parent.id);
7334                    }
7335                    if (xpDomainInfo != null) {
7336                        if (xpResolveInfo != null) {
7337                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7338                            // in the result.
7339                            result.remove(xpResolveInfo);
7340                        }
7341                        if (result.size() == 0 && !addEphemeral) {
7342                            // No result in current profile, but found candidate in parent user.
7343                            // And we are not going to add emphemeral app, so we can return the
7344                            // result straight away.
7345                            result.add(xpDomainInfo.resolveInfo);
7346                            return applyPostResolutionFilter(result, instantAppPkgName,
7347                                    allowDynamicSplits, filterCallingUid, userId);
7348                        }
7349                    } else if (result.size() <= 1 && !addEphemeral) {
7350                        // No result in parent user and <= 1 result in current profile, and we
7351                        // are not going to add emphemeral app, so we can return the result without
7352                        // further processing.
7353                        return applyPostResolutionFilter(result, instantAppPkgName,
7354                                allowDynamicSplits, filterCallingUid, userId);
7355                    }
7356                    // We have more than one candidate (combining results from current and parent
7357                    // profile), so we need filtering and sorting.
7358                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7359                            intent, flags, result, xpDomainInfo, userId);
7360                    sortResult = true;
7361                }
7362            } else {
7363                final PackageParser.Package pkg = mPackages.get(pkgName);
7364                result = null;
7365                if (pkg != null) {
7366                    result = filterIfNotSystemUser(
7367                            mActivities.queryIntentForPackage(
7368                                    intent, resolvedType, flags, pkg.activities, userId),
7369                            userId);
7370                }
7371                if (result == null || result.size() == 0) {
7372                    // the caller wants to resolve for a particular package; however, there
7373                    // were no installed results, so, try to find an ephemeral result
7374                    addEphemeral = !ephemeralDisabled
7375                            && isInstantAppAllowed(
7376                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7377                    if (result == null) {
7378                        result = new ArrayList<>();
7379                    }
7380                }
7381            }
7382        }
7383        if (addEphemeral) {
7384            result = maybeAddInstantAppInstaller(
7385                    result, intent, resolvedType, flags, userId, resolveForStart);
7386        }
7387        if (sortResult) {
7388            Collections.sort(result, mResolvePrioritySorter);
7389        }
7390        return applyPostResolutionFilter(
7391                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7392    }
7393
7394    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7395            String resolvedType, int flags, int userId, boolean resolveForStart) {
7396        // first, check to see if we've got an instant app already installed
7397        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7398        ResolveInfo localInstantApp = null;
7399        boolean blockResolution = false;
7400        if (!alreadyResolvedLocally) {
7401            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7402                    flags
7403                        | PackageManager.GET_RESOLVED_FILTER
7404                        | PackageManager.MATCH_INSTANT
7405                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7406                    userId);
7407            for (int i = instantApps.size() - 1; i >= 0; --i) {
7408                final ResolveInfo info = instantApps.get(i);
7409                final String packageName = info.activityInfo.packageName;
7410                final PackageSetting ps = mSettings.mPackages.get(packageName);
7411                if (ps.getInstantApp(userId)) {
7412                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7413                    final int status = (int)(packedStatus >> 32);
7414                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7415                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7416                        // there's a local instant application installed, but, the user has
7417                        // chosen to never use it; skip resolution and don't acknowledge
7418                        // an instant application is even available
7419                        if (DEBUG_EPHEMERAL) {
7420                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7421                        }
7422                        blockResolution = true;
7423                        break;
7424                    } else {
7425                        // we have a locally installed instant application; skip resolution
7426                        // but acknowledge there's an instant application available
7427                        if (DEBUG_EPHEMERAL) {
7428                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7429                        }
7430                        localInstantApp = info;
7431                        break;
7432                    }
7433                }
7434            }
7435        }
7436        // no app installed, let's see if one's available
7437        AuxiliaryResolveInfo auxiliaryResponse = null;
7438        if (!blockResolution) {
7439            if (localInstantApp == null) {
7440                // we don't have an instant app locally, resolve externally
7441                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7442                final InstantAppRequest requestObject = new InstantAppRequest(
7443                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7444                        null /*callingPackage*/, userId, null /*verificationBundle*/,
7445                        resolveForStart);
7446                auxiliaryResponse =
7447                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7448                                mContext, mInstantAppResolverConnection, requestObject);
7449                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7450            } else {
7451                // we have an instant application locally, but, we can't admit that since
7452                // callers shouldn't be able to determine prior browsing. create a dummy
7453                // auxiliary response so the downstream code behaves as if there's an
7454                // instant application available externally. when it comes time to start
7455                // the instant application, we'll do the right thing.
7456                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7457                auxiliaryResponse = new AuxiliaryResolveInfo(
7458                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7459                        ai.versionCode, null /*failureIntent*/);
7460            }
7461        }
7462        if (auxiliaryResponse != null) {
7463            if (DEBUG_EPHEMERAL) {
7464                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7465            }
7466            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7467            final PackageSetting ps =
7468                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7469            if (ps != null) {
7470                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7471                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7472                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7473                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7474                // make sure this resolver is the default
7475                ephemeralInstaller.isDefault = true;
7476                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7477                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7478                // add a non-generic filter
7479                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7480                ephemeralInstaller.filter.addDataPath(
7481                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7482                ephemeralInstaller.isInstantAppAvailable = true;
7483                result.add(ephemeralInstaller);
7484            }
7485        }
7486        return result;
7487    }
7488
7489    private static class CrossProfileDomainInfo {
7490        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7491        ResolveInfo resolveInfo;
7492        /* Best domain verification status of the activities found in the other profile */
7493        int bestDomainVerificationStatus;
7494    }
7495
7496    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7497            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7498        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7499                sourceUserId)) {
7500            return null;
7501        }
7502        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7503                resolvedType, flags, parentUserId);
7504
7505        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7506            return null;
7507        }
7508        CrossProfileDomainInfo result = null;
7509        int size = resultTargetUser.size();
7510        for (int i = 0; i < size; i++) {
7511            ResolveInfo riTargetUser = resultTargetUser.get(i);
7512            // Intent filter verification is only for filters that specify a host. So don't return
7513            // those that handle all web uris.
7514            if (riTargetUser.handleAllWebDataURI) {
7515                continue;
7516            }
7517            String packageName = riTargetUser.activityInfo.packageName;
7518            PackageSetting ps = mSettings.mPackages.get(packageName);
7519            if (ps == null) {
7520                continue;
7521            }
7522            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7523            int status = (int)(verificationState >> 32);
7524            if (result == null) {
7525                result = new CrossProfileDomainInfo();
7526                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7527                        sourceUserId, parentUserId);
7528                result.bestDomainVerificationStatus = status;
7529            } else {
7530                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7531                        result.bestDomainVerificationStatus);
7532            }
7533        }
7534        // Don't consider matches with status NEVER across profiles.
7535        if (result != null && result.bestDomainVerificationStatus
7536                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7537            return null;
7538        }
7539        return result;
7540    }
7541
7542    /**
7543     * Verification statuses are ordered from the worse to the best, except for
7544     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7545     */
7546    private int bestDomainVerificationStatus(int status1, int status2) {
7547        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7548            return status2;
7549        }
7550        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7551            return status1;
7552        }
7553        return (int) MathUtils.max(status1, status2);
7554    }
7555
7556    private boolean isUserEnabled(int userId) {
7557        long callingId = Binder.clearCallingIdentity();
7558        try {
7559            UserInfo userInfo = sUserManager.getUserInfo(userId);
7560            return userInfo != null && userInfo.isEnabled();
7561        } finally {
7562            Binder.restoreCallingIdentity(callingId);
7563        }
7564    }
7565
7566    /**
7567     * Filter out activities with systemUserOnly flag set, when current user is not System.
7568     *
7569     * @return filtered list
7570     */
7571    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7572        if (userId == UserHandle.USER_SYSTEM) {
7573            return resolveInfos;
7574        }
7575        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7576            ResolveInfo info = resolveInfos.get(i);
7577            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7578                resolveInfos.remove(i);
7579            }
7580        }
7581        return resolveInfos;
7582    }
7583
7584    /**
7585     * Filters out ephemeral activities.
7586     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7587     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7588     *
7589     * @param resolveInfos The pre-filtered list of resolved activities
7590     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7591     *          is performed.
7592     * @return A filtered list of resolved activities.
7593     */
7594    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7595            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7596        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7597            final ResolveInfo info = resolveInfos.get(i);
7598            // allow activities that are defined in the provided package
7599            if (allowDynamicSplits
7600                    && info.activityInfo.splitName != null
7601                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7602                            info.activityInfo.splitName)) {
7603                // requested activity is defined in a split that hasn't been installed yet.
7604                // add the installer to the resolve list
7605                if (DEBUG_INSTALL) {
7606                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7607                }
7608                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7609                final ComponentName installFailureActivity = findInstallFailureActivity(
7610                        info.activityInfo.packageName,  filterCallingUid, userId);
7611                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7612                        info.activityInfo.packageName, info.activityInfo.splitName,
7613                        installFailureActivity,
7614                        info.activityInfo.applicationInfo.versionCode,
7615                        null /*failureIntent*/);
7616                // make sure this resolver is the default
7617                installerInfo.isDefault = true;
7618                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7619                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7620                // add a non-generic filter
7621                installerInfo.filter = new IntentFilter();
7622                // load resources from the correct package
7623                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7624                resolveInfos.set(i, installerInfo);
7625                continue;
7626            }
7627            // caller is a full app, don't need to apply any other filtering
7628            if (ephemeralPkgName == null) {
7629                continue;
7630            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7631                // caller is same app; don't need to apply any other filtering
7632                continue;
7633            }
7634            // allow activities that have been explicitly exposed to ephemeral apps
7635            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7636            if (!isEphemeralApp
7637                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7638                continue;
7639            }
7640            resolveInfos.remove(i);
7641        }
7642        return resolveInfos;
7643    }
7644
7645    /**
7646     * Returns the activity component that can handle install failures.
7647     * <p>By default, the instant application installer handles failures. However, an
7648     * application may want to handle failures on its own. Applications do this by
7649     * creating an activity with an intent filter that handles the action
7650     * {@link Intent#ACTION_INSTALL_FAILURE}.
7651     */
7652    private @Nullable ComponentName findInstallFailureActivity(
7653            String packageName, int filterCallingUid, int userId) {
7654        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7655        failureActivityIntent.setPackage(packageName);
7656        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7657        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7658                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7659                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7660        final int NR = result.size();
7661        if (NR > 0) {
7662            for (int i = 0; i < NR; i++) {
7663                final ResolveInfo info = result.get(i);
7664                if (info.activityInfo.splitName != null) {
7665                    continue;
7666                }
7667                return new ComponentName(packageName, info.activityInfo.name);
7668            }
7669        }
7670        return null;
7671    }
7672
7673    /**
7674     * @param resolveInfos list of resolve infos in descending priority order
7675     * @return if the list contains a resolve info with non-negative priority
7676     */
7677    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7678        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7679    }
7680
7681    private static boolean hasWebURI(Intent intent) {
7682        if (intent.getData() == null) {
7683            return false;
7684        }
7685        final String scheme = intent.getScheme();
7686        if (TextUtils.isEmpty(scheme)) {
7687            return false;
7688        }
7689        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7690    }
7691
7692    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7693            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7694            int userId) {
7695        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7696
7697        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7698            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7699                    candidates.size());
7700        }
7701
7702        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7703        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7704        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7705        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7706        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7707        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7708
7709        synchronized (mPackages) {
7710            final int count = candidates.size();
7711            // First, try to use linked apps. Partition the candidates into four lists:
7712            // one for the final results, one for the "do not use ever", one for "undefined status"
7713            // and finally one for "browser app type".
7714            for (int n=0; n<count; n++) {
7715                ResolveInfo info = candidates.get(n);
7716                String packageName = info.activityInfo.packageName;
7717                PackageSetting ps = mSettings.mPackages.get(packageName);
7718                if (ps != null) {
7719                    // Add to the special match all list (Browser use case)
7720                    if (info.handleAllWebDataURI) {
7721                        matchAllList.add(info);
7722                        continue;
7723                    }
7724                    // Try to get the status from User settings first
7725                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7726                    int status = (int)(packedStatus >> 32);
7727                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7728                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7729                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7730                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7731                                    + " : linkgen=" + linkGeneration);
7732                        }
7733                        // Use link-enabled generation as preferredOrder, i.e.
7734                        // prefer newly-enabled over earlier-enabled.
7735                        info.preferredOrder = linkGeneration;
7736                        alwaysList.add(info);
7737                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7738                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7739                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7740                        }
7741                        neverList.add(info);
7742                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7743                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7744                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7745                        }
7746                        alwaysAskList.add(info);
7747                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7748                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7749                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7750                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7751                        }
7752                        undefinedList.add(info);
7753                    }
7754                }
7755            }
7756
7757            // We'll want to include browser possibilities in a few cases
7758            boolean includeBrowser = false;
7759
7760            // First try to add the "always" resolution(s) for the current user, if any
7761            if (alwaysList.size() > 0) {
7762                result.addAll(alwaysList);
7763            } else {
7764                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7765                result.addAll(undefinedList);
7766                // Maybe add one for the other profile.
7767                if (xpDomainInfo != null && (
7768                        xpDomainInfo.bestDomainVerificationStatus
7769                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7770                    result.add(xpDomainInfo.resolveInfo);
7771                }
7772                includeBrowser = true;
7773            }
7774
7775            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7776            // If there were 'always' entries their preferred order has been set, so we also
7777            // back that off to make the alternatives equivalent
7778            if (alwaysAskList.size() > 0) {
7779                for (ResolveInfo i : result) {
7780                    i.preferredOrder = 0;
7781                }
7782                result.addAll(alwaysAskList);
7783                includeBrowser = true;
7784            }
7785
7786            if (includeBrowser) {
7787                // Also add browsers (all of them or only the default one)
7788                if (DEBUG_DOMAIN_VERIFICATION) {
7789                    Slog.v(TAG, "   ...including browsers in candidate set");
7790                }
7791                if ((matchFlags & MATCH_ALL) != 0) {
7792                    result.addAll(matchAllList);
7793                } else {
7794                    // Browser/generic handling case.  If there's a default browser, go straight
7795                    // to that (but only if there is no other higher-priority match).
7796                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7797                    int maxMatchPrio = 0;
7798                    ResolveInfo defaultBrowserMatch = null;
7799                    final int numCandidates = matchAllList.size();
7800                    for (int n = 0; n < numCandidates; n++) {
7801                        ResolveInfo info = matchAllList.get(n);
7802                        // track the highest overall match priority...
7803                        if (info.priority > maxMatchPrio) {
7804                            maxMatchPrio = info.priority;
7805                        }
7806                        // ...and the highest-priority default browser match
7807                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7808                            if (defaultBrowserMatch == null
7809                                    || (defaultBrowserMatch.priority < info.priority)) {
7810                                if (debug) {
7811                                    Slog.v(TAG, "Considering default browser match " + info);
7812                                }
7813                                defaultBrowserMatch = info;
7814                            }
7815                        }
7816                    }
7817                    if (defaultBrowserMatch != null
7818                            && defaultBrowserMatch.priority >= maxMatchPrio
7819                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7820                    {
7821                        if (debug) {
7822                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7823                        }
7824                        result.add(defaultBrowserMatch);
7825                    } else {
7826                        result.addAll(matchAllList);
7827                    }
7828                }
7829
7830                // If there is nothing selected, add all candidates and remove the ones that the user
7831                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7832                if (result.size() == 0) {
7833                    result.addAll(candidates);
7834                    result.removeAll(neverList);
7835                }
7836            }
7837        }
7838        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7839            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7840                    result.size());
7841            for (ResolveInfo info : result) {
7842                Slog.v(TAG, "  + " + info.activityInfo);
7843            }
7844        }
7845        return result;
7846    }
7847
7848    // Returns a packed value as a long:
7849    //
7850    // high 'int'-sized word: link status: undefined/ask/never/always.
7851    // low 'int'-sized word: relative priority among 'always' results.
7852    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7853        long result = ps.getDomainVerificationStatusForUser(userId);
7854        // if none available, get the master status
7855        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7856            if (ps.getIntentFilterVerificationInfo() != null) {
7857                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7858            }
7859        }
7860        return result;
7861    }
7862
7863    private ResolveInfo querySkipCurrentProfileIntents(
7864            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7865            int flags, int sourceUserId) {
7866        if (matchingFilters != null) {
7867            int size = matchingFilters.size();
7868            for (int i = 0; i < size; i ++) {
7869                CrossProfileIntentFilter filter = matchingFilters.get(i);
7870                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7871                    // Checking if there are activities in the target user that can handle the
7872                    // intent.
7873                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7874                            resolvedType, flags, sourceUserId);
7875                    if (resolveInfo != null) {
7876                        return resolveInfo;
7877                    }
7878                }
7879            }
7880        }
7881        return null;
7882    }
7883
7884    // Return matching ResolveInfo in target user if any.
7885    private ResolveInfo queryCrossProfileIntents(
7886            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7887            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7888        if (matchingFilters != null) {
7889            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7890            // match the same intent. For performance reasons, it is better not to
7891            // run queryIntent twice for the same userId
7892            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7893            int size = matchingFilters.size();
7894            for (int i = 0; i < size; i++) {
7895                CrossProfileIntentFilter filter = matchingFilters.get(i);
7896                int targetUserId = filter.getTargetUserId();
7897                boolean skipCurrentProfile =
7898                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7899                boolean skipCurrentProfileIfNoMatchFound =
7900                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7901                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7902                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7903                    // Checking if there are activities in the target user that can handle the
7904                    // intent.
7905                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7906                            resolvedType, flags, sourceUserId);
7907                    if (resolveInfo != null) return resolveInfo;
7908                    alreadyTriedUserIds.put(targetUserId, true);
7909                }
7910            }
7911        }
7912        return null;
7913    }
7914
7915    /**
7916     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7917     * will forward the intent to the filter's target user.
7918     * Otherwise, returns null.
7919     */
7920    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7921            String resolvedType, int flags, int sourceUserId) {
7922        int targetUserId = filter.getTargetUserId();
7923        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7924                resolvedType, flags, targetUserId);
7925        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7926            // If all the matches in the target profile are suspended, return null.
7927            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7928                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7929                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7930                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7931                            targetUserId);
7932                }
7933            }
7934        }
7935        return null;
7936    }
7937
7938    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7939            int sourceUserId, int targetUserId) {
7940        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7941        long ident = Binder.clearCallingIdentity();
7942        boolean targetIsProfile;
7943        try {
7944            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7945        } finally {
7946            Binder.restoreCallingIdentity(ident);
7947        }
7948        String className;
7949        if (targetIsProfile) {
7950            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7951        } else {
7952            className = FORWARD_INTENT_TO_PARENT;
7953        }
7954        ComponentName forwardingActivityComponentName = new ComponentName(
7955                mAndroidApplication.packageName, className);
7956        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7957                sourceUserId);
7958        if (!targetIsProfile) {
7959            forwardingActivityInfo.showUserIcon = targetUserId;
7960            forwardingResolveInfo.noResourceId = true;
7961        }
7962        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7963        forwardingResolveInfo.priority = 0;
7964        forwardingResolveInfo.preferredOrder = 0;
7965        forwardingResolveInfo.match = 0;
7966        forwardingResolveInfo.isDefault = true;
7967        forwardingResolveInfo.filter = filter;
7968        forwardingResolveInfo.targetUserId = targetUserId;
7969        return forwardingResolveInfo;
7970    }
7971
7972    @Override
7973    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7974            Intent[] specifics, String[] specificTypes, Intent intent,
7975            String resolvedType, int flags, int userId) {
7976        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7977                specificTypes, intent, resolvedType, flags, userId));
7978    }
7979
7980    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7981            Intent[] specifics, String[] specificTypes, Intent intent,
7982            String resolvedType, int flags, int userId) {
7983        if (!sUserManager.exists(userId)) return Collections.emptyList();
7984        final int callingUid = Binder.getCallingUid();
7985        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7986                false /*includeInstantApps*/);
7987        enforceCrossUserPermission(callingUid, userId,
7988                false /*requireFullPermission*/, false /*checkShell*/,
7989                "query intent activity options");
7990        final String resultsAction = intent.getAction();
7991
7992        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7993                | PackageManager.GET_RESOLVED_FILTER, userId);
7994
7995        if (DEBUG_INTENT_MATCHING) {
7996            Log.v(TAG, "Query " + intent + ": " + results);
7997        }
7998
7999        int specificsPos = 0;
8000        int N;
8001
8002        // todo: note that the algorithm used here is O(N^2).  This
8003        // isn't a problem in our current environment, but if we start running
8004        // into situations where we have more than 5 or 10 matches then this
8005        // should probably be changed to something smarter...
8006
8007        // First we go through and resolve each of the specific items
8008        // that were supplied, taking care of removing any corresponding
8009        // duplicate items in the generic resolve list.
8010        if (specifics != null) {
8011            for (int i=0; i<specifics.length; i++) {
8012                final Intent sintent = specifics[i];
8013                if (sintent == null) {
8014                    continue;
8015                }
8016
8017                if (DEBUG_INTENT_MATCHING) {
8018                    Log.v(TAG, "Specific #" + i + ": " + sintent);
8019                }
8020
8021                String action = sintent.getAction();
8022                if (resultsAction != null && resultsAction.equals(action)) {
8023                    // If this action was explicitly requested, then don't
8024                    // remove things that have it.
8025                    action = null;
8026                }
8027
8028                ResolveInfo ri = null;
8029                ActivityInfo ai = null;
8030
8031                ComponentName comp = sintent.getComponent();
8032                if (comp == null) {
8033                    ri = resolveIntent(
8034                        sintent,
8035                        specificTypes != null ? specificTypes[i] : null,
8036                            flags, userId);
8037                    if (ri == null) {
8038                        continue;
8039                    }
8040                    if (ri == mResolveInfo) {
8041                        // ACK!  Must do something better with this.
8042                    }
8043                    ai = ri.activityInfo;
8044                    comp = new ComponentName(ai.applicationInfo.packageName,
8045                            ai.name);
8046                } else {
8047                    ai = getActivityInfo(comp, flags, userId);
8048                    if (ai == null) {
8049                        continue;
8050                    }
8051                }
8052
8053                // Look for any generic query activities that are duplicates
8054                // of this specific one, and remove them from the results.
8055                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
8056                N = results.size();
8057                int j;
8058                for (j=specificsPos; j<N; j++) {
8059                    ResolveInfo sri = results.get(j);
8060                    if ((sri.activityInfo.name.equals(comp.getClassName())
8061                            && sri.activityInfo.applicationInfo.packageName.equals(
8062                                    comp.getPackageName()))
8063                        || (action != null && sri.filter.matchAction(action))) {
8064                        results.remove(j);
8065                        if (DEBUG_INTENT_MATCHING) Log.v(
8066                            TAG, "Removing duplicate item from " + j
8067                            + " due to specific " + specificsPos);
8068                        if (ri == null) {
8069                            ri = sri;
8070                        }
8071                        j--;
8072                        N--;
8073                    }
8074                }
8075
8076                // Add this specific item to its proper place.
8077                if (ri == null) {
8078                    ri = new ResolveInfo();
8079                    ri.activityInfo = ai;
8080                }
8081                results.add(specificsPos, ri);
8082                ri.specificIndex = i;
8083                specificsPos++;
8084            }
8085        }
8086
8087        // Now we go through the remaining generic results and remove any
8088        // duplicate actions that are found here.
8089        N = results.size();
8090        for (int i=specificsPos; i<N-1; i++) {
8091            final ResolveInfo rii = results.get(i);
8092            if (rii.filter == null) {
8093                continue;
8094            }
8095
8096            // Iterate over all of the actions of this result's intent
8097            // filter...  typically this should be just one.
8098            final Iterator<String> it = rii.filter.actionsIterator();
8099            if (it == null) {
8100                continue;
8101            }
8102            while (it.hasNext()) {
8103                final String action = it.next();
8104                if (resultsAction != null && resultsAction.equals(action)) {
8105                    // If this action was explicitly requested, then don't
8106                    // remove things that have it.
8107                    continue;
8108                }
8109                for (int j=i+1; j<N; j++) {
8110                    final ResolveInfo rij = results.get(j);
8111                    if (rij.filter != null && rij.filter.hasAction(action)) {
8112                        results.remove(j);
8113                        if (DEBUG_INTENT_MATCHING) Log.v(
8114                            TAG, "Removing duplicate item from " + j
8115                            + " due to action " + action + " at " + i);
8116                        j--;
8117                        N--;
8118                    }
8119                }
8120            }
8121
8122            // If the caller didn't request filter information, drop it now
8123            // so we don't have to marshall/unmarshall it.
8124            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8125                rii.filter = null;
8126            }
8127        }
8128
8129        // Filter out the caller activity if so requested.
8130        if (caller != null) {
8131            N = results.size();
8132            for (int i=0; i<N; i++) {
8133                ActivityInfo ainfo = results.get(i).activityInfo;
8134                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8135                        && caller.getClassName().equals(ainfo.name)) {
8136                    results.remove(i);
8137                    break;
8138                }
8139            }
8140        }
8141
8142        // If the caller didn't request filter information,
8143        // drop them now so we don't have to
8144        // marshall/unmarshall it.
8145        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8146            N = results.size();
8147            for (int i=0; i<N; i++) {
8148                results.get(i).filter = null;
8149            }
8150        }
8151
8152        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8153        return results;
8154    }
8155
8156    @Override
8157    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8158            String resolvedType, int flags, int userId) {
8159        return new ParceledListSlice<>(
8160                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8161                        false /*allowDynamicSplits*/));
8162    }
8163
8164    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8165            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8166        if (!sUserManager.exists(userId)) return Collections.emptyList();
8167        final int callingUid = Binder.getCallingUid();
8168        enforceCrossUserPermission(callingUid, userId,
8169                false /*requireFullPermission*/, false /*checkShell*/,
8170                "query intent receivers");
8171        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8172        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8173                false /*includeInstantApps*/);
8174        ComponentName comp = intent.getComponent();
8175        if (comp == null) {
8176            if (intent.getSelector() != null) {
8177                intent = intent.getSelector();
8178                comp = intent.getComponent();
8179            }
8180        }
8181        if (comp != null) {
8182            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8183            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8184            if (ai != null) {
8185                // When specifying an explicit component, we prevent the activity from being
8186                // used when either 1) the calling package is normal and the activity is within
8187                // an instant application or 2) the calling package is ephemeral and the
8188                // activity is not visible to instant applications.
8189                final boolean matchInstantApp =
8190                        (flags & PackageManager.MATCH_INSTANT) != 0;
8191                final boolean matchVisibleToInstantAppOnly =
8192                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8193                final boolean matchExplicitlyVisibleOnly =
8194                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8195                final boolean isCallerInstantApp =
8196                        instantAppPkgName != null;
8197                final boolean isTargetSameInstantApp =
8198                        comp.getPackageName().equals(instantAppPkgName);
8199                final boolean isTargetInstantApp =
8200                        (ai.applicationInfo.privateFlags
8201                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8202                final boolean isTargetVisibleToInstantApp =
8203                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8204                final boolean isTargetExplicitlyVisibleToInstantApp =
8205                        isTargetVisibleToInstantApp
8206                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8207                final boolean isTargetHiddenFromInstantApp =
8208                        !isTargetVisibleToInstantApp
8209                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8210                final boolean blockResolution =
8211                        !isTargetSameInstantApp
8212                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8213                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8214                                        && isTargetHiddenFromInstantApp));
8215                if (!blockResolution) {
8216                    ResolveInfo ri = new ResolveInfo();
8217                    ri.activityInfo = ai;
8218                    list.add(ri);
8219                }
8220            }
8221            return applyPostResolutionFilter(
8222                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8223        }
8224
8225        // reader
8226        synchronized (mPackages) {
8227            String pkgName = intent.getPackage();
8228            if (pkgName == null) {
8229                final List<ResolveInfo> result =
8230                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8231                return applyPostResolutionFilter(
8232                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8233            }
8234            final PackageParser.Package pkg = mPackages.get(pkgName);
8235            if (pkg != null) {
8236                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8237                        intent, resolvedType, flags, pkg.receivers, userId);
8238                return applyPostResolutionFilter(
8239                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8240            }
8241            return Collections.emptyList();
8242        }
8243    }
8244
8245    @Override
8246    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8247        final int callingUid = Binder.getCallingUid();
8248        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8249    }
8250
8251    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8252            int userId, int callingUid) {
8253        if (!sUserManager.exists(userId)) return null;
8254        flags = updateFlagsForResolve(
8255                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8256        List<ResolveInfo> query = queryIntentServicesInternal(
8257                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8258        if (query != null) {
8259            if (query.size() >= 1) {
8260                // If there is more than one service with the same priority,
8261                // just arbitrarily pick the first one.
8262                return query.get(0);
8263            }
8264        }
8265        return null;
8266    }
8267
8268    @Override
8269    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8270            String resolvedType, int flags, int userId) {
8271        final int callingUid = Binder.getCallingUid();
8272        return new ParceledListSlice<>(queryIntentServicesInternal(
8273                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8274    }
8275
8276    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8277            String resolvedType, int flags, int userId, int callingUid,
8278            boolean includeInstantApps) {
8279        if (!sUserManager.exists(userId)) return Collections.emptyList();
8280        enforceCrossUserPermission(callingUid, userId,
8281                false /*requireFullPermission*/, false /*checkShell*/,
8282                "query intent receivers");
8283        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8284        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8285        ComponentName comp = intent.getComponent();
8286        if (comp == null) {
8287            if (intent.getSelector() != null) {
8288                intent = intent.getSelector();
8289                comp = intent.getComponent();
8290            }
8291        }
8292        if (comp != null) {
8293            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8294            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8295            if (si != null) {
8296                // When specifying an explicit component, we prevent the service from being
8297                // used when either 1) the service is in an instant application and the
8298                // caller is not the same instant application or 2) the calling package is
8299                // ephemeral and the activity is not visible to ephemeral applications.
8300                final boolean matchInstantApp =
8301                        (flags & PackageManager.MATCH_INSTANT) != 0;
8302                final boolean matchVisibleToInstantAppOnly =
8303                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8304                final boolean isCallerInstantApp =
8305                        instantAppPkgName != null;
8306                final boolean isTargetSameInstantApp =
8307                        comp.getPackageName().equals(instantAppPkgName);
8308                final boolean isTargetInstantApp =
8309                        (si.applicationInfo.privateFlags
8310                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8311                final boolean isTargetHiddenFromInstantApp =
8312                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8313                final boolean blockResolution =
8314                        !isTargetSameInstantApp
8315                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8316                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8317                                        && isTargetHiddenFromInstantApp));
8318                if (!blockResolution) {
8319                    final ResolveInfo ri = new ResolveInfo();
8320                    ri.serviceInfo = si;
8321                    list.add(ri);
8322                }
8323            }
8324            return list;
8325        }
8326
8327        // reader
8328        synchronized (mPackages) {
8329            String pkgName = intent.getPackage();
8330            if (pkgName == null) {
8331                return applyPostServiceResolutionFilter(
8332                        mServices.queryIntent(intent, resolvedType, flags, userId),
8333                        instantAppPkgName);
8334            }
8335            final PackageParser.Package pkg = mPackages.get(pkgName);
8336            if (pkg != null) {
8337                return applyPostServiceResolutionFilter(
8338                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8339                                userId),
8340                        instantAppPkgName);
8341            }
8342            return Collections.emptyList();
8343        }
8344    }
8345
8346    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8347            String instantAppPkgName) {
8348        if (instantAppPkgName == null) {
8349            return resolveInfos;
8350        }
8351        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8352            final ResolveInfo info = resolveInfos.get(i);
8353            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8354            // allow services that are defined in the provided package
8355            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8356                if (info.serviceInfo.splitName != null
8357                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8358                                info.serviceInfo.splitName)) {
8359                    // requested service is defined in a split that hasn't been installed yet.
8360                    // add the installer to the resolve list
8361                    if (DEBUG_EPHEMERAL) {
8362                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8363                    }
8364                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8365                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8366                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8367                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8368                            null /*failureIntent*/);
8369                    // make sure this resolver is the default
8370                    installerInfo.isDefault = true;
8371                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8372                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8373                    // add a non-generic filter
8374                    installerInfo.filter = new IntentFilter();
8375                    // load resources from the correct package
8376                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8377                    resolveInfos.set(i, installerInfo);
8378                }
8379                continue;
8380            }
8381            // allow services that have been explicitly exposed to ephemeral apps
8382            if (!isEphemeralApp
8383                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8384                continue;
8385            }
8386            resolveInfos.remove(i);
8387        }
8388        return resolveInfos;
8389    }
8390
8391    @Override
8392    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8393            String resolvedType, int flags, int userId) {
8394        return new ParceledListSlice<>(
8395                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8396    }
8397
8398    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8399            Intent intent, String resolvedType, int flags, int userId) {
8400        if (!sUserManager.exists(userId)) return Collections.emptyList();
8401        final int callingUid = Binder.getCallingUid();
8402        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8403        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8404                false /*includeInstantApps*/);
8405        ComponentName comp = intent.getComponent();
8406        if (comp == null) {
8407            if (intent.getSelector() != null) {
8408                intent = intent.getSelector();
8409                comp = intent.getComponent();
8410            }
8411        }
8412        if (comp != null) {
8413            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8414            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8415            if (pi != null) {
8416                // When specifying an explicit component, we prevent the provider from being
8417                // used when either 1) the provider is in an instant application and the
8418                // caller is not the same instant application or 2) the calling package is an
8419                // instant application and the provider is not visible to instant applications.
8420                final boolean matchInstantApp =
8421                        (flags & PackageManager.MATCH_INSTANT) != 0;
8422                final boolean matchVisibleToInstantAppOnly =
8423                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8424                final boolean isCallerInstantApp =
8425                        instantAppPkgName != null;
8426                final boolean isTargetSameInstantApp =
8427                        comp.getPackageName().equals(instantAppPkgName);
8428                final boolean isTargetInstantApp =
8429                        (pi.applicationInfo.privateFlags
8430                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8431                final boolean isTargetHiddenFromInstantApp =
8432                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8433                final boolean blockResolution =
8434                        !isTargetSameInstantApp
8435                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8436                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8437                                        && isTargetHiddenFromInstantApp));
8438                if (!blockResolution) {
8439                    final ResolveInfo ri = new ResolveInfo();
8440                    ri.providerInfo = pi;
8441                    list.add(ri);
8442                }
8443            }
8444            return list;
8445        }
8446
8447        // reader
8448        synchronized (mPackages) {
8449            String pkgName = intent.getPackage();
8450            if (pkgName == null) {
8451                return applyPostContentProviderResolutionFilter(
8452                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8453                        instantAppPkgName);
8454            }
8455            final PackageParser.Package pkg = mPackages.get(pkgName);
8456            if (pkg != null) {
8457                return applyPostContentProviderResolutionFilter(
8458                        mProviders.queryIntentForPackage(
8459                        intent, resolvedType, flags, pkg.providers, userId),
8460                        instantAppPkgName);
8461            }
8462            return Collections.emptyList();
8463        }
8464    }
8465
8466    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8467            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8468        if (instantAppPkgName == null) {
8469            return resolveInfos;
8470        }
8471        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8472            final ResolveInfo info = resolveInfos.get(i);
8473            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8474            // allow providers that are defined in the provided package
8475            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8476                if (info.providerInfo.splitName != null
8477                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8478                                info.providerInfo.splitName)) {
8479                    // requested provider is defined in a split that hasn't been installed yet.
8480                    // add the installer to the resolve list
8481                    if (DEBUG_EPHEMERAL) {
8482                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8483                    }
8484                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8485                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8486                            info.providerInfo.packageName, info.providerInfo.splitName,
8487                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8488                            null /*failureIntent*/);
8489                    // make sure this resolver is the default
8490                    installerInfo.isDefault = true;
8491                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8492                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8493                    // add a non-generic filter
8494                    installerInfo.filter = new IntentFilter();
8495                    // load resources from the correct package
8496                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8497                    resolveInfos.set(i, installerInfo);
8498                }
8499                continue;
8500            }
8501            // allow providers that have been explicitly exposed to instant applications
8502            if (!isEphemeralApp
8503                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8504                continue;
8505            }
8506            resolveInfos.remove(i);
8507        }
8508        return resolveInfos;
8509    }
8510
8511    @Override
8512    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8513        final int callingUid = Binder.getCallingUid();
8514        if (getInstantAppPackageName(callingUid) != null) {
8515            return ParceledListSlice.emptyList();
8516        }
8517        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8518        flags = updateFlagsForPackage(flags, userId, null);
8519        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8520        enforceCrossUserPermission(callingUid, userId,
8521                true /* requireFullPermission */, false /* checkShell */,
8522                "get installed packages");
8523
8524        // writer
8525        synchronized (mPackages) {
8526            ArrayList<PackageInfo> list;
8527            if (listUninstalled) {
8528                list = new ArrayList<>(mSettings.mPackages.size());
8529                for (PackageSetting ps : mSettings.mPackages.values()) {
8530                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8531                        continue;
8532                    }
8533                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8534                        continue;
8535                    }
8536                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8537                    if (pi != null) {
8538                        list.add(pi);
8539                    }
8540                }
8541            } else {
8542                list = new ArrayList<>(mPackages.size());
8543                for (PackageParser.Package p : mPackages.values()) {
8544                    final PackageSetting ps = (PackageSetting) p.mExtras;
8545                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8546                        continue;
8547                    }
8548                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8549                        continue;
8550                    }
8551                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8552                            p.mExtras, flags, userId);
8553                    if (pi != null) {
8554                        list.add(pi);
8555                    }
8556                }
8557            }
8558
8559            return new ParceledListSlice<>(list);
8560        }
8561    }
8562
8563    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8564            String[] permissions, boolean[] tmp, int flags, int userId) {
8565        int numMatch = 0;
8566        final PermissionsState permissionsState = ps.getPermissionsState();
8567        for (int i=0; i<permissions.length; i++) {
8568            final String permission = permissions[i];
8569            if (permissionsState.hasPermission(permission, userId)) {
8570                tmp[i] = true;
8571                numMatch++;
8572            } else {
8573                tmp[i] = false;
8574            }
8575        }
8576        if (numMatch == 0) {
8577            return;
8578        }
8579        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8580
8581        // The above might return null in cases of uninstalled apps or install-state
8582        // skew across users/profiles.
8583        if (pi != null) {
8584            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8585                if (numMatch == permissions.length) {
8586                    pi.requestedPermissions = permissions;
8587                } else {
8588                    pi.requestedPermissions = new String[numMatch];
8589                    numMatch = 0;
8590                    for (int i=0; i<permissions.length; i++) {
8591                        if (tmp[i]) {
8592                            pi.requestedPermissions[numMatch] = permissions[i];
8593                            numMatch++;
8594                        }
8595                    }
8596                }
8597            }
8598            list.add(pi);
8599        }
8600    }
8601
8602    @Override
8603    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8604            String[] permissions, int flags, int userId) {
8605        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8606        flags = updateFlagsForPackage(flags, userId, permissions);
8607        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8608                true /* requireFullPermission */, false /* checkShell */,
8609                "get packages holding permissions");
8610        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8611
8612        // writer
8613        synchronized (mPackages) {
8614            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8615            boolean[] tmpBools = new boolean[permissions.length];
8616            if (listUninstalled) {
8617                for (PackageSetting ps : mSettings.mPackages.values()) {
8618                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8619                            userId);
8620                }
8621            } else {
8622                for (PackageParser.Package pkg : mPackages.values()) {
8623                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8624                    if (ps != null) {
8625                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8626                                userId);
8627                    }
8628                }
8629            }
8630
8631            return new ParceledListSlice<PackageInfo>(list);
8632        }
8633    }
8634
8635    @Override
8636    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8637        final int callingUid = Binder.getCallingUid();
8638        if (getInstantAppPackageName(callingUid) != null) {
8639            return ParceledListSlice.emptyList();
8640        }
8641        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8642        flags = updateFlagsForApplication(flags, userId, null);
8643        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8644
8645        // writer
8646        synchronized (mPackages) {
8647            ArrayList<ApplicationInfo> list;
8648            if (listUninstalled) {
8649                list = new ArrayList<>(mSettings.mPackages.size());
8650                for (PackageSetting ps : mSettings.mPackages.values()) {
8651                    ApplicationInfo ai;
8652                    int effectiveFlags = flags;
8653                    if (ps.isSystem()) {
8654                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8655                    }
8656                    if (ps.pkg != null) {
8657                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8658                            continue;
8659                        }
8660                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8661                            continue;
8662                        }
8663                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8664                                ps.readUserState(userId), userId);
8665                        if (ai != null) {
8666                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8667                        }
8668                    } else {
8669                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8670                        // and already converts to externally visible package name
8671                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8672                                callingUid, effectiveFlags, userId);
8673                    }
8674                    if (ai != null) {
8675                        list.add(ai);
8676                    }
8677                }
8678            } else {
8679                list = new ArrayList<>(mPackages.size());
8680                for (PackageParser.Package p : mPackages.values()) {
8681                    if (p.mExtras != null) {
8682                        PackageSetting ps = (PackageSetting) p.mExtras;
8683                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8684                            continue;
8685                        }
8686                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8687                            continue;
8688                        }
8689                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8690                                ps.readUserState(userId), userId);
8691                        if (ai != null) {
8692                            ai.packageName = resolveExternalPackageNameLPr(p);
8693                            list.add(ai);
8694                        }
8695                    }
8696                }
8697            }
8698
8699            return new ParceledListSlice<>(list);
8700        }
8701    }
8702
8703    @Override
8704    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8705        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8706            return null;
8707        }
8708        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8709            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8710                    "getEphemeralApplications");
8711        }
8712        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8713                true /* requireFullPermission */, false /* checkShell */,
8714                "getEphemeralApplications");
8715        synchronized (mPackages) {
8716            List<InstantAppInfo> instantApps = mInstantAppRegistry
8717                    .getInstantAppsLPr(userId);
8718            if (instantApps != null) {
8719                return new ParceledListSlice<>(instantApps);
8720            }
8721        }
8722        return null;
8723    }
8724
8725    @Override
8726    public boolean isInstantApp(String packageName, int userId) {
8727        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8728                true /* requireFullPermission */, false /* checkShell */,
8729                "isInstantApp");
8730        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8731            return false;
8732        }
8733
8734        synchronized (mPackages) {
8735            int callingUid = Binder.getCallingUid();
8736            if (Process.isIsolated(callingUid)) {
8737                callingUid = mIsolatedOwners.get(callingUid);
8738            }
8739            final PackageSetting ps = mSettings.mPackages.get(packageName);
8740            PackageParser.Package pkg = mPackages.get(packageName);
8741            final boolean returnAllowed =
8742                    ps != null
8743                    && (isCallerSameApp(packageName, callingUid)
8744                            || canViewInstantApps(callingUid, userId)
8745                            || mInstantAppRegistry.isInstantAccessGranted(
8746                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8747            if (returnAllowed) {
8748                return ps.getInstantApp(userId);
8749            }
8750        }
8751        return false;
8752    }
8753
8754    @Override
8755    public byte[] getInstantAppCookie(String packageName, int userId) {
8756        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8757            return null;
8758        }
8759
8760        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8761                true /* requireFullPermission */, false /* checkShell */,
8762                "getInstantAppCookie");
8763        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8764            return null;
8765        }
8766        synchronized (mPackages) {
8767            return mInstantAppRegistry.getInstantAppCookieLPw(
8768                    packageName, userId);
8769        }
8770    }
8771
8772    @Override
8773    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8774        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8775            return true;
8776        }
8777
8778        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8779                true /* requireFullPermission */, true /* checkShell */,
8780                "setInstantAppCookie");
8781        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8782            return false;
8783        }
8784        synchronized (mPackages) {
8785            return mInstantAppRegistry.setInstantAppCookieLPw(
8786                    packageName, cookie, userId);
8787        }
8788    }
8789
8790    @Override
8791    public Bitmap getInstantAppIcon(String packageName, int userId) {
8792        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8793            return null;
8794        }
8795
8796        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8797            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8798                    "getInstantAppIcon");
8799        }
8800        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8801                true /* requireFullPermission */, false /* checkShell */,
8802                "getInstantAppIcon");
8803
8804        synchronized (mPackages) {
8805            return mInstantAppRegistry.getInstantAppIconLPw(
8806                    packageName, userId);
8807        }
8808    }
8809
8810    private boolean isCallerSameApp(String packageName, int uid) {
8811        PackageParser.Package pkg = mPackages.get(packageName);
8812        return pkg != null
8813                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8814    }
8815
8816    @Override
8817    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8818        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8819            return ParceledListSlice.emptyList();
8820        }
8821        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8822    }
8823
8824    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8825        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8826
8827        // reader
8828        synchronized (mPackages) {
8829            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8830            final int userId = UserHandle.getCallingUserId();
8831            while (i.hasNext()) {
8832                final PackageParser.Package p = i.next();
8833                if (p.applicationInfo == null) continue;
8834
8835                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8836                        && !p.applicationInfo.isDirectBootAware();
8837                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8838                        && p.applicationInfo.isDirectBootAware();
8839
8840                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8841                        && (!mSafeMode || isSystemApp(p))
8842                        && (matchesUnaware || matchesAware)) {
8843                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8844                    if (ps != null) {
8845                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8846                                ps.readUserState(userId), userId);
8847                        if (ai != null) {
8848                            finalList.add(ai);
8849                        }
8850                    }
8851                }
8852            }
8853        }
8854
8855        return finalList;
8856    }
8857
8858    @Override
8859    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8860        if (!sUserManager.exists(userId)) return null;
8861        flags = updateFlagsForComponent(flags, userId, name);
8862        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8863        // reader
8864        synchronized (mPackages) {
8865            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8866            PackageSetting ps = provider != null
8867                    ? mSettings.mPackages.get(provider.owner.packageName)
8868                    : null;
8869            if (ps != null) {
8870                final boolean isInstantApp = ps.getInstantApp(userId);
8871                // normal application; filter out instant application provider
8872                if (instantAppPkgName == null && isInstantApp) {
8873                    return null;
8874                }
8875                // instant application; filter out other instant applications
8876                if (instantAppPkgName != null
8877                        && isInstantApp
8878                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8879                    return null;
8880                }
8881                // instant application; filter out non-exposed provider
8882                if (instantAppPkgName != null
8883                        && !isInstantApp
8884                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8885                    return null;
8886                }
8887                // provider not enabled
8888                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8889                    return null;
8890                }
8891                return PackageParser.generateProviderInfo(
8892                        provider, flags, ps.readUserState(userId), userId);
8893            }
8894            return null;
8895        }
8896    }
8897
8898    /**
8899     * @deprecated
8900     */
8901    @Deprecated
8902    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8903        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8904            return;
8905        }
8906        // reader
8907        synchronized (mPackages) {
8908            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8909                    .entrySet().iterator();
8910            final int userId = UserHandle.getCallingUserId();
8911            while (i.hasNext()) {
8912                Map.Entry<String, PackageParser.Provider> entry = i.next();
8913                PackageParser.Provider p = entry.getValue();
8914                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8915
8916                if (ps != null && p.syncable
8917                        && (!mSafeMode || (p.info.applicationInfo.flags
8918                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8919                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8920                            ps.readUserState(userId), userId);
8921                    if (info != null) {
8922                        outNames.add(entry.getKey());
8923                        outInfo.add(info);
8924                    }
8925                }
8926            }
8927        }
8928    }
8929
8930    @Override
8931    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8932            int uid, int flags, String metaDataKey) {
8933        final int callingUid = Binder.getCallingUid();
8934        final int userId = processName != null ? UserHandle.getUserId(uid)
8935                : UserHandle.getCallingUserId();
8936        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8937        flags = updateFlagsForComponent(flags, userId, processName);
8938        ArrayList<ProviderInfo> finalList = null;
8939        // reader
8940        synchronized (mPackages) {
8941            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8942            while (i.hasNext()) {
8943                final PackageParser.Provider p = i.next();
8944                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8945                if (ps != null && p.info.authority != null
8946                        && (processName == null
8947                                || (p.info.processName.equals(processName)
8948                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8949                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8950
8951                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8952                    // parameter.
8953                    if (metaDataKey != null
8954                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8955                        continue;
8956                    }
8957                    final ComponentName component =
8958                            new ComponentName(p.info.packageName, p.info.name);
8959                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8960                        continue;
8961                    }
8962                    if (finalList == null) {
8963                        finalList = new ArrayList<ProviderInfo>(3);
8964                    }
8965                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8966                            ps.readUserState(userId), userId);
8967                    if (info != null) {
8968                        finalList.add(info);
8969                    }
8970                }
8971            }
8972        }
8973
8974        if (finalList != null) {
8975            Collections.sort(finalList, mProviderInitOrderSorter);
8976            return new ParceledListSlice<ProviderInfo>(finalList);
8977        }
8978
8979        return ParceledListSlice.emptyList();
8980    }
8981
8982    @Override
8983    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8984        // reader
8985        synchronized (mPackages) {
8986            final int callingUid = Binder.getCallingUid();
8987            final int callingUserId = UserHandle.getUserId(callingUid);
8988            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8989            if (ps == null) return null;
8990            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8991                return null;
8992            }
8993            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8994            return PackageParser.generateInstrumentationInfo(i, flags);
8995        }
8996    }
8997
8998    @Override
8999    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
9000            String targetPackage, int flags) {
9001        final int callingUid = Binder.getCallingUid();
9002        final int callingUserId = UserHandle.getUserId(callingUid);
9003        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
9004        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
9005            return ParceledListSlice.emptyList();
9006        }
9007        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
9008    }
9009
9010    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
9011            int flags) {
9012        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
9013
9014        // reader
9015        synchronized (mPackages) {
9016            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
9017            while (i.hasNext()) {
9018                final PackageParser.Instrumentation p = i.next();
9019                if (targetPackage == null
9020                        || targetPackage.equals(p.info.targetPackage)) {
9021                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
9022                            flags);
9023                    if (ii != null) {
9024                        finalList.add(ii);
9025                    }
9026                }
9027            }
9028        }
9029
9030        return finalList;
9031    }
9032
9033    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
9034        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
9035        try {
9036            scanDirLI(dir, parseFlags, scanFlags, currentTime);
9037        } finally {
9038            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9039        }
9040    }
9041
9042    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
9043        final File[] files = dir.listFiles();
9044        if (ArrayUtils.isEmpty(files)) {
9045            Log.d(TAG, "No files in app dir " + dir);
9046            return;
9047        }
9048
9049        if (DEBUG_PACKAGE_SCANNING) {
9050            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
9051                    + " flags=0x" + Integer.toHexString(parseFlags));
9052        }
9053        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
9054                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
9055                mParallelPackageParserCallback);
9056
9057        // Submit files for parsing in parallel
9058        int fileCount = 0;
9059        for (File file : files) {
9060            final boolean isPackage = (isApkFile(file) || file.isDirectory())
9061                    && !PackageInstallerService.isStageName(file.getName());
9062            if (!isPackage) {
9063                // Ignore entries which are not packages
9064                continue;
9065            }
9066            parallelPackageParser.submit(file, parseFlags);
9067            fileCount++;
9068        }
9069
9070        // Process results one by one
9071        for (; fileCount > 0; fileCount--) {
9072            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
9073            Throwable throwable = parseResult.throwable;
9074            int errorCode = PackageManager.INSTALL_SUCCEEDED;
9075
9076            if (throwable == null) {
9077                // Static shared libraries have synthetic package names
9078                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
9079                    renameStaticSharedLibraryPackage(parseResult.pkg);
9080                }
9081                try {
9082                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
9083                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
9084                                currentTime, null);
9085                    }
9086                } catch (PackageManagerException e) {
9087                    errorCode = e.error;
9088                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
9089                }
9090            } else if (throwable instanceof PackageParser.PackageParserException) {
9091                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9092                        throwable;
9093                errorCode = e.error;
9094                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9095            } else {
9096                throw new IllegalStateException("Unexpected exception occurred while parsing "
9097                        + parseResult.scanFile, throwable);
9098            }
9099
9100            // Delete invalid userdata apps
9101            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
9102                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
9103                logCriticalInfo(Log.WARN,
9104                        "Deleting invalid package at " + parseResult.scanFile);
9105                removeCodePathLI(parseResult.scanFile);
9106            }
9107        }
9108        parallelPackageParser.close();
9109    }
9110
9111    private static File getSettingsProblemFile() {
9112        File dataDir = Environment.getDataDirectory();
9113        File systemDir = new File(dataDir, "system");
9114        File fname = new File(systemDir, "uiderrors.txt");
9115        return fname;
9116    }
9117
9118    static void reportSettingsProblem(int priority, String msg) {
9119        logCriticalInfo(priority, msg);
9120    }
9121
9122    public static void logCriticalInfo(int priority, String msg) {
9123        Slog.println(priority, TAG, msg);
9124        EventLogTags.writePmCriticalInfo(msg);
9125        try {
9126            File fname = getSettingsProblemFile();
9127            FileOutputStream out = new FileOutputStream(fname, true);
9128            PrintWriter pw = new FastPrintWriter(out);
9129            SimpleDateFormat formatter = new SimpleDateFormat();
9130            String dateString = formatter.format(new Date(System.currentTimeMillis()));
9131            pw.println(dateString + ": " + msg);
9132            pw.close();
9133            FileUtils.setPermissions(
9134                    fname.toString(),
9135                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9136                    -1, -1);
9137        } catch (java.io.IOException e) {
9138        }
9139    }
9140
9141    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9142        if (srcFile.isDirectory()) {
9143            final File baseFile = new File(pkg.baseCodePath);
9144            long maxModifiedTime = baseFile.lastModified();
9145            if (pkg.splitCodePaths != null) {
9146                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9147                    final File splitFile = new File(pkg.splitCodePaths[i]);
9148                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9149                }
9150            }
9151            return maxModifiedTime;
9152        }
9153        return srcFile.lastModified();
9154    }
9155
9156    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9157            final int policyFlags) throws PackageManagerException {
9158        // When upgrading from pre-N MR1, verify the package time stamp using the package
9159        // directory and not the APK file.
9160        final long lastModifiedTime = mIsPreNMR1Upgrade
9161                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9162        if (ps != null
9163                && ps.codePath.equals(srcFile)
9164                && ps.timeStamp == lastModifiedTime
9165                && !isCompatSignatureUpdateNeeded(pkg)
9166                && !isRecoverSignatureUpdateNeeded(pkg)) {
9167            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9168            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9169            ArraySet<PublicKey> signingKs;
9170            synchronized (mPackages) {
9171                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9172            }
9173            if (ps.signatures.mSignatures != null
9174                    && ps.signatures.mSignatures.length != 0
9175                    && signingKs != null) {
9176                // Optimization: reuse the existing cached certificates
9177                // if the package appears to be unchanged.
9178                pkg.mSignatures = ps.signatures.mSignatures;
9179                pkg.mSigningKeys = signingKs;
9180                return;
9181            }
9182
9183            Slog.w(TAG, "PackageSetting for " + ps.name
9184                    + " is missing signatures.  Collecting certs again to recover them.");
9185        } else {
9186            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9187        }
9188
9189        try {
9190            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9191            PackageParser.collectCertificates(pkg, policyFlags);
9192        } catch (PackageParserException e) {
9193            throw PackageManagerException.from(e);
9194        } finally {
9195            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9196        }
9197    }
9198
9199    /**
9200     *  Traces a package scan.
9201     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9202     */
9203    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9204            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9205        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9206        try {
9207            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9208        } finally {
9209            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9210        }
9211    }
9212
9213    /**
9214     *  Scans a package and returns the newly parsed package.
9215     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9216     */
9217    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9218            long currentTime, UserHandle user) throws PackageManagerException {
9219        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9220        PackageParser pp = new PackageParser();
9221        pp.setSeparateProcesses(mSeparateProcesses);
9222        pp.setOnlyCoreApps(mOnlyCore);
9223        pp.setDisplayMetrics(mMetrics);
9224        pp.setCallback(mPackageParserCallback);
9225
9226        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9227            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9228        }
9229
9230        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9231        final PackageParser.Package pkg;
9232        try {
9233            pkg = pp.parsePackage(scanFile, parseFlags);
9234        } catch (PackageParserException e) {
9235            throw PackageManagerException.from(e);
9236        } finally {
9237            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9238        }
9239
9240        // Static shared libraries have synthetic package names
9241        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9242            renameStaticSharedLibraryPackage(pkg);
9243        }
9244
9245        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9246    }
9247
9248    /**
9249     *  Scans a package and returns the newly parsed package.
9250     *  @throws PackageManagerException on a parse error.
9251     */
9252    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9253            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9254            throws PackageManagerException {
9255        // If the package has children and this is the first dive in the function
9256        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9257        // packages (parent and children) would be successfully scanned before the
9258        // actual scan since scanning mutates internal state and we want to atomically
9259        // install the package and its children.
9260        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9261            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9262                scanFlags |= SCAN_CHECK_ONLY;
9263            }
9264        } else {
9265            scanFlags &= ~SCAN_CHECK_ONLY;
9266        }
9267
9268        // Scan the parent
9269        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9270                scanFlags, currentTime, user);
9271
9272        // Scan the children
9273        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9274        for (int i = 0; i < childCount; i++) {
9275            PackageParser.Package childPackage = pkg.childPackages.get(i);
9276            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9277                    currentTime, user);
9278        }
9279
9280
9281        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9282            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9283        }
9284
9285        return scannedPkg;
9286    }
9287
9288    /**
9289     *  Scans a package and returns the newly parsed package.
9290     *  @throws PackageManagerException on a parse error.
9291     */
9292    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9293            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9294            throws PackageManagerException {
9295        PackageSetting ps = null;
9296        PackageSetting updatedPkg;
9297        // reader
9298        synchronized (mPackages) {
9299            // Look to see if we already know about this package.
9300            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9301            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9302                // This package has been renamed to its original name.  Let's
9303                // use that.
9304                ps = mSettings.getPackageLPr(oldName);
9305            }
9306            // If there was no original package, see one for the real package name.
9307            if (ps == null) {
9308                ps = mSettings.getPackageLPr(pkg.packageName);
9309            }
9310            // Check to see if this package could be hiding/updating a system
9311            // package.  Must look for it either under the original or real
9312            // package name depending on our state.
9313            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9314            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9315
9316            // If this is a package we don't know about on the system partition, we
9317            // may need to remove disabled child packages on the system partition
9318            // or may need to not add child packages if the parent apk is updated
9319            // on the data partition and no longer defines this child package.
9320            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9321                // If this is a parent package for an updated system app and this system
9322                // app got an OTA update which no longer defines some of the child packages
9323                // we have to prune them from the disabled system packages.
9324                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9325                if (disabledPs != null) {
9326                    final int scannedChildCount = (pkg.childPackages != null)
9327                            ? pkg.childPackages.size() : 0;
9328                    final int disabledChildCount = disabledPs.childPackageNames != null
9329                            ? disabledPs.childPackageNames.size() : 0;
9330                    for (int i = 0; i < disabledChildCount; i++) {
9331                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9332                        boolean disabledPackageAvailable = false;
9333                        for (int j = 0; j < scannedChildCount; j++) {
9334                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9335                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9336                                disabledPackageAvailable = true;
9337                                break;
9338                            }
9339                         }
9340                         if (!disabledPackageAvailable) {
9341                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9342                         }
9343                    }
9344                }
9345            }
9346        }
9347
9348        final boolean isUpdatedPkg = updatedPkg != null;
9349        final boolean isUpdatedSystemPkg = isUpdatedPkg
9350                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9351        boolean isUpdatedPkgBetter = false;
9352        // First check if this is a system package that may involve an update
9353        if (isUpdatedSystemPkg) {
9354            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9355            // it needs to drop FLAG_PRIVILEGED.
9356            if (locationIsPrivileged(scanFile)) {
9357                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9358            } else {
9359                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9360            }
9361
9362            if (ps != null && !ps.codePath.equals(scanFile)) {
9363                // The path has changed from what was last scanned...  check the
9364                // version of the new path against what we have stored to determine
9365                // what to do.
9366                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9367                if (pkg.mVersionCode <= ps.versionCode) {
9368                    // The system package has been updated and the code path does not match
9369                    // Ignore entry. Skip it.
9370                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9371                            + " ignored: updated version " + ps.versionCode
9372                            + " better than this " + pkg.mVersionCode);
9373                    if (!updatedPkg.codePath.equals(scanFile)) {
9374                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9375                                + ps.name + " changing from " + updatedPkg.codePathString
9376                                + " to " + scanFile);
9377                        updatedPkg.codePath = scanFile;
9378                        updatedPkg.codePathString = scanFile.toString();
9379                        updatedPkg.resourcePath = scanFile;
9380                        updatedPkg.resourcePathString = scanFile.toString();
9381                    }
9382                    updatedPkg.pkg = pkg;
9383                    updatedPkg.versionCode = pkg.mVersionCode;
9384
9385                    // Update the disabled system child packages to point to the package too.
9386                    final int childCount = updatedPkg.childPackageNames != null
9387                            ? updatedPkg.childPackageNames.size() : 0;
9388                    for (int i = 0; i < childCount; i++) {
9389                        String childPackageName = updatedPkg.childPackageNames.get(i);
9390                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9391                                childPackageName);
9392                        if (updatedChildPkg != null) {
9393                            updatedChildPkg.pkg = pkg;
9394                            updatedChildPkg.versionCode = pkg.mVersionCode;
9395                        }
9396                    }
9397                } else {
9398                    // The current app on the system partition is better than
9399                    // what we have updated to on the data partition; switch
9400                    // back to the system partition version.
9401                    // At this point, its safely assumed that package installation for
9402                    // apps in system partition will go through. If not there won't be a working
9403                    // version of the app
9404                    // writer
9405                    synchronized (mPackages) {
9406                        // Just remove the loaded entries from package lists.
9407                        mPackages.remove(ps.name);
9408                    }
9409
9410                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9411                            + " reverting from " + ps.codePathString
9412                            + ": new version " + pkg.mVersionCode
9413                            + " better than installed " + ps.versionCode);
9414
9415                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9416                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9417                    synchronized (mInstallLock) {
9418                        args.cleanUpResourcesLI();
9419                    }
9420                    synchronized (mPackages) {
9421                        mSettings.enableSystemPackageLPw(ps.name);
9422                    }
9423                    isUpdatedPkgBetter = true;
9424                }
9425            }
9426        }
9427
9428        String resourcePath = null;
9429        String baseResourcePath = null;
9430        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9431            if (ps != null && ps.resourcePathString != null) {
9432                resourcePath = ps.resourcePathString;
9433                baseResourcePath = ps.resourcePathString;
9434            } else {
9435                // Should not happen at all. Just log an error.
9436                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9437            }
9438        } else {
9439            resourcePath = pkg.codePath;
9440            baseResourcePath = pkg.baseCodePath;
9441        }
9442
9443        // Set application objects path explicitly.
9444        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9445        pkg.setApplicationInfoCodePath(pkg.codePath);
9446        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9447        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9448        pkg.setApplicationInfoResourcePath(resourcePath);
9449        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9450        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9451
9452        // throw an exception if we have an update to a system application, but, it's not more
9453        // recent than the package we've already scanned
9454        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9455            // Set CPU Abis to application info.
9456            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9457                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
9458                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
9459            } else {
9460                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
9461                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
9462            }
9463
9464            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9465                    + scanFile + " ignored: updated version " + ps.versionCode
9466                    + " better than this " + pkg.mVersionCode);
9467        }
9468
9469        if (isUpdatedPkg) {
9470            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9471            // initially
9472            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9473
9474            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9475            // flag set initially
9476            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9477                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9478            }
9479        }
9480
9481        // Verify certificates against what was last scanned
9482        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9483
9484        /*
9485         * A new system app appeared, but we already had a non-system one of the
9486         * same name installed earlier.
9487         */
9488        boolean shouldHideSystemApp = false;
9489        if (!isUpdatedPkg && ps != null
9490                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9491            /*
9492             * Check to make sure the signatures match first. If they don't,
9493             * wipe the installed application and its data.
9494             */
9495            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9496                    != PackageManager.SIGNATURE_MATCH) {
9497                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9498                        + " signatures don't match existing userdata copy; removing");
9499                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9500                        "scanPackageInternalLI")) {
9501                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9502                }
9503                ps = null;
9504            } else {
9505                /*
9506                 * If the newly-added system app is an older version than the
9507                 * already installed version, hide it. It will be scanned later
9508                 * and re-added like an update.
9509                 */
9510                if (pkg.mVersionCode <= ps.versionCode) {
9511                    shouldHideSystemApp = true;
9512                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9513                            + " but new version " + pkg.mVersionCode + " better than installed "
9514                            + ps.versionCode + "; hiding system");
9515                } else {
9516                    /*
9517                     * The newly found system app is a newer version that the
9518                     * one previously installed. Simply remove the
9519                     * already-installed application and replace it with our own
9520                     * while keeping the application data.
9521                     */
9522                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9523                            + " reverting from " + ps.codePathString + ": new version "
9524                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9525                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9526                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9527                    synchronized (mInstallLock) {
9528                        args.cleanUpResourcesLI();
9529                    }
9530                }
9531            }
9532        }
9533
9534        // The apk is forward locked (not public) if its code and resources
9535        // are kept in different files. (except for app in either system or
9536        // vendor path).
9537        // TODO grab this value from PackageSettings
9538        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9539            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9540                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9541            }
9542        }
9543
9544        final int userId = ((user == null) ? 0 : user.getIdentifier());
9545        if (ps != null && ps.getInstantApp(userId)) {
9546            scanFlags |= SCAN_AS_INSTANT_APP;
9547        }
9548        if (ps != null && ps.getVirtulalPreload(userId)) {
9549            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9550        }
9551
9552        // Note that we invoke the following method only if we are about to unpack an application
9553        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9554                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9555
9556        /*
9557         * If the system app should be overridden by a previously installed
9558         * data, hide the system app now and let the /data/app scan pick it up
9559         * again.
9560         */
9561        if (shouldHideSystemApp) {
9562            synchronized (mPackages) {
9563                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9564            }
9565        }
9566
9567        return scannedPkg;
9568    }
9569
9570    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9571        // Derive the new package synthetic package name
9572        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9573                + pkg.staticSharedLibVersion);
9574    }
9575
9576    private static String fixProcessName(String defProcessName,
9577            String processName) {
9578        if (processName == null) {
9579            return defProcessName;
9580        }
9581        return processName;
9582    }
9583
9584    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9585            throws PackageManagerException {
9586        if (pkgSetting.signatures.mSignatures != null) {
9587            // Already existing package. Make sure signatures match
9588            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9589                    == PackageManager.SIGNATURE_MATCH;
9590            if (!match) {
9591                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9592                        == PackageManager.SIGNATURE_MATCH;
9593            }
9594            if (!match) {
9595                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9596                        == PackageManager.SIGNATURE_MATCH;
9597            }
9598            if (!match) {
9599                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9600                        + pkg.packageName + " signatures do not match the "
9601                        + "previously installed version; ignoring!");
9602            }
9603        }
9604
9605        // Check for shared user signatures
9606        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9607            // Already existing package. Make sure signatures match
9608            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9609                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9610            if (!match) {
9611                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9612                        == PackageManager.SIGNATURE_MATCH;
9613            }
9614            if (!match) {
9615                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9616                        == PackageManager.SIGNATURE_MATCH;
9617            }
9618            if (!match) {
9619                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9620                        "Package " + pkg.packageName
9621                        + " has no signatures that match those in shared user "
9622                        + pkgSetting.sharedUser.name + "; ignoring!");
9623            }
9624        }
9625    }
9626
9627    /**
9628     * Enforces that only the system UID or root's UID can call a method exposed
9629     * via Binder.
9630     *
9631     * @param message used as message if SecurityException is thrown
9632     * @throws SecurityException if the caller is not system or root
9633     */
9634    private static final void enforceSystemOrRoot(String message) {
9635        final int uid = Binder.getCallingUid();
9636        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9637            throw new SecurityException(message);
9638        }
9639    }
9640
9641    @Override
9642    public void performFstrimIfNeeded() {
9643        enforceSystemOrRoot("Only the system can request fstrim");
9644
9645        // Before everything else, see whether we need to fstrim.
9646        try {
9647            IStorageManager sm = PackageHelper.getStorageManager();
9648            if (sm != null) {
9649                boolean doTrim = false;
9650                final long interval = android.provider.Settings.Global.getLong(
9651                        mContext.getContentResolver(),
9652                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9653                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9654                if (interval > 0) {
9655                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9656                    if (timeSinceLast > interval) {
9657                        doTrim = true;
9658                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9659                                + "; running immediately");
9660                    }
9661                }
9662                if (doTrim) {
9663                    final boolean dexOptDialogShown;
9664                    synchronized (mPackages) {
9665                        dexOptDialogShown = mDexOptDialogShown;
9666                    }
9667                    if (!isFirstBoot() && dexOptDialogShown) {
9668                        try {
9669                            ActivityManager.getService().showBootMessage(
9670                                    mContext.getResources().getString(
9671                                            R.string.android_upgrading_fstrim), true);
9672                        } catch (RemoteException e) {
9673                        }
9674                    }
9675                    sm.runMaintenance();
9676                }
9677            } else {
9678                Slog.e(TAG, "storageManager service unavailable!");
9679            }
9680        } catch (RemoteException e) {
9681            // Can't happen; StorageManagerService is local
9682        }
9683    }
9684
9685    @Override
9686    public void updatePackagesIfNeeded() {
9687        enforceSystemOrRoot("Only the system can request package update");
9688
9689        // We need to re-extract after an OTA.
9690        boolean causeUpgrade = isUpgrade();
9691
9692        // First boot or factory reset.
9693        // Note: we also handle devices that are upgrading to N right now as if it is their
9694        //       first boot, as they do not have profile data.
9695        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9696
9697        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9698        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9699
9700        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9701            return;
9702        }
9703
9704        List<PackageParser.Package> pkgs;
9705        synchronized (mPackages) {
9706            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9707        }
9708
9709        final long startTime = System.nanoTime();
9710        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9711                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9712                    false /* bootComplete */);
9713
9714        final int elapsedTimeSeconds =
9715                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9716
9717        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9718        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9719        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9720        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9721        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9722    }
9723
9724    /*
9725     * Return the prebuilt profile path given a package base code path.
9726     */
9727    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9728        return pkg.baseCodePath + ".prof";
9729    }
9730
9731    /**
9732     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9733     * containing statistics about the invocation. The array consists of three elements,
9734     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9735     * and {@code numberOfPackagesFailed}.
9736     */
9737    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9738            final String compilerFilter, boolean bootComplete) {
9739
9740        int numberOfPackagesVisited = 0;
9741        int numberOfPackagesOptimized = 0;
9742        int numberOfPackagesSkipped = 0;
9743        int numberOfPackagesFailed = 0;
9744        final int numberOfPackagesToDexopt = pkgs.size();
9745
9746        for (PackageParser.Package pkg : pkgs) {
9747            numberOfPackagesVisited++;
9748
9749            boolean useProfileForDexopt = false;
9750
9751            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9752                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9753                // that are already compiled.
9754                File profileFile = new File(getPrebuildProfilePath(pkg));
9755                // Copy profile if it exists.
9756                if (profileFile.exists()) {
9757                    try {
9758                        // We could also do this lazily before calling dexopt in
9759                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9760                        // is that we don't have a good way to say "do this only once".
9761                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9762                                pkg.applicationInfo.uid, pkg.packageName)) {
9763                            Log.e(TAG, "Installer failed to copy system profile!");
9764                        } else {
9765                            // Disabled as this causes speed-profile compilation during first boot
9766                            // even if things are already compiled.
9767                            // useProfileForDexopt = true;
9768                        }
9769                    } catch (Exception e) {
9770                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9771                                e);
9772                    }
9773                } else {
9774                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9775                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9776                    // minimize the number off apps being speed-profile compiled during first boot.
9777                    // The other paths will not change the filter.
9778                    if (disabledPs != null && disabledPs.pkg.isStub) {
9779                        // The package is the stub one, remove the stub suffix to get the normal
9780                        // package and APK names.
9781                        String systemProfilePath =
9782                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9783                        profileFile = new File(systemProfilePath);
9784                        // If we have a profile for a compressed APK, copy it to the reference
9785                        // location.
9786                        // Note that copying the profile here will cause it to override the
9787                        // reference profile every OTA even though the existing reference profile
9788                        // may have more data. We can't copy during decompression since the
9789                        // directories are not set up at that point.
9790                        if (profileFile.exists()) {
9791                            try {
9792                                // We could also do this lazily before calling dexopt in
9793                                // PackageDexOptimizer to prevent this happening on first boot. The
9794                                // issue is that we don't have a good way to say "do this only
9795                                // once".
9796                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9797                                        pkg.applicationInfo.uid, pkg.packageName)) {
9798                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9799                                } else {
9800                                    useProfileForDexopt = true;
9801                                }
9802                            } catch (Exception e) {
9803                                Log.e(TAG, "Failed to copy profile " +
9804                                        profileFile.getAbsolutePath() + " ", e);
9805                            }
9806                        }
9807                    }
9808                }
9809            }
9810
9811            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9812                if (DEBUG_DEXOPT) {
9813                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9814                }
9815                numberOfPackagesSkipped++;
9816                continue;
9817            }
9818
9819            if (DEBUG_DEXOPT) {
9820                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9821                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9822            }
9823
9824            if (showDialog) {
9825                try {
9826                    ActivityManager.getService().showBootMessage(
9827                            mContext.getResources().getString(R.string.android_upgrading_apk,
9828                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9829                } catch (RemoteException e) {
9830                }
9831                synchronized (mPackages) {
9832                    mDexOptDialogShown = true;
9833                }
9834            }
9835
9836            String pkgCompilerFilter = compilerFilter;
9837            if (useProfileForDexopt) {
9838                // Use background dexopt mode to try and use the profile. Note that this does not
9839                // guarantee usage of the profile.
9840                pkgCompilerFilter =
9841                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9842                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
9843            }
9844
9845            // checkProfiles is false to avoid merging profiles during boot which
9846            // might interfere with background compilation (b/28612421).
9847            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9848            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9849            // trade-off worth doing to save boot time work.
9850            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9851            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9852                    pkg.packageName,
9853                    pkgCompilerFilter,
9854                    dexoptFlags));
9855
9856            switch (primaryDexOptStaus) {
9857                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9858                    numberOfPackagesOptimized++;
9859                    break;
9860                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9861                    numberOfPackagesSkipped++;
9862                    break;
9863                case PackageDexOptimizer.DEX_OPT_FAILED:
9864                    numberOfPackagesFailed++;
9865                    break;
9866                default:
9867                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9868                    break;
9869            }
9870        }
9871
9872        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9873                numberOfPackagesFailed };
9874    }
9875
9876    @Override
9877    public void notifyPackageUse(String packageName, int reason) {
9878        synchronized (mPackages) {
9879            final int callingUid = Binder.getCallingUid();
9880            final int callingUserId = UserHandle.getUserId(callingUid);
9881            if (getInstantAppPackageName(callingUid) != null) {
9882                if (!isCallerSameApp(packageName, callingUid)) {
9883                    return;
9884                }
9885            } else {
9886                if (isInstantApp(packageName, callingUserId)) {
9887                    return;
9888                }
9889            }
9890            notifyPackageUseLocked(packageName, reason);
9891        }
9892    }
9893
9894    private void notifyPackageUseLocked(String packageName, int reason) {
9895        final PackageParser.Package p = mPackages.get(packageName);
9896        if (p == null) {
9897            return;
9898        }
9899        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9900    }
9901
9902    @Override
9903    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9904            List<String> classPaths, String loaderIsa) {
9905        int userId = UserHandle.getCallingUserId();
9906        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9907        if (ai == null) {
9908            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9909                + loadingPackageName + ", user=" + userId);
9910            return;
9911        }
9912        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9913    }
9914
9915    @Override
9916    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9917            IDexModuleRegisterCallback callback) {
9918        int userId = UserHandle.getCallingUserId();
9919        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9920        DexManager.RegisterDexModuleResult result;
9921        if (ai == null) {
9922            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9923                     " calling user. package=" + packageName + ", user=" + userId);
9924            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9925        } else {
9926            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9927        }
9928
9929        if (callback != null) {
9930            mHandler.post(() -> {
9931                try {
9932                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9933                } catch (RemoteException e) {
9934                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9935                }
9936            });
9937        }
9938    }
9939
9940    /**
9941     * Ask the package manager to perform a dex-opt with the given compiler filter.
9942     *
9943     * Note: exposed only for the shell command to allow moving packages explicitly to a
9944     *       definite state.
9945     */
9946    @Override
9947    public boolean performDexOptMode(String packageName,
9948            boolean checkProfiles, String targetCompilerFilter, boolean force,
9949            boolean bootComplete, String splitName) {
9950        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9951                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9952                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9953        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9954                splitName, flags));
9955    }
9956
9957    /**
9958     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9959     * secondary dex files belonging to the given package.
9960     *
9961     * Note: exposed only for the shell command to allow moving packages explicitly to a
9962     *       definite state.
9963     */
9964    @Override
9965    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9966            boolean force) {
9967        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9968                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9969                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9970                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9971        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9972    }
9973
9974    /*package*/ boolean performDexOpt(DexoptOptions options) {
9975        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9976            return false;
9977        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9978            return false;
9979        }
9980
9981        if (options.isDexoptOnlySecondaryDex()) {
9982            return mDexManager.dexoptSecondaryDex(options);
9983        } else {
9984            int dexoptStatus = performDexOptWithStatus(options);
9985            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9986        }
9987    }
9988
9989    /**
9990     * Perform dexopt on the given package and return one of following result:
9991     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9992     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9993     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9994     */
9995    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9996        return performDexOptTraced(options);
9997    }
9998
9999    private int performDexOptTraced(DexoptOptions options) {
10000        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10001        try {
10002            return performDexOptInternal(options);
10003        } finally {
10004            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10005        }
10006    }
10007
10008    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
10009    // if the package can now be considered up to date for the given filter.
10010    private int performDexOptInternal(DexoptOptions options) {
10011        PackageParser.Package p;
10012        synchronized (mPackages) {
10013            p = mPackages.get(options.getPackageName());
10014            if (p == null) {
10015                // Package could not be found. Report failure.
10016                return PackageDexOptimizer.DEX_OPT_FAILED;
10017            }
10018            mPackageUsage.maybeWriteAsync(mPackages);
10019            mCompilerStats.maybeWriteAsync();
10020        }
10021        long callingId = Binder.clearCallingIdentity();
10022        try {
10023            synchronized (mInstallLock) {
10024                return performDexOptInternalWithDependenciesLI(p, options);
10025            }
10026        } finally {
10027            Binder.restoreCallingIdentity(callingId);
10028        }
10029    }
10030
10031    public ArraySet<String> getOptimizablePackages() {
10032        ArraySet<String> pkgs = new ArraySet<String>();
10033        synchronized (mPackages) {
10034            for (PackageParser.Package p : mPackages.values()) {
10035                if (PackageDexOptimizer.canOptimizePackage(p)) {
10036                    pkgs.add(p.packageName);
10037                }
10038            }
10039        }
10040        return pkgs;
10041    }
10042
10043    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
10044            DexoptOptions options) {
10045        // Select the dex optimizer based on the force parameter.
10046        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
10047        //       allocate an object here.
10048        PackageDexOptimizer pdo = options.isForce()
10049                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
10050                : mPackageDexOptimizer;
10051
10052        // Dexopt all dependencies first. Note: we ignore the return value and march on
10053        // on errors.
10054        // Note that we are going to call performDexOpt on those libraries as many times as
10055        // they are referenced in packages. When we do a batch of performDexOpt (for example
10056        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
10057        // and the first package that uses the library will dexopt it. The
10058        // others will see that the compiled code for the library is up to date.
10059        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
10060        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
10061        if (!deps.isEmpty()) {
10062            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
10063                    options.getCompilerFilter(), options.getSplitName(),
10064                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
10065            for (PackageParser.Package depPackage : deps) {
10066                // TODO: Analyze and investigate if we (should) profile libraries.
10067                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
10068                        getOrCreateCompilerPackageStats(depPackage),
10069                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
10070            }
10071        }
10072        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
10073                getOrCreateCompilerPackageStats(p),
10074                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
10075    }
10076
10077    /**
10078     * Reconcile the information we have about the secondary dex files belonging to
10079     * {@code packagName} and the actual dex files. For all dex files that were
10080     * deleted, update the internal records and delete the generated oat files.
10081     */
10082    @Override
10083    public void reconcileSecondaryDexFiles(String packageName) {
10084        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10085            return;
10086        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
10087            return;
10088        }
10089        mDexManager.reconcileSecondaryDexFiles(packageName);
10090    }
10091
10092    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
10093    // a reference there.
10094    /*package*/ DexManager getDexManager() {
10095        return mDexManager;
10096    }
10097
10098    /**
10099     * Execute the background dexopt job immediately.
10100     */
10101    @Override
10102    public boolean runBackgroundDexoptJob() {
10103        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10104            return false;
10105        }
10106        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
10107    }
10108
10109    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
10110        if (p.usesLibraries != null || p.usesOptionalLibraries != null
10111                || p.usesStaticLibraries != null) {
10112            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
10113            Set<String> collectedNames = new HashSet<>();
10114            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
10115
10116            retValue.remove(p);
10117
10118            return retValue;
10119        } else {
10120            return Collections.emptyList();
10121        }
10122    }
10123
10124    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
10125            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10126        if (!collectedNames.contains(p.packageName)) {
10127            collectedNames.add(p.packageName);
10128            collected.add(p);
10129
10130            if (p.usesLibraries != null) {
10131                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10132                        null, collected, collectedNames);
10133            }
10134            if (p.usesOptionalLibraries != null) {
10135                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10136                        null, collected, collectedNames);
10137            }
10138            if (p.usesStaticLibraries != null) {
10139                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10140                        p.usesStaticLibrariesVersions, collected, collectedNames);
10141            }
10142        }
10143    }
10144
10145    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10146            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10147        final int libNameCount = libs.size();
10148        for (int i = 0; i < libNameCount; i++) {
10149            String libName = libs.get(i);
10150            int version = (versions != null && versions.length == libNameCount)
10151                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10152            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10153            if (libPkg != null) {
10154                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10155            }
10156        }
10157    }
10158
10159    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10160        synchronized (mPackages) {
10161            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10162            if (libEntry != null) {
10163                return mPackages.get(libEntry.apk);
10164            }
10165            return null;
10166        }
10167    }
10168
10169    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10170        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10171        if (versionedLib == null) {
10172            return null;
10173        }
10174        return versionedLib.get(version);
10175    }
10176
10177    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10178        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10179                pkg.staticSharedLibName);
10180        if (versionedLib == null) {
10181            return null;
10182        }
10183        int previousLibVersion = -1;
10184        final int versionCount = versionedLib.size();
10185        for (int i = 0; i < versionCount; i++) {
10186            final int libVersion = versionedLib.keyAt(i);
10187            if (libVersion < pkg.staticSharedLibVersion) {
10188                previousLibVersion = Math.max(previousLibVersion, libVersion);
10189            }
10190        }
10191        if (previousLibVersion >= 0) {
10192            return versionedLib.get(previousLibVersion);
10193        }
10194        return null;
10195    }
10196
10197    public void shutdown() {
10198        mPackageUsage.writeNow(mPackages);
10199        mCompilerStats.writeNow();
10200        mDexManager.writePackageDexUsageNow();
10201    }
10202
10203    @Override
10204    public void dumpProfiles(String packageName) {
10205        PackageParser.Package pkg;
10206        synchronized (mPackages) {
10207            pkg = mPackages.get(packageName);
10208            if (pkg == null) {
10209                throw new IllegalArgumentException("Unknown package: " + packageName);
10210            }
10211        }
10212        /* Only the shell, root, or the app user should be able to dump profiles. */
10213        int callingUid = Binder.getCallingUid();
10214        if (callingUid != Process.SHELL_UID &&
10215            callingUid != Process.ROOT_UID &&
10216            callingUid != pkg.applicationInfo.uid) {
10217            throw new SecurityException("dumpProfiles");
10218        }
10219
10220        synchronized (mInstallLock) {
10221            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10222            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10223            try {
10224                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10225                String codePaths = TextUtils.join(";", allCodePaths);
10226                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10227            } catch (InstallerException e) {
10228                Slog.w(TAG, "Failed to dump profiles", e);
10229            }
10230            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10231        }
10232    }
10233
10234    @Override
10235    public void forceDexOpt(String packageName) {
10236        enforceSystemOrRoot("forceDexOpt");
10237
10238        PackageParser.Package pkg;
10239        synchronized (mPackages) {
10240            pkg = mPackages.get(packageName);
10241            if (pkg == null) {
10242                throw new IllegalArgumentException("Unknown package: " + packageName);
10243            }
10244        }
10245
10246        synchronized (mInstallLock) {
10247            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10248
10249            // Whoever is calling forceDexOpt wants a compiled package.
10250            // Don't use profiles since that may cause compilation to be skipped.
10251            final int res = performDexOptInternalWithDependenciesLI(
10252                    pkg,
10253                    new DexoptOptions(packageName,
10254                            getDefaultCompilerFilter(),
10255                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10256
10257            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10258            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10259                throw new IllegalStateException("Failed to dexopt: " + res);
10260            }
10261        }
10262    }
10263
10264    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10265        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10266            Slog.w(TAG, "Unable to update from " + oldPkg.name
10267                    + " to " + newPkg.packageName
10268                    + ": old package not in system partition");
10269            return false;
10270        } else if (mPackages.get(oldPkg.name) != null) {
10271            Slog.w(TAG, "Unable to update from " + oldPkg.name
10272                    + " to " + newPkg.packageName
10273                    + ": old package still exists");
10274            return false;
10275        }
10276        return true;
10277    }
10278
10279    void removeCodePathLI(File codePath) {
10280        if (codePath.isDirectory()) {
10281            try {
10282                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10283            } catch (InstallerException e) {
10284                Slog.w(TAG, "Failed to remove code path", e);
10285            }
10286        } else {
10287            codePath.delete();
10288        }
10289    }
10290
10291    private int[] resolveUserIds(int userId) {
10292        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10293    }
10294
10295    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10296        if (pkg == null) {
10297            Slog.wtf(TAG, "Package was null!", new Throwable());
10298            return;
10299        }
10300        clearAppDataLeafLIF(pkg, userId, flags);
10301        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10302        for (int i = 0; i < childCount; i++) {
10303            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10304        }
10305    }
10306
10307    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10308        final PackageSetting ps;
10309        synchronized (mPackages) {
10310            ps = mSettings.mPackages.get(pkg.packageName);
10311        }
10312        for (int realUserId : resolveUserIds(userId)) {
10313            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10314            try {
10315                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10316                        ceDataInode);
10317            } catch (InstallerException e) {
10318                Slog.w(TAG, String.valueOf(e));
10319            }
10320        }
10321    }
10322
10323    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10324        if (pkg == null) {
10325            Slog.wtf(TAG, "Package was null!", new Throwable());
10326            return;
10327        }
10328        destroyAppDataLeafLIF(pkg, userId, flags);
10329        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10330        for (int i = 0; i < childCount; i++) {
10331            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10332        }
10333    }
10334
10335    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10336        final PackageSetting ps;
10337        synchronized (mPackages) {
10338            ps = mSettings.mPackages.get(pkg.packageName);
10339        }
10340        for (int realUserId : resolveUserIds(userId)) {
10341            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10342            try {
10343                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10344                        ceDataInode);
10345            } catch (InstallerException e) {
10346                Slog.w(TAG, String.valueOf(e));
10347            }
10348            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10349        }
10350    }
10351
10352    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10353        if (pkg == null) {
10354            Slog.wtf(TAG, "Package was null!", new Throwable());
10355            return;
10356        }
10357        destroyAppProfilesLeafLIF(pkg);
10358        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10359        for (int i = 0; i < childCount; i++) {
10360            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10361        }
10362    }
10363
10364    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10365        try {
10366            mInstaller.destroyAppProfiles(pkg.packageName);
10367        } catch (InstallerException e) {
10368            Slog.w(TAG, String.valueOf(e));
10369        }
10370    }
10371
10372    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10373        if (pkg == null) {
10374            Slog.wtf(TAG, "Package was null!", new Throwable());
10375            return;
10376        }
10377        clearAppProfilesLeafLIF(pkg);
10378        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10379        for (int i = 0; i < childCount; i++) {
10380            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10381        }
10382    }
10383
10384    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10385        try {
10386            mInstaller.clearAppProfiles(pkg.packageName);
10387        } catch (InstallerException e) {
10388            Slog.w(TAG, String.valueOf(e));
10389        }
10390    }
10391
10392    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10393            long lastUpdateTime) {
10394        // Set parent install/update time
10395        PackageSetting ps = (PackageSetting) pkg.mExtras;
10396        if (ps != null) {
10397            ps.firstInstallTime = firstInstallTime;
10398            ps.lastUpdateTime = lastUpdateTime;
10399        }
10400        // Set children install/update time
10401        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10402        for (int i = 0; i < childCount; i++) {
10403            PackageParser.Package childPkg = pkg.childPackages.get(i);
10404            ps = (PackageSetting) childPkg.mExtras;
10405            if (ps != null) {
10406                ps.firstInstallTime = firstInstallTime;
10407                ps.lastUpdateTime = lastUpdateTime;
10408            }
10409        }
10410    }
10411
10412    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
10413            SharedLibraryEntry file,
10414            PackageParser.Package changingLib) {
10415        if (file.path != null) {
10416            usesLibraryFiles.add(file.path);
10417            return;
10418        }
10419        PackageParser.Package p = mPackages.get(file.apk);
10420        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10421            // If we are doing this while in the middle of updating a library apk,
10422            // then we need to make sure to use that new apk for determining the
10423            // dependencies here.  (We haven't yet finished committing the new apk
10424            // to the package manager state.)
10425            if (p == null || p.packageName.equals(changingLib.packageName)) {
10426                p = changingLib;
10427            }
10428        }
10429        if (p != null) {
10430            usesLibraryFiles.addAll(p.getAllCodePaths());
10431            if (p.usesLibraryFiles != null) {
10432                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10433            }
10434        }
10435    }
10436
10437    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10438            PackageParser.Package changingLib) throws PackageManagerException {
10439        if (pkg == null) {
10440            return;
10441        }
10442        // The collection used here must maintain the order of addition (so
10443        // that libraries are searched in the correct order) and must have no
10444        // duplicates.
10445        Set<String> usesLibraryFiles = null;
10446        if (pkg.usesLibraries != null) {
10447            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10448                    null, null, pkg.packageName, changingLib, true,
10449                    pkg.applicationInfo.targetSdkVersion, null);
10450        }
10451        if (pkg.usesStaticLibraries != null) {
10452            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10453                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10454                    pkg.packageName, changingLib, true,
10455                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10456        }
10457        if (pkg.usesOptionalLibraries != null) {
10458            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10459                    null, null, pkg.packageName, changingLib, false,
10460                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10461        }
10462        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10463            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10464        } else {
10465            pkg.usesLibraryFiles = null;
10466        }
10467    }
10468
10469    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10470            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
10471            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10472            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
10473            throws PackageManagerException {
10474        final int libCount = requestedLibraries.size();
10475        for (int i = 0; i < libCount; i++) {
10476            final String libName = requestedLibraries.get(i);
10477            final int libVersion = requiredVersions != null ? requiredVersions[i]
10478                    : SharedLibraryInfo.VERSION_UNDEFINED;
10479            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10480            if (libEntry == null) {
10481                if (required) {
10482                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10483                            "Package " + packageName + " requires unavailable shared library "
10484                                    + libName + "; failing!");
10485                } else if (DEBUG_SHARED_LIBRARIES) {
10486                    Slog.i(TAG, "Package " + packageName
10487                            + " desires unavailable shared library "
10488                            + libName + "; ignoring!");
10489                }
10490            } else {
10491                if (requiredVersions != null && requiredCertDigests != null) {
10492                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10493                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10494                            "Package " + packageName + " requires unavailable static shared"
10495                                    + " library " + libName + " version "
10496                                    + libEntry.info.getVersion() + "; failing!");
10497                    }
10498
10499                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10500                    if (libPkg == null) {
10501                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10502                                "Package " + packageName + " requires unavailable static shared"
10503                                        + " library; failing!");
10504                    }
10505
10506                    final String[] expectedCertDigests = requiredCertDigests[i];
10507                    // For apps targeting O MR1 we require explicit enumeration of all certs.
10508                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
10509                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
10510                            : PackageUtils.computeSignaturesSha256Digests(
10511                                    new Signature[]{libPkg.mSignatures[0]});
10512
10513                    // Take a shortcut if sizes don't match. Note that if an app doesn't
10514                    // target O we don't parse the "additional-certificate" tags similarly
10515                    // how we only consider all certs only for apps targeting O (see above).
10516                    // Therefore, the size check is safe to make.
10517                    if (expectedCertDigests.length != libCertDigests.length) {
10518                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10519                                "Package " + packageName + " requires differently signed" +
10520                                        " static sDexLoadReporter.java:45.19hared library; failing!");
10521                    }
10522
10523                    // Use a predictable order as signature order may vary
10524                    Arrays.sort(libCertDigests);
10525                    Arrays.sort(expectedCertDigests);
10526
10527                    final int certCount = libCertDigests.length;
10528                    for (int j = 0; j < certCount; j++) {
10529                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
10530                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10531                                    "Package " + packageName + " requires differently signed" +
10532                                            " static shared library; failing!");
10533                        }
10534                    }
10535                }
10536
10537                if (outUsedLibraries == null) {
10538                    // Use LinkedHashSet to preserve the order of files added to
10539                    // usesLibraryFiles while eliminating duplicates.
10540                    outUsedLibraries = new LinkedHashSet<>();
10541                }
10542                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10543            }
10544        }
10545        return outUsedLibraries;
10546    }
10547
10548    private static boolean hasString(List<String> list, List<String> which) {
10549        if (list == null) {
10550            return false;
10551        }
10552        for (int i=list.size()-1; i>=0; i--) {
10553            for (int j=which.size()-1; j>=0; j--) {
10554                if (which.get(j).equals(list.get(i))) {
10555                    return true;
10556                }
10557            }
10558        }
10559        return false;
10560    }
10561
10562    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10563            PackageParser.Package changingPkg) {
10564        ArrayList<PackageParser.Package> res = null;
10565        for (PackageParser.Package pkg : mPackages.values()) {
10566            if (changingPkg != null
10567                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10568                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10569                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10570                            changingPkg.staticSharedLibName)) {
10571                return null;
10572            }
10573            if (res == null) {
10574                res = new ArrayList<>();
10575            }
10576            res.add(pkg);
10577            try {
10578                updateSharedLibrariesLPr(pkg, changingPkg);
10579            } catch (PackageManagerException e) {
10580                // If a system app update or an app and a required lib missing we
10581                // delete the package and for updated system apps keep the data as
10582                // it is better for the user to reinstall than to be in an limbo
10583                // state. Also libs disappearing under an app should never happen
10584                // - just in case.
10585                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10586                    final int flags = pkg.isUpdatedSystemApp()
10587                            ? PackageManager.DELETE_KEEP_DATA : 0;
10588                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10589                            flags , null, true, null);
10590                }
10591                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10592            }
10593        }
10594        return res;
10595    }
10596
10597    /**
10598     * Derive the value of the {@code cpuAbiOverride} based on the provided
10599     * value and an optional stored value from the package settings.
10600     */
10601    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10602        String cpuAbiOverride = null;
10603
10604        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10605            cpuAbiOverride = null;
10606        } else if (abiOverride != null) {
10607            cpuAbiOverride = abiOverride;
10608        } else if (settings != null) {
10609            cpuAbiOverride = settings.cpuAbiOverrideString;
10610        }
10611
10612        return cpuAbiOverride;
10613    }
10614
10615    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10616            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10617                    throws PackageManagerException {
10618        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10619        // If the package has children and this is the first dive in the function
10620        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10621        // whether all packages (parent and children) would be successfully scanned
10622        // before the actual scan since scanning mutates internal state and we want
10623        // to atomically install the package and its children.
10624        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10625            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10626                scanFlags |= SCAN_CHECK_ONLY;
10627            }
10628        } else {
10629            scanFlags &= ~SCAN_CHECK_ONLY;
10630        }
10631
10632        final PackageParser.Package scannedPkg;
10633        try {
10634            // Scan the parent
10635            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10636            // Scan the children
10637            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10638            for (int i = 0; i < childCount; i++) {
10639                PackageParser.Package childPkg = pkg.childPackages.get(i);
10640                scanPackageLI(childPkg, policyFlags,
10641                        scanFlags, currentTime, user);
10642            }
10643        } finally {
10644            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10645        }
10646
10647        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10648            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10649        }
10650
10651        return scannedPkg;
10652    }
10653
10654    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10655            int scanFlags, long currentTime, @Nullable UserHandle user)
10656                    throws PackageManagerException {
10657        boolean success = false;
10658        try {
10659            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10660                    currentTime, user);
10661            success = true;
10662            return res;
10663        } finally {
10664            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10665                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10666                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10667                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10668                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10669            }
10670        }
10671    }
10672
10673    /**
10674     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10675     */
10676    private static boolean apkHasCode(String fileName) {
10677        StrictJarFile jarFile = null;
10678        try {
10679            jarFile = new StrictJarFile(fileName,
10680                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10681            return jarFile.findEntry("classes.dex") != null;
10682        } catch (IOException ignore) {
10683        } finally {
10684            try {
10685                if (jarFile != null) {
10686                    jarFile.close();
10687                }
10688            } catch (IOException ignore) {}
10689        }
10690        return false;
10691    }
10692
10693    /**
10694     * Enforces code policy for the package. This ensures that if an APK has
10695     * declared hasCode="true" in its manifest that the APK actually contains
10696     * code.
10697     *
10698     * @throws PackageManagerException If bytecode could not be found when it should exist
10699     */
10700    private static void assertCodePolicy(PackageParser.Package pkg)
10701            throws PackageManagerException {
10702        final boolean shouldHaveCode =
10703                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10704        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10705            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10706                    "Package " + pkg.baseCodePath + " code is missing");
10707        }
10708
10709        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10710            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10711                final boolean splitShouldHaveCode =
10712                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10713                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10714                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10715                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10716                }
10717            }
10718        }
10719    }
10720
10721    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10722            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10723                    throws PackageManagerException {
10724        if (DEBUG_PACKAGE_SCANNING) {
10725            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10726                Log.d(TAG, "Scanning package " + pkg.packageName);
10727        }
10728
10729        applyPolicy(pkg, policyFlags);
10730
10731        assertPackageIsValid(pkg, policyFlags, scanFlags);
10732
10733        if (Build.IS_DEBUGGABLE &&
10734                pkg.isPrivilegedApp() &&
10735                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10736            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10737        }
10738
10739        // Initialize package source and resource directories
10740        final File scanFile = new File(pkg.codePath);
10741        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10742        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10743
10744        SharedUserSetting suid = null;
10745        PackageSetting pkgSetting = null;
10746
10747        // Getting the package setting may have a side-effect, so if we
10748        // are only checking if scan would succeed, stash a copy of the
10749        // old setting to restore at the end.
10750        PackageSetting nonMutatedPs = null;
10751
10752        // We keep references to the derived CPU Abis from settings in oder to reuse
10753        // them in the case where we're not upgrading or booting for the first time.
10754        String primaryCpuAbiFromSettings = null;
10755        String secondaryCpuAbiFromSettings = null;
10756        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10757
10758        // writer
10759        synchronized (mPackages) {
10760            if (pkg.mSharedUserId != null) {
10761                // SIDE EFFECTS; may potentially allocate a new shared user
10762                suid = mSettings.getSharedUserLPw(
10763                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10764                if (DEBUG_PACKAGE_SCANNING) {
10765                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10766                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10767                                + "): packages=" + suid.packages);
10768                }
10769            }
10770
10771            // Check if we are renaming from an original package name.
10772            PackageSetting origPackage = null;
10773            String realName = null;
10774            if (pkg.mOriginalPackages != null) {
10775                // This package may need to be renamed to a previously
10776                // installed name.  Let's check on that...
10777                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10778                if (pkg.mOriginalPackages.contains(renamed)) {
10779                    // This package had originally been installed as the
10780                    // original name, and we have already taken care of
10781                    // transitioning to the new one.  Just update the new
10782                    // one to continue using the old name.
10783                    realName = pkg.mRealPackage;
10784                    if (!pkg.packageName.equals(renamed)) {
10785                        // Callers into this function may have already taken
10786                        // care of renaming the package; only do it here if
10787                        // it is not already done.
10788                        pkg.setPackageName(renamed);
10789                    }
10790                } else {
10791                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10792                        if ((origPackage = mSettings.getPackageLPr(
10793                                pkg.mOriginalPackages.get(i))) != null) {
10794                            // We do have the package already installed under its
10795                            // original name...  should we use it?
10796                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10797                                // New package is not compatible with original.
10798                                origPackage = null;
10799                                continue;
10800                            } else if (origPackage.sharedUser != null) {
10801                                // Make sure uid is compatible between packages.
10802                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10803                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10804                                            + " to " + pkg.packageName + ": old uid "
10805                                            + origPackage.sharedUser.name
10806                                            + " differs from " + pkg.mSharedUserId);
10807                                    origPackage = null;
10808                                    continue;
10809                                }
10810                                // TODO: Add case when shared user id is added [b/28144775]
10811                            } else {
10812                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10813                                        + pkg.packageName + " to old name " + origPackage.name);
10814                            }
10815                            break;
10816                        }
10817                    }
10818                }
10819            }
10820
10821            if (mTransferedPackages.contains(pkg.packageName)) {
10822                Slog.w(TAG, "Package " + pkg.packageName
10823                        + " was transferred to another, but its .apk remains");
10824            }
10825
10826            // See comments in nonMutatedPs declaration
10827            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10828                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10829                if (foundPs != null) {
10830                    nonMutatedPs = new PackageSetting(foundPs);
10831                }
10832            }
10833
10834            if (!needToDeriveAbi) {
10835                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10836                if (foundPs != null) {
10837                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10838                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10839                } else {
10840                    // when re-adding a system package failed after uninstalling updates.
10841                    needToDeriveAbi = true;
10842                }
10843            }
10844
10845            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10846            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10847                PackageManagerService.reportSettingsProblem(Log.WARN,
10848                        "Package " + pkg.packageName + " shared user changed from "
10849                                + (pkgSetting.sharedUser != null
10850                                        ? pkgSetting.sharedUser.name : "<nothing>")
10851                                + " to "
10852                                + (suid != null ? suid.name : "<nothing>")
10853                                + "; replacing with new");
10854                pkgSetting = null;
10855            }
10856            final PackageSetting oldPkgSetting =
10857                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10858            final PackageSetting disabledPkgSetting =
10859                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10860
10861            String[] usesStaticLibraries = null;
10862            if (pkg.usesStaticLibraries != null) {
10863                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10864                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10865            }
10866
10867            if (pkgSetting == null) {
10868                final String parentPackageName = (pkg.parentPackage != null)
10869                        ? pkg.parentPackage.packageName : null;
10870                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10871                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10872                // REMOVE SharedUserSetting from method; update in a separate call
10873                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10874                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10875                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10876                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10877                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10878                        true /*allowInstall*/, instantApp, virtualPreload,
10879                        parentPackageName, pkg.getChildPackageNames(),
10880                        UserManagerService.getInstance(), usesStaticLibraries,
10881                        pkg.usesStaticLibrariesVersions);
10882                // SIDE EFFECTS; updates system state; move elsewhere
10883                if (origPackage != null) {
10884                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10885                }
10886                mSettings.addUserToSettingLPw(pkgSetting);
10887            } else {
10888                // REMOVE SharedUserSetting from method; update in a separate call.
10889                //
10890                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10891                // secondaryCpuAbi are not known at this point so we always update them
10892                // to null here, only to reset them at a later point.
10893                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10894                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10895                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10896                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10897                        UserManagerService.getInstance(), usesStaticLibraries,
10898                        pkg.usesStaticLibrariesVersions);
10899            }
10900            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10901            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10902
10903            // SIDE EFFECTS; modifies system state; move elsewhere
10904            if (pkgSetting.origPackage != null) {
10905                // If we are first transitioning from an original package,
10906                // fix up the new package's name now.  We need to do this after
10907                // looking up the package under its new name, so getPackageLP
10908                // can take care of fiddling things correctly.
10909                pkg.setPackageName(origPackage.name);
10910
10911                // File a report about this.
10912                String msg = "New package " + pkgSetting.realName
10913                        + " renamed to replace old package " + pkgSetting.name;
10914                reportSettingsProblem(Log.WARN, msg);
10915
10916                // Make a note of it.
10917                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10918                    mTransferedPackages.add(origPackage.name);
10919                }
10920
10921                // No longer need to retain this.
10922                pkgSetting.origPackage = null;
10923            }
10924
10925            // SIDE EFFECTS; modifies system state; move elsewhere
10926            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10927                // Make a note of it.
10928                mTransferedPackages.add(pkg.packageName);
10929            }
10930
10931            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10932                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10933            }
10934
10935            if ((scanFlags & SCAN_BOOTING) == 0
10936                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10937                // Check all shared libraries and map to their actual file path.
10938                // We only do this here for apps not on a system dir, because those
10939                // are the only ones that can fail an install due to this.  We
10940                // will take care of the system apps by updating all of their
10941                // library paths after the scan is done. Also during the initial
10942                // scan don't update any libs as we do this wholesale after all
10943                // apps are scanned to avoid dependency based scanning.
10944                updateSharedLibrariesLPr(pkg, null);
10945            }
10946
10947            if (mFoundPolicyFile) {
10948                SELinuxMMAC.assignSeInfoValue(pkg);
10949            }
10950            pkg.applicationInfo.uid = pkgSetting.appId;
10951            pkg.mExtras = pkgSetting;
10952
10953
10954            // Static shared libs have same package with different versions where
10955            // we internally use a synthetic package name to allow multiple versions
10956            // of the same package, therefore we need to compare signatures against
10957            // the package setting for the latest library version.
10958            PackageSetting signatureCheckPs = pkgSetting;
10959            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10960                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10961                if (libraryEntry != null) {
10962                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10963                }
10964            }
10965
10966            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10967                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10968                    // We just determined the app is signed correctly, so bring
10969                    // over the latest parsed certs.
10970                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10971                } else {
10972                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10973                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10974                                "Package " + pkg.packageName + " upgrade keys do not match the "
10975                                + "previously installed version");
10976                    } else {
10977                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10978                        String msg = "System package " + pkg.packageName
10979                                + " signature changed; retaining data.";
10980                        reportSettingsProblem(Log.WARN, msg);
10981                    }
10982                }
10983            } else {
10984                try {
10985                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10986                    verifySignaturesLP(signatureCheckPs, pkg);
10987                    // We just determined the app is signed correctly, so bring
10988                    // over the latest parsed certs.
10989                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10990                } catch (PackageManagerException e) {
10991                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10992                        throw e;
10993                    }
10994                    // The signature has changed, but this package is in the system
10995                    // image...  let's recover!
10996                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10997                    // However...  if this package is part of a shared user, but it
10998                    // doesn't match the signature of the shared user, let's fail.
10999                    // What this means is that you can't change the signatures
11000                    // associated with an overall shared user, which doesn't seem all
11001                    // that unreasonable.
11002                    if (signatureCheckPs.sharedUser != null) {
11003                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
11004                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
11005                            throw new PackageManagerException(
11006                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
11007                                    "Signature mismatch for shared user: "
11008                                            + pkgSetting.sharedUser);
11009                        }
11010                    }
11011                    // File a report about this.
11012                    String msg = "System package " + pkg.packageName
11013                            + " signature changed; retaining data.";
11014                    reportSettingsProblem(Log.WARN, msg);
11015                }
11016            }
11017
11018            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
11019                // This package wants to adopt ownership of permissions from
11020                // another package.
11021                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
11022                    final String origName = pkg.mAdoptPermissions.get(i);
11023                    final PackageSetting orig = mSettings.getPackageLPr(origName);
11024                    if (orig != null) {
11025                        if (verifyPackageUpdateLPr(orig, pkg)) {
11026                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
11027                                    + pkg.packageName);
11028                            // SIDE EFFECTS; updates permissions system state; move elsewhere
11029                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
11030                        }
11031                    }
11032                }
11033            }
11034        }
11035
11036        pkg.applicationInfo.processName = fixProcessName(
11037                pkg.applicationInfo.packageName,
11038                pkg.applicationInfo.processName);
11039
11040        if (pkg != mPlatformPackage) {
11041            // Get all of our default paths setup
11042            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
11043        }
11044
11045        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
11046
11047        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
11048            if (needToDeriveAbi) {
11049                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
11050                final boolean extractNativeLibs = !pkg.isLibrary();
11051                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
11052                        mAppLib32InstallDir);
11053                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11054
11055                // Some system apps still use directory structure for native libraries
11056                // in which case we might end up not detecting abi solely based on apk
11057                // structure. Try to detect abi based on directory structure.
11058                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
11059                        pkg.applicationInfo.primaryCpuAbi == null) {
11060                    setBundledAppAbisAndRoots(pkg, pkgSetting);
11061                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11062                }
11063            } else {
11064                // This is not a first boot or an upgrade, don't bother deriving the
11065                // ABI during the scan. Instead, trust the value that was stored in the
11066                // package setting.
11067                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
11068                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
11069
11070                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11071
11072                if (DEBUG_ABI_SELECTION) {
11073                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
11074                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
11075                        pkg.applicationInfo.secondaryCpuAbi);
11076                }
11077            }
11078        } else {
11079            if ((scanFlags & SCAN_MOVE) != 0) {
11080                // We haven't run dex-opt for this move (since we've moved the compiled output too)
11081                // but we already have this packages package info in the PackageSetting. We just
11082                // use that and derive the native library path based on the new codepath.
11083                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
11084                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
11085            }
11086
11087            // Set native library paths again. For moves, the path will be updated based on the
11088            // ABIs we've determined above. For non-moves, the path will be updated based on the
11089            // ABIs we determined during compilation, but the path will depend on the final
11090            // package path (after the rename away from the stage path).
11091            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11092        }
11093
11094        // This is a special case for the "system" package, where the ABI is
11095        // dictated by the zygote configuration (and init.rc). We should keep track
11096        // of this ABI so that we can deal with "normal" applications that run under
11097        // the same UID correctly.
11098        if (mPlatformPackage == pkg) {
11099            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
11100                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
11101        }
11102
11103        // If there's a mismatch between the abi-override in the package setting
11104        // and the abiOverride specified for the install. Warn about this because we
11105        // would've already compiled the app without taking the package setting into
11106        // account.
11107        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
11108            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
11109                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
11110                        " for package " + pkg.packageName);
11111            }
11112        }
11113
11114        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11115        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11116        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
11117
11118        // Copy the derived override back to the parsed package, so that we can
11119        // update the package settings accordingly.
11120        pkg.cpuAbiOverride = cpuAbiOverride;
11121
11122        if (DEBUG_ABI_SELECTION) {
11123            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
11124                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
11125                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
11126        }
11127
11128        // Push the derived path down into PackageSettings so we know what to
11129        // clean up at uninstall time.
11130        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
11131
11132        if (DEBUG_ABI_SELECTION) {
11133            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
11134                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
11135                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
11136        }
11137
11138        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
11139        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
11140            // We don't do this here during boot because we can do it all
11141            // at once after scanning all existing packages.
11142            //
11143            // We also do this *before* we perform dexopt on this package, so that
11144            // we can avoid redundant dexopts, and also to make sure we've got the
11145            // code and package path correct.
11146            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
11147        }
11148
11149        if (mFactoryTest && pkg.requestedPermissions.contains(
11150                android.Manifest.permission.FACTORY_TEST)) {
11151            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
11152        }
11153
11154        if (isSystemApp(pkg)) {
11155            pkgSetting.isOrphaned = true;
11156        }
11157
11158        // Take care of first install / last update times.
11159        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
11160        if (currentTime != 0) {
11161            if (pkgSetting.firstInstallTime == 0) {
11162                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
11163            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11164                pkgSetting.lastUpdateTime = currentTime;
11165            }
11166        } else if (pkgSetting.firstInstallTime == 0) {
11167            // We need *something*.  Take time time stamp of the file.
11168            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11169        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11170            if (scanFileTime != pkgSetting.timeStamp) {
11171                // A package on the system image has changed; consider this
11172                // to be an update.
11173                pkgSetting.lastUpdateTime = scanFileTime;
11174            }
11175        }
11176        pkgSetting.setTimeStamp(scanFileTime);
11177
11178        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11179            if (nonMutatedPs != null) {
11180                synchronized (mPackages) {
11181                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11182                }
11183            }
11184        } else {
11185            final int userId = user == null ? 0 : user.getIdentifier();
11186            // Modify state for the given package setting
11187            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11188                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11189            if (pkgSetting.getInstantApp(userId)) {
11190                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11191            }
11192        }
11193        return pkg;
11194    }
11195
11196    /**
11197     * Applies policy to the parsed package based upon the given policy flags.
11198     * Ensures the package is in a good state.
11199     * <p>
11200     * Implementation detail: This method must NOT have any side effect. It would
11201     * ideally be static, but, it requires locks to read system state.
11202     */
11203    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11204        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11205            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11206            if (pkg.applicationInfo.isDirectBootAware()) {
11207                // we're direct boot aware; set for all components
11208                for (PackageParser.Service s : pkg.services) {
11209                    s.info.encryptionAware = s.info.directBootAware = true;
11210                }
11211                for (PackageParser.Provider p : pkg.providers) {
11212                    p.info.encryptionAware = p.info.directBootAware = true;
11213                }
11214                for (PackageParser.Activity a : pkg.activities) {
11215                    a.info.encryptionAware = a.info.directBootAware = true;
11216                }
11217                for (PackageParser.Activity r : pkg.receivers) {
11218                    r.info.encryptionAware = r.info.directBootAware = true;
11219                }
11220            }
11221            if (compressedFileExists(pkg.codePath)) {
11222                pkg.isStub = true;
11223            }
11224        } else {
11225            // Only allow system apps to be flagged as core apps.
11226            pkg.coreApp = false;
11227            // clear flags not applicable to regular apps
11228            pkg.applicationInfo.privateFlags &=
11229                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11230            pkg.applicationInfo.privateFlags &=
11231                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11232        }
11233        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11234
11235        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11236            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11237        }
11238
11239        if (!isSystemApp(pkg)) {
11240            // Only system apps can use these features.
11241            pkg.mOriginalPackages = null;
11242            pkg.mRealPackage = null;
11243            pkg.mAdoptPermissions = null;
11244        }
11245    }
11246
11247    /**
11248     * Asserts the parsed package is valid according to the given policy. If the
11249     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11250     * <p>
11251     * Implementation detail: This method must NOT have any side effects. It would
11252     * ideally be static, but, it requires locks to read system state.
11253     *
11254     * @throws PackageManagerException If the package fails any of the validation checks
11255     */
11256    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11257            throws PackageManagerException {
11258        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11259            assertCodePolicy(pkg);
11260        }
11261
11262        if (pkg.applicationInfo.getCodePath() == null ||
11263                pkg.applicationInfo.getResourcePath() == null) {
11264            // Bail out. The resource and code paths haven't been set.
11265            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11266                    "Code and resource paths haven't been set correctly");
11267        }
11268
11269        // Make sure we're not adding any bogus keyset info
11270        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11271        ksms.assertScannedPackageValid(pkg);
11272
11273        synchronized (mPackages) {
11274            // The special "android" package can only be defined once
11275            if (pkg.packageName.equals("android")) {
11276                if (mAndroidApplication != null) {
11277                    Slog.w(TAG, "*************************************************");
11278                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11279                    Slog.w(TAG, " codePath=" + pkg.codePath);
11280                    Slog.w(TAG, "*************************************************");
11281                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11282                            "Core android package being redefined.  Skipping.");
11283                }
11284            }
11285
11286            // A package name must be unique; don't allow duplicates
11287            if (mPackages.containsKey(pkg.packageName)) {
11288                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11289                        "Application package " + pkg.packageName
11290                        + " already installed.  Skipping duplicate.");
11291            }
11292
11293            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11294                // Static libs have a synthetic package name containing the version
11295                // but we still want the base name to be unique.
11296                if (mPackages.containsKey(pkg.manifestPackageName)) {
11297                    throw new PackageManagerException(
11298                            "Duplicate static shared lib provider package");
11299                }
11300
11301                // Static shared libraries should have at least O target SDK
11302                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11303                    throw new PackageManagerException(
11304                            "Packages declaring static-shared libs must target O SDK or higher");
11305                }
11306
11307                // Package declaring static a shared lib cannot be instant apps
11308                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11309                    throw new PackageManagerException(
11310                            "Packages declaring static-shared libs cannot be instant apps");
11311                }
11312
11313                // Package declaring static a shared lib cannot be renamed since the package
11314                // name is synthetic and apps can't code around package manager internals.
11315                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11316                    throw new PackageManagerException(
11317                            "Packages declaring static-shared libs cannot be renamed");
11318                }
11319
11320                // Package declaring static a shared lib cannot declare child packages
11321                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11322                    throw new PackageManagerException(
11323                            "Packages declaring static-shared libs cannot have child packages");
11324                }
11325
11326                // Package declaring static a shared lib cannot declare dynamic libs
11327                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11328                    throw new PackageManagerException(
11329                            "Packages declaring static-shared libs cannot declare dynamic libs");
11330                }
11331
11332                // Package declaring static a shared lib cannot declare shared users
11333                if (pkg.mSharedUserId != null) {
11334                    throw new PackageManagerException(
11335                            "Packages declaring static-shared libs cannot declare shared users");
11336                }
11337
11338                // Static shared libs cannot declare activities
11339                if (!pkg.activities.isEmpty()) {
11340                    throw new PackageManagerException(
11341                            "Static shared libs cannot declare activities");
11342                }
11343
11344                // Static shared libs cannot declare services
11345                if (!pkg.services.isEmpty()) {
11346                    throw new PackageManagerException(
11347                            "Static shared libs cannot declare services");
11348                }
11349
11350                // Static shared libs cannot declare providers
11351                if (!pkg.providers.isEmpty()) {
11352                    throw new PackageManagerException(
11353                            "Static shared libs cannot declare content providers");
11354                }
11355
11356                // Static shared libs cannot declare receivers
11357                if (!pkg.receivers.isEmpty()) {
11358                    throw new PackageManagerException(
11359                            "Static shared libs cannot declare broadcast receivers");
11360                }
11361
11362                // Static shared libs cannot declare permission groups
11363                if (!pkg.permissionGroups.isEmpty()) {
11364                    throw new PackageManagerException(
11365                            "Static shared libs cannot declare permission groups");
11366                }
11367
11368                // Static shared libs cannot declare permissions
11369                if (!pkg.permissions.isEmpty()) {
11370                    throw new PackageManagerException(
11371                            "Static shared libs cannot declare permissions");
11372                }
11373
11374                // Static shared libs cannot declare protected broadcasts
11375                if (pkg.protectedBroadcasts != null) {
11376                    throw new PackageManagerException(
11377                            "Static shared libs cannot declare protected broadcasts");
11378                }
11379
11380                // Static shared libs cannot be overlay targets
11381                if (pkg.mOverlayTarget != null) {
11382                    throw new PackageManagerException(
11383                            "Static shared libs cannot be overlay targets");
11384                }
11385
11386                // The version codes must be ordered as lib versions
11387                int minVersionCode = Integer.MIN_VALUE;
11388                int maxVersionCode = Integer.MAX_VALUE;
11389
11390                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11391                        pkg.staticSharedLibName);
11392                if (versionedLib != null) {
11393                    final int versionCount = versionedLib.size();
11394                    for (int i = 0; i < versionCount; i++) {
11395                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11396                        final int libVersionCode = libInfo.getDeclaringPackage()
11397                                .getVersionCode();
11398                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11399                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11400                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11401                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11402                        } else {
11403                            minVersionCode = maxVersionCode = libVersionCode;
11404                            break;
11405                        }
11406                    }
11407                }
11408                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11409                    throw new PackageManagerException("Static shared"
11410                            + " lib version codes must be ordered as lib versions");
11411                }
11412            }
11413
11414            // Only privileged apps and updated privileged apps can add child packages.
11415            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11416                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11417                    throw new PackageManagerException("Only privileged apps can add child "
11418                            + "packages. Ignoring package " + pkg.packageName);
11419                }
11420                final int childCount = pkg.childPackages.size();
11421                for (int i = 0; i < childCount; i++) {
11422                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11423                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11424                            childPkg.packageName)) {
11425                        throw new PackageManagerException("Can't override child of "
11426                                + "another disabled app. Ignoring package " + pkg.packageName);
11427                    }
11428                }
11429            }
11430
11431            // If we're only installing presumed-existing packages, require that the
11432            // scanned APK is both already known and at the path previously established
11433            // for it.  Previously unknown packages we pick up normally, but if we have an
11434            // a priori expectation about this package's install presence, enforce it.
11435            // With a singular exception for new system packages. When an OTA contains
11436            // a new system package, we allow the codepath to change from a system location
11437            // to the user-installed location. If we don't allow this change, any newer,
11438            // user-installed version of the application will be ignored.
11439            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11440                if (mExpectingBetter.containsKey(pkg.packageName)) {
11441                    logCriticalInfo(Log.WARN,
11442                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11443                } else {
11444                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11445                    if (known != null) {
11446                        if (DEBUG_PACKAGE_SCANNING) {
11447                            Log.d(TAG, "Examining " + pkg.codePath
11448                                    + " and requiring known paths " + known.codePathString
11449                                    + " & " + known.resourcePathString);
11450                        }
11451                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11452                                || !pkg.applicationInfo.getResourcePath().equals(
11453                                        known.resourcePathString)) {
11454                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11455                                    "Application package " + pkg.packageName
11456                                    + " found at " + pkg.applicationInfo.getCodePath()
11457                                    + " but expected at " + known.codePathString
11458                                    + "; ignoring.");
11459                        }
11460                    } else {
11461                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11462                                "Application package " + pkg.packageName
11463                                + " not found; ignoring.");
11464                    }
11465                }
11466            }
11467
11468            // Verify that this new package doesn't have any content providers
11469            // that conflict with existing packages.  Only do this if the
11470            // package isn't already installed, since we don't want to break
11471            // things that are installed.
11472            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11473                final int N = pkg.providers.size();
11474                int i;
11475                for (i=0; i<N; i++) {
11476                    PackageParser.Provider p = pkg.providers.get(i);
11477                    if (p.info.authority != null) {
11478                        String names[] = p.info.authority.split(";");
11479                        for (int j = 0; j < names.length; j++) {
11480                            if (mProvidersByAuthority.containsKey(names[j])) {
11481                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11482                                final String otherPackageName =
11483                                        ((other != null && other.getComponentName() != null) ?
11484                                                other.getComponentName().getPackageName() : "?");
11485                                throw new PackageManagerException(
11486                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11487                                        "Can't install because provider name " + names[j]
11488                                                + " (in package " + pkg.applicationInfo.packageName
11489                                                + ") is already used by " + otherPackageName);
11490                            }
11491                        }
11492                    }
11493                }
11494            }
11495        }
11496    }
11497
11498    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11499            int type, String declaringPackageName, int declaringVersionCode) {
11500        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11501        if (versionedLib == null) {
11502            versionedLib = new SparseArray<>();
11503            mSharedLibraries.put(name, versionedLib);
11504            if (type == SharedLibraryInfo.TYPE_STATIC) {
11505                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11506            }
11507        } else if (versionedLib.indexOfKey(version) >= 0) {
11508            return false;
11509        }
11510        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11511                version, type, declaringPackageName, declaringVersionCode);
11512        versionedLib.put(version, libEntry);
11513        return true;
11514    }
11515
11516    private boolean removeSharedLibraryLPw(String name, int version) {
11517        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11518        if (versionedLib == null) {
11519            return false;
11520        }
11521        final int libIdx = versionedLib.indexOfKey(version);
11522        if (libIdx < 0) {
11523            return false;
11524        }
11525        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11526        versionedLib.remove(version);
11527        if (versionedLib.size() <= 0) {
11528            mSharedLibraries.remove(name);
11529            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11530                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11531                        .getPackageName());
11532            }
11533        }
11534        return true;
11535    }
11536
11537    /**
11538     * Adds a scanned package to the system. When this method is finished, the package will
11539     * be available for query, resolution, etc...
11540     */
11541    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11542            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11543        final String pkgName = pkg.packageName;
11544        if (mCustomResolverComponentName != null &&
11545                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11546            setUpCustomResolverActivity(pkg);
11547        }
11548
11549        if (pkg.packageName.equals("android")) {
11550            synchronized (mPackages) {
11551                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11552                    // Set up information for our fall-back user intent resolution activity.
11553                    mPlatformPackage = pkg;
11554                    pkg.mVersionCode = mSdkVersion;
11555                    mAndroidApplication = pkg.applicationInfo;
11556                    if (!mResolverReplaced) {
11557                        mResolveActivity.applicationInfo = mAndroidApplication;
11558                        mResolveActivity.name = ResolverActivity.class.getName();
11559                        mResolveActivity.packageName = mAndroidApplication.packageName;
11560                        mResolveActivity.processName = "system:ui";
11561                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11562                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11563                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11564                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11565                        mResolveActivity.exported = true;
11566                        mResolveActivity.enabled = true;
11567                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11568                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11569                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11570                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11571                                | ActivityInfo.CONFIG_ORIENTATION
11572                                | ActivityInfo.CONFIG_KEYBOARD
11573                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11574                        mResolveInfo.activityInfo = mResolveActivity;
11575                        mResolveInfo.priority = 0;
11576                        mResolveInfo.preferredOrder = 0;
11577                        mResolveInfo.match = 0;
11578                        mResolveComponentName = new ComponentName(
11579                                mAndroidApplication.packageName, mResolveActivity.name);
11580                    }
11581                }
11582            }
11583        }
11584
11585        ArrayList<PackageParser.Package> clientLibPkgs = null;
11586        // writer
11587        synchronized (mPackages) {
11588            boolean hasStaticSharedLibs = false;
11589
11590            // Any app can add new static shared libraries
11591            if (pkg.staticSharedLibName != null) {
11592                // Static shared libs don't allow renaming as they have synthetic package
11593                // names to allow install of multiple versions, so use name from manifest.
11594                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11595                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11596                        pkg.manifestPackageName, pkg.mVersionCode)) {
11597                    hasStaticSharedLibs = true;
11598                } else {
11599                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11600                                + pkg.staticSharedLibName + " already exists; skipping");
11601                }
11602                // Static shared libs cannot be updated once installed since they
11603                // use synthetic package name which includes the version code, so
11604                // not need to update other packages's shared lib dependencies.
11605            }
11606
11607            if (!hasStaticSharedLibs
11608                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11609                // Only system apps can add new dynamic shared libraries.
11610                if (pkg.libraryNames != null) {
11611                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11612                        String name = pkg.libraryNames.get(i);
11613                        boolean allowed = false;
11614                        if (pkg.isUpdatedSystemApp()) {
11615                            // New library entries can only be added through the
11616                            // system image.  This is important to get rid of a lot
11617                            // of nasty edge cases: for example if we allowed a non-
11618                            // system update of the app to add a library, then uninstalling
11619                            // the update would make the library go away, and assumptions
11620                            // we made such as through app install filtering would now
11621                            // have allowed apps on the device which aren't compatible
11622                            // with it.  Better to just have the restriction here, be
11623                            // conservative, and create many fewer cases that can negatively
11624                            // impact the user experience.
11625                            final PackageSetting sysPs = mSettings
11626                                    .getDisabledSystemPkgLPr(pkg.packageName);
11627                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11628                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11629                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11630                                        allowed = true;
11631                                        break;
11632                                    }
11633                                }
11634                            }
11635                        } else {
11636                            allowed = true;
11637                        }
11638                        if (allowed) {
11639                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11640                                    SharedLibraryInfo.VERSION_UNDEFINED,
11641                                    SharedLibraryInfo.TYPE_DYNAMIC,
11642                                    pkg.packageName, pkg.mVersionCode)) {
11643                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11644                                        + name + " already exists; skipping");
11645                            }
11646                        } else {
11647                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11648                                    + name + " that is not declared on system image; skipping");
11649                        }
11650                    }
11651
11652                    if ((scanFlags & SCAN_BOOTING) == 0) {
11653                        // If we are not booting, we need to update any applications
11654                        // that are clients of our shared library.  If we are booting,
11655                        // this will all be done once the scan is complete.
11656                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11657                    }
11658                }
11659            }
11660        }
11661
11662        if ((scanFlags & SCAN_BOOTING) != 0) {
11663            // No apps can run during boot scan, so they don't need to be frozen
11664        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11665            // Caller asked to not kill app, so it's probably not frozen
11666        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11667            // Caller asked us to ignore frozen check for some reason; they
11668            // probably didn't know the package name
11669        } else {
11670            // We're doing major surgery on this package, so it better be frozen
11671            // right now to keep it from launching
11672            checkPackageFrozen(pkgName);
11673        }
11674
11675        // Also need to kill any apps that are dependent on the library.
11676        if (clientLibPkgs != null) {
11677            for (int i=0; i<clientLibPkgs.size(); i++) {
11678                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11679                killApplication(clientPkg.applicationInfo.packageName,
11680                        clientPkg.applicationInfo.uid, "update lib");
11681            }
11682        }
11683
11684        // writer
11685        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11686
11687        synchronized (mPackages) {
11688            // We don't expect installation to fail beyond this point
11689
11690            // Add the new setting to mSettings
11691            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11692            // Add the new setting to mPackages
11693            mPackages.put(pkg.applicationInfo.packageName, pkg);
11694            // Make sure we don't accidentally delete its data.
11695            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11696            while (iter.hasNext()) {
11697                PackageCleanItem item = iter.next();
11698                if (pkgName.equals(item.packageName)) {
11699                    iter.remove();
11700                }
11701            }
11702
11703            // Add the package's KeySets to the global KeySetManagerService
11704            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11705            ksms.addScannedPackageLPw(pkg);
11706
11707            int N = pkg.providers.size();
11708            StringBuilder r = null;
11709            int i;
11710            for (i=0; i<N; i++) {
11711                PackageParser.Provider p = pkg.providers.get(i);
11712                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11713                        p.info.processName);
11714                mProviders.addProvider(p);
11715                p.syncable = p.info.isSyncable;
11716                if (p.info.authority != null) {
11717                    String names[] = p.info.authority.split(";");
11718                    p.info.authority = null;
11719                    for (int j = 0; j < names.length; j++) {
11720                        if (j == 1 && p.syncable) {
11721                            // We only want the first authority for a provider to possibly be
11722                            // syncable, so if we already added this provider using a different
11723                            // authority clear the syncable flag. We copy the provider before
11724                            // changing it because the mProviders object contains a reference
11725                            // to a provider that we don't want to change.
11726                            // Only do this for the second authority since the resulting provider
11727                            // object can be the same for all future authorities for this provider.
11728                            p = new PackageParser.Provider(p);
11729                            p.syncable = false;
11730                        }
11731                        if (!mProvidersByAuthority.containsKey(names[j])) {
11732                            mProvidersByAuthority.put(names[j], p);
11733                            if (p.info.authority == null) {
11734                                p.info.authority = names[j];
11735                            } else {
11736                                p.info.authority = p.info.authority + ";" + names[j];
11737                            }
11738                            if (DEBUG_PACKAGE_SCANNING) {
11739                                if (chatty)
11740                                    Log.d(TAG, "Registered content provider: " + names[j]
11741                                            + ", className = " + p.info.name + ", isSyncable = "
11742                                            + p.info.isSyncable);
11743                            }
11744                        } else {
11745                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11746                            Slog.w(TAG, "Skipping provider name " + names[j] +
11747                                    " (in package " + pkg.applicationInfo.packageName +
11748                                    "): name already used by "
11749                                    + ((other != null && other.getComponentName() != null)
11750                                            ? other.getComponentName().getPackageName() : "?"));
11751                        }
11752                    }
11753                }
11754                if (chatty) {
11755                    if (r == null) {
11756                        r = new StringBuilder(256);
11757                    } else {
11758                        r.append(' ');
11759                    }
11760                    r.append(p.info.name);
11761                }
11762            }
11763            if (r != null) {
11764                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11765            }
11766
11767            N = pkg.services.size();
11768            r = null;
11769            for (i=0; i<N; i++) {
11770                PackageParser.Service s = pkg.services.get(i);
11771                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11772                        s.info.processName);
11773                mServices.addService(s);
11774                if (chatty) {
11775                    if (r == null) {
11776                        r = new StringBuilder(256);
11777                    } else {
11778                        r.append(' ');
11779                    }
11780                    r.append(s.info.name);
11781                }
11782            }
11783            if (r != null) {
11784                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11785            }
11786
11787            N = pkg.receivers.size();
11788            r = null;
11789            for (i=0; i<N; i++) {
11790                PackageParser.Activity a = pkg.receivers.get(i);
11791                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11792                        a.info.processName);
11793                mReceivers.addActivity(a, "receiver");
11794                if (chatty) {
11795                    if (r == null) {
11796                        r = new StringBuilder(256);
11797                    } else {
11798                        r.append(' ');
11799                    }
11800                    r.append(a.info.name);
11801                }
11802            }
11803            if (r != null) {
11804                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11805            }
11806
11807            N = pkg.activities.size();
11808            r = null;
11809            for (i=0; i<N; i++) {
11810                PackageParser.Activity a = pkg.activities.get(i);
11811                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11812                        a.info.processName);
11813                mActivities.addActivity(a, "activity");
11814                if (chatty) {
11815                    if (r == null) {
11816                        r = new StringBuilder(256);
11817                    } else {
11818                        r.append(' ');
11819                    }
11820                    r.append(a.info.name);
11821                }
11822            }
11823            if (r != null) {
11824                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11825            }
11826
11827            N = pkg.permissionGroups.size();
11828            r = null;
11829            for (i=0; i<N; i++) {
11830                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11831                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11832                final String curPackageName = cur == null ? null : cur.info.packageName;
11833                // Dont allow ephemeral apps to define new permission groups.
11834                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11835                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11836                            + pg.info.packageName
11837                            + " ignored: instant apps cannot define new permission groups.");
11838                    continue;
11839                }
11840                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11841                if (cur == null || isPackageUpdate) {
11842                    mPermissionGroups.put(pg.info.name, pg);
11843                    if (chatty) {
11844                        if (r == null) {
11845                            r = new StringBuilder(256);
11846                        } else {
11847                            r.append(' ');
11848                        }
11849                        if (isPackageUpdate) {
11850                            r.append("UPD:");
11851                        }
11852                        r.append(pg.info.name);
11853                    }
11854                } else {
11855                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11856                            + pg.info.packageName + " ignored: original from "
11857                            + cur.info.packageName);
11858                    if (chatty) {
11859                        if (r == null) {
11860                            r = new StringBuilder(256);
11861                        } else {
11862                            r.append(' ');
11863                        }
11864                        r.append("DUP:");
11865                        r.append(pg.info.name);
11866                    }
11867                }
11868            }
11869            if (r != null) {
11870                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11871            }
11872
11873            N = pkg.permissions.size();
11874            r = null;
11875            for (i=0; i<N; i++) {
11876                PackageParser.Permission p = pkg.permissions.get(i);
11877
11878                // Dont allow ephemeral apps to define new permissions.
11879                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11880                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11881                            + p.info.packageName
11882                            + " ignored: instant apps cannot define new permissions.");
11883                    continue;
11884                }
11885
11886                // Assume by default that we did not install this permission into the system.
11887                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11888
11889                // Now that permission groups have a special meaning, we ignore permission
11890                // groups for legacy apps to prevent unexpected behavior. In particular,
11891                // permissions for one app being granted to someone just because they happen
11892                // to be in a group defined by another app (before this had no implications).
11893                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11894                    p.group = mPermissionGroups.get(p.info.group);
11895                    // Warn for a permission in an unknown group.
11896                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11897                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11898                                + p.info.packageName + " in an unknown group " + p.info.group);
11899                    }
11900                }
11901
11902                ArrayMap<String, BasePermission> permissionMap =
11903                        p.tree ? mSettings.mPermissionTrees
11904                                : mSettings.mPermissions;
11905                BasePermission bp = permissionMap.get(p.info.name);
11906
11907                // Allow system apps to redefine non-system permissions
11908                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11909                    final boolean currentOwnerIsSystem = (bp.perm != null
11910                            && isSystemApp(bp.perm.owner));
11911                    if (isSystemApp(p.owner)) {
11912                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11913                            // It's a built-in permission and no owner, take ownership now
11914                            bp.packageSetting = pkgSetting;
11915                            bp.perm = p;
11916                            bp.uid = pkg.applicationInfo.uid;
11917                            bp.sourcePackage = p.info.packageName;
11918                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11919                        } else if (!currentOwnerIsSystem) {
11920                            String msg = "New decl " + p.owner + " of permission  "
11921                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11922                            reportSettingsProblem(Log.WARN, msg);
11923                            bp = null;
11924                        }
11925                    }
11926                }
11927
11928                if (bp == null) {
11929                    bp = new BasePermission(p.info.name, p.info.packageName,
11930                            BasePermission.TYPE_NORMAL);
11931                    permissionMap.put(p.info.name, bp);
11932                }
11933
11934                if (bp.perm == null) {
11935                    if (bp.sourcePackage == null
11936                            || bp.sourcePackage.equals(p.info.packageName)) {
11937                        BasePermission tree = findPermissionTreeLP(p.info.name);
11938                        if (tree == null
11939                                || tree.sourcePackage.equals(p.info.packageName)) {
11940                            bp.packageSetting = pkgSetting;
11941                            bp.perm = p;
11942                            bp.uid = pkg.applicationInfo.uid;
11943                            bp.sourcePackage = p.info.packageName;
11944                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11945                            if (chatty) {
11946                                if (r == null) {
11947                                    r = new StringBuilder(256);
11948                                } else {
11949                                    r.append(' ');
11950                                }
11951                                r.append(p.info.name);
11952                            }
11953                        } else {
11954                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11955                                    + p.info.packageName + " ignored: base tree "
11956                                    + tree.name + " is from package "
11957                                    + tree.sourcePackage);
11958                        }
11959                    } else {
11960                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11961                                + p.info.packageName + " ignored: original from "
11962                                + bp.sourcePackage);
11963                    }
11964                } else if (chatty) {
11965                    if (r == null) {
11966                        r = new StringBuilder(256);
11967                    } else {
11968                        r.append(' ');
11969                    }
11970                    r.append("DUP:");
11971                    r.append(p.info.name);
11972                }
11973                if (bp.perm == p) {
11974                    bp.protectionLevel = p.info.protectionLevel;
11975                }
11976            }
11977
11978            if (r != null) {
11979                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11980            }
11981
11982            N = pkg.instrumentation.size();
11983            r = null;
11984            for (i=0; i<N; i++) {
11985                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11986                a.info.packageName = pkg.applicationInfo.packageName;
11987                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11988                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11989                a.info.splitNames = pkg.splitNames;
11990                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11991                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11992                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11993                a.info.dataDir = pkg.applicationInfo.dataDir;
11994                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11995                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11996                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11997                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11998                mInstrumentation.put(a.getComponentName(), a);
11999                if (chatty) {
12000                    if (r == null) {
12001                        r = new StringBuilder(256);
12002                    } else {
12003                        r.append(' ');
12004                    }
12005                    r.append(a.info.name);
12006                }
12007            }
12008            if (r != null) {
12009                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
12010            }
12011
12012            if (pkg.protectedBroadcasts != null) {
12013                N = pkg.protectedBroadcasts.size();
12014                synchronized (mProtectedBroadcasts) {
12015                    for (i = 0; i < N; i++) {
12016                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
12017                    }
12018                }
12019            }
12020        }
12021
12022        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12023    }
12024
12025    /**
12026     * Derive the ABI of a non-system package located at {@code scanFile}. This information
12027     * is derived purely on the basis of the contents of {@code scanFile} and
12028     * {@code cpuAbiOverride}.
12029     *
12030     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
12031     */
12032    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
12033                                 String cpuAbiOverride, boolean extractLibs,
12034                                 File appLib32InstallDir)
12035            throws PackageManagerException {
12036        // Give ourselves some initial paths; we'll come back for another
12037        // pass once we've determined ABI below.
12038        setNativeLibraryPaths(pkg, appLib32InstallDir);
12039
12040        // We would never need to extract libs for forward-locked and external packages,
12041        // since the container service will do it for us. We shouldn't attempt to
12042        // extract libs from system app when it was not updated.
12043        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
12044                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
12045            extractLibs = false;
12046        }
12047
12048        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
12049        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
12050
12051        NativeLibraryHelper.Handle handle = null;
12052        try {
12053            handle = NativeLibraryHelper.Handle.create(pkg);
12054            // TODO(multiArch): This can be null for apps that didn't go through the
12055            // usual installation process. We can calculate it again, like we
12056            // do during install time.
12057            //
12058            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
12059            // unnecessary.
12060            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
12061
12062            // Null out the abis so that they can be recalculated.
12063            pkg.applicationInfo.primaryCpuAbi = null;
12064            pkg.applicationInfo.secondaryCpuAbi = null;
12065            if (isMultiArch(pkg.applicationInfo)) {
12066                // Warn if we've set an abiOverride for multi-lib packages..
12067                // By definition, we need to copy both 32 and 64 bit libraries for
12068                // such packages.
12069                if (pkg.cpuAbiOverride != null
12070                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
12071                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
12072                }
12073
12074                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
12075                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
12076                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
12077                    if (extractLibs) {
12078                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12079                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12080                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
12081                                useIsaSpecificSubdirs);
12082                    } else {
12083                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12084                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
12085                    }
12086                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12087                }
12088
12089                // Shared library native code should be in the APK zip aligned
12090                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
12091                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12092                            "Shared library native lib extraction not supported");
12093                }
12094
12095                maybeThrowExceptionForMultiArchCopy(
12096                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
12097
12098                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
12099                    if (extractLibs) {
12100                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12101                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12102                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
12103                                useIsaSpecificSubdirs);
12104                    } else {
12105                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12106                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
12107                    }
12108                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12109                }
12110
12111                maybeThrowExceptionForMultiArchCopy(
12112                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
12113
12114                if (abi64 >= 0) {
12115                    // Shared library native libs should be in the APK zip aligned
12116                    if (extractLibs && pkg.isLibrary()) {
12117                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12118                                "Shared library native lib extraction not supported");
12119                    }
12120                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
12121                }
12122
12123                if (abi32 >= 0) {
12124                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
12125                    if (abi64 >= 0) {
12126                        if (pkg.use32bitAbi) {
12127                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
12128                            pkg.applicationInfo.primaryCpuAbi = abi;
12129                        } else {
12130                            pkg.applicationInfo.secondaryCpuAbi = abi;
12131                        }
12132                    } else {
12133                        pkg.applicationInfo.primaryCpuAbi = abi;
12134                    }
12135                }
12136            } else {
12137                String[] abiList = (cpuAbiOverride != null) ?
12138                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
12139
12140                // Enable gross and lame hacks for apps that are built with old
12141                // SDK tools. We must scan their APKs for renderscript bitcode and
12142                // not launch them if it's present. Don't bother checking on devices
12143                // that don't have 64 bit support.
12144                boolean needsRenderScriptOverride = false;
12145                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
12146                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
12147                    abiList = Build.SUPPORTED_32_BIT_ABIS;
12148                    needsRenderScriptOverride = true;
12149                }
12150
12151                final int copyRet;
12152                if (extractLibs) {
12153                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12154                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12155                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
12156                } else {
12157                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12158                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
12159                }
12160                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12161
12162                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
12163                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12164                            "Error unpackaging native libs for app, errorCode=" + copyRet);
12165                }
12166
12167                if (copyRet >= 0) {
12168                    // Shared libraries that have native libs must be multi-architecture
12169                    if (pkg.isLibrary()) {
12170                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12171                                "Shared library with native libs must be multiarch");
12172                    }
12173                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12174                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12175                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12176                } else if (needsRenderScriptOverride) {
12177                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
12178                }
12179            }
12180        } catch (IOException ioe) {
12181            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12182        } finally {
12183            IoUtils.closeQuietly(handle);
12184        }
12185
12186        // Now that we've calculated the ABIs and determined if it's an internal app,
12187        // we will go ahead and populate the nativeLibraryPath.
12188        setNativeLibraryPaths(pkg, appLib32InstallDir);
12189    }
12190
12191    /**
12192     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12193     * i.e, so that all packages can be run inside a single process if required.
12194     *
12195     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12196     * this function will either try and make the ABI for all packages in {@code packagesForUser}
12197     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12198     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12199     * updating a package that belongs to a shared user.
12200     *
12201     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12202     * adds unnecessary complexity.
12203     */
12204    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
12205            PackageParser.Package scannedPackage) {
12206        String requiredInstructionSet = null;
12207        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12208            requiredInstructionSet = VMRuntime.getInstructionSet(
12209                     scannedPackage.applicationInfo.primaryCpuAbi);
12210        }
12211
12212        PackageSetting requirer = null;
12213        for (PackageSetting ps : packagesForUser) {
12214            // If packagesForUser contains scannedPackage, we skip it. This will happen
12215            // when scannedPackage is an update of an existing package. Without this check,
12216            // we will never be able to change the ABI of any package belonging to a shared
12217            // user, even if it's compatible with other packages.
12218            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12219                if (ps.primaryCpuAbiString == null) {
12220                    continue;
12221                }
12222
12223                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12224                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12225                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12226                    // this but there's not much we can do.
12227                    String errorMessage = "Instruction set mismatch, "
12228                            + ((requirer == null) ? "[caller]" : requirer)
12229                            + " requires " + requiredInstructionSet + " whereas " + ps
12230                            + " requires " + instructionSet;
12231                    Slog.w(TAG, errorMessage);
12232                }
12233
12234                if (requiredInstructionSet == null) {
12235                    requiredInstructionSet = instructionSet;
12236                    requirer = ps;
12237                }
12238            }
12239        }
12240
12241        if (requiredInstructionSet != null) {
12242            String adjustedAbi;
12243            if (requirer != null) {
12244                // requirer != null implies that either scannedPackage was null or that scannedPackage
12245                // did not require an ABI, in which case we have to adjust scannedPackage to match
12246                // the ABI of the set (which is the same as requirer's ABI)
12247                adjustedAbi = requirer.primaryCpuAbiString;
12248                if (scannedPackage != null) {
12249                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12250                }
12251            } else {
12252                // requirer == null implies that we're updating all ABIs in the set to
12253                // match scannedPackage.
12254                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12255            }
12256
12257            for (PackageSetting ps : packagesForUser) {
12258                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12259                    if (ps.primaryCpuAbiString != null) {
12260                        continue;
12261                    }
12262
12263                    ps.primaryCpuAbiString = adjustedAbi;
12264                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12265                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12266                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12267                        if (DEBUG_ABI_SELECTION) {
12268                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12269                                    + " (requirer="
12270                                    + (requirer != null ? requirer.pkg : "null")
12271                                    + ", scannedPackage="
12272                                    + (scannedPackage != null ? scannedPackage : "null")
12273                                    + ")");
12274                        }
12275                        try {
12276                            mInstaller.rmdex(ps.codePathString,
12277                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12278                        } catch (InstallerException ignored) {
12279                        }
12280                    }
12281                }
12282            }
12283        }
12284    }
12285
12286    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12287        synchronized (mPackages) {
12288            mResolverReplaced = true;
12289            // Set up information for custom user intent resolution activity.
12290            mResolveActivity.applicationInfo = pkg.applicationInfo;
12291            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12292            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12293            mResolveActivity.processName = pkg.applicationInfo.packageName;
12294            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12295            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12296                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12297            mResolveActivity.theme = 0;
12298            mResolveActivity.exported = true;
12299            mResolveActivity.enabled = true;
12300            mResolveInfo.activityInfo = mResolveActivity;
12301            mResolveInfo.priority = 0;
12302            mResolveInfo.preferredOrder = 0;
12303            mResolveInfo.match = 0;
12304            mResolveComponentName = mCustomResolverComponentName;
12305            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12306                    mResolveComponentName);
12307        }
12308    }
12309
12310    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12311        if (installerActivity == null) {
12312            if (DEBUG_EPHEMERAL) {
12313                Slog.d(TAG, "Clear ephemeral installer activity");
12314            }
12315            mInstantAppInstallerActivity = null;
12316            return;
12317        }
12318
12319        if (DEBUG_EPHEMERAL) {
12320            Slog.d(TAG, "Set ephemeral installer activity: "
12321                    + installerActivity.getComponentName());
12322        }
12323        // Set up information for ephemeral installer activity
12324        mInstantAppInstallerActivity = installerActivity;
12325        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12326                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12327        mInstantAppInstallerActivity.exported = true;
12328        mInstantAppInstallerActivity.enabled = true;
12329        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12330        mInstantAppInstallerInfo.priority = 0;
12331        mInstantAppInstallerInfo.preferredOrder = 1;
12332        mInstantAppInstallerInfo.isDefault = true;
12333        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12334                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12335    }
12336
12337    private static String calculateBundledApkRoot(final String codePathString) {
12338        final File codePath = new File(codePathString);
12339        final File codeRoot;
12340        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12341            codeRoot = Environment.getRootDirectory();
12342        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12343            codeRoot = Environment.getOemDirectory();
12344        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12345            codeRoot = Environment.getVendorDirectory();
12346        } else {
12347            // Unrecognized code path; take its top real segment as the apk root:
12348            // e.g. /something/app/blah.apk => /something
12349            try {
12350                File f = codePath.getCanonicalFile();
12351                File parent = f.getParentFile();    // non-null because codePath is a file
12352                File tmp;
12353                while ((tmp = parent.getParentFile()) != null) {
12354                    f = parent;
12355                    parent = tmp;
12356                }
12357                codeRoot = f;
12358                Slog.w(TAG, "Unrecognized code path "
12359                        + codePath + " - using " + codeRoot);
12360            } catch (IOException e) {
12361                // Can't canonicalize the code path -- shenanigans?
12362                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12363                return Environment.getRootDirectory().getPath();
12364            }
12365        }
12366        return codeRoot.getPath();
12367    }
12368
12369    /**
12370     * Derive and set the location of native libraries for the given package,
12371     * which varies depending on where and how the package was installed.
12372     */
12373    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12374        final ApplicationInfo info = pkg.applicationInfo;
12375        final String codePath = pkg.codePath;
12376        final File codeFile = new File(codePath);
12377        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12378        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12379
12380        info.nativeLibraryRootDir = null;
12381        info.nativeLibraryRootRequiresIsa = false;
12382        info.nativeLibraryDir = null;
12383        info.secondaryNativeLibraryDir = null;
12384
12385        if (isApkFile(codeFile)) {
12386            // Monolithic install
12387            if (bundledApp) {
12388                // If "/system/lib64/apkname" exists, assume that is the per-package
12389                // native library directory to use; otherwise use "/system/lib/apkname".
12390                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12391                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12392                        getPrimaryInstructionSet(info));
12393
12394                // This is a bundled system app so choose the path based on the ABI.
12395                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12396                // is just the default path.
12397                final String apkName = deriveCodePathName(codePath);
12398                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12399                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12400                        apkName).getAbsolutePath();
12401
12402                if (info.secondaryCpuAbi != null) {
12403                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12404                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12405                            secondaryLibDir, apkName).getAbsolutePath();
12406                }
12407            } else if (asecApp) {
12408                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12409                        .getAbsolutePath();
12410            } else {
12411                final String apkName = deriveCodePathName(codePath);
12412                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12413                        .getAbsolutePath();
12414            }
12415
12416            info.nativeLibraryRootRequiresIsa = false;
12417            info.nativeLibraryDir = info.nativeLibraryRootDir;
12418        } else {
12419            // Cluster install
12420            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12421            info.nativeLibraryRootRequiresIsa = true;
12422
12423            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12424                    getPrimaryInstructionSet(info)).getAbsolutePath();
12425
12426            if (info.secondaryCpuAbi != null) {
12427                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12428                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12429            }
12430        }
12431    }
12432
12433    /**
12434     * Calculate the abis and roots for a bundled app. These can uniquely
12435     * be determined from the contents of the system partition, i.e whether
12436     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12437     * of this information, and instead assume that the system was built
12438     * sensibly.
12439     */
12440    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12441                                           PackageSetting pkgSetting) {
12442        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12443
12444        // If "/system/lib64/apkname" exists, assume that is the per-package
12445        // native library directory to use; otherwise use "/system/lib/apkname".
12446        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12447        setBundledAppAbi(pkg, apkRoot, apkName);
12448        // pkgSetting might be null during rescan following uninstall of updates
12449        // to a bundled app, so accommodate that possibility.  The settings in
12450        // that case will be established later from the parsed package.
12451        //
12452        // If the settings aren't null, sync them up with what we've just derived.
12453        // note that apkRoot isn't stored in the package settings.
12454        if (pkgSetting != null) {
12455            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12456            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12457        }
12458    }
12459
12460    /**
12461     * Deduces the ABI of a bundled app and sets the relevant fields on the
12462     * parsed pkg object.
12463     *
12464     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12465     *        under which system libraries are installed.
12466     * @param apkName the name of the installed package.
12467     */
12468    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12469        final File codeFile = new File(pkg.codePath);
12470
12471        final boolean has64BitLibs;
12472        final boolean has32BitLibs;
12473        if (isApkFile(codeFile)) {
12474            // Monolithic install
12475            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12476            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12477        } else {
12478            // Cluster install
12479            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12480            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12481                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12482                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12483                has64BitLibs = (new File(rootDir, isa)).exists();
12484            } else {
12485                has64BitLibs = false;
12486            }
12487            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12488                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12489                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12490                has32BitLibs = (new File(rootDir, isa)).exists();
12491            } else {
12492                has32BitLibs = false;
12493            }
12494        }
12495
12496        if (has64BitLibs && !has32BitLibs) {
12497            // The package has 64 bit libs, but not 32 bit libs. Its primary
12498            // ABI should be 64 bit. We can safely assume here that the bundled
12499            // native libraries correspond to the most preferred ABI in the list.
12500
12501            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12502            pkg.applicationInfo.secondaryCpuAbi = null;
12503        } else if (has32BitLibs && !has64BitLibs) {
12504            // The package has 32 bit libs but not 64 bit libs. Its primary
12505            // ABI should be 32 bit.
12506
12507            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12508            pkg.applicationInfo.secondaryCpuAbi = null;
12509        } else if (has32BitLibs && has64BitLibs) {
12510            // The application has both 64 and 32 bit bundled libraries. We check
12511            // here that the app declares multiArch support, and warn if it doesn't.
12512            //
12513            // We will be lenient here and record both ABIs. The primary will be the
12514            // ABI that's higher on the list, i.e, a device that's configured to prefer
12515            // 64 bit apps will see a 64 bit primary ABI,
12516
12517            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12518                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12519            }
12520
12521            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12522                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12523                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12524            } else {
12525                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12526                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12527            }
12528        } else {
12529            pkg.applicationInfo.primaryCpuAbi = null;
12530            pkg.applicationInfo.secondaryCpuAbi = null;
12531        }
12532    }
12533
12534    private void killApplication(String pkgName, int appId, String reason) {
12535        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12536    }
12537
12538    private void killApplication(String pkgName, int appId, int userId, String reason) {
12539        // Request the ActivityManager to kill the process(only for existing packages)
12540        // so that we do not end up in a confused state while the user is still using the older
12541        // version of the application while the new one gets installed.
12542        final long token = Binder.clearCallingIdentity();
12543        try {
12544            IActivityManager am = ActivityManager.getService();
12545            if (am != null) {
12546                try {
12547                    am.killApplication(pkgName, appId, userId, reason);
12548                } catch (RemoteException e) {
12549                }
12550            }
12551        } finally {
12552            Binder.restoreCallingIdentity(token);
12553        }
12554    }
12555
12556    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12557        // Remove the parent package setting
12558        PackageSetting ps = (PackageSetting) pkg.mExtras;
12559        if (ps != null) {
12560            removePackageLI(ps, chatty);
12561        }
12562        // Remove the child package setting
12563        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12564        for (int i = 0; i < childCount; i++) {
12565            PackageParser.Package childPkg = pkg.childPackages.get(i);
12566            ps = (PackageSetting) childPkg.mExtras;
12567            if (ps != null) {
12568                removePackageLI(ps, chatty);
12569            }
12570        }
12571    }
12572
12573    void removePackageLI(PackageSetting ps, boolean chatty) {
12574        if (DEBUG_INSTALL) {
12575            if (chatty)
12576                Log.d(TAG, "Removing package " + ps.name);
12577        }
12578
12579        // writer
12580        synchronized (mPackages) {
12581            mPackages.remove(ps.name);
12582            final PackageParser.Package pkg = ps.pkg;
12583            if (pkg != null) {
12584                cleanPackageDataStructuresLILPw(pkg, chatty);
12585            }
12586        }
12587    }
12588
12589    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12590        if (DEBUG_INSTALL) {
12591            if (chatty)
12592                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12593        }
12594
12595        // writer
12596        synchronized (mPackages) {
12597            // Remove the parent package
12598            mPackages.remove(pkg.applicationInfo.packageName);
12599            cleanPackageDataStructuresLILPw(pkg, chatty);
12600
12601            // Remove the child packages
12602            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12603            for (int i = 0; i < childCount; i++) {
12604                PackageParser.Package childPkg = pkg.childPackages.get(i);
12605                mPackages.remove(childPkg.applicationInfo.packageName);
12606                cleanPackageDataStructuresLILPw(childPkg, chatty);
12607            }
12608        }
12609    }
12610
12611    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12612        int N = pkg.providers.size();
12613        StringBuilder r = null;
12614        int i;
12615        for (i=0; i<N; i++) {
12616            PackageParser.Provider p = pkg.providers.get(i);
12617            mProviders.removeProvider(p);
12618            if (p.info.authority == null) {
12619
12620                /* There was another ContentProvider with this authority when
12621                 * this app was installed so this authority is null,
12622                 * Ignore it as we don't have to unregister the provider.
12623                 */
12624                continue;
12625            }
12626            String names[] = p.info.authority.split(";");
12627            for (int j = 0; j < names.length; j++) {
12628                if (mProvidersByAuthority.get(names[j]) == p) {
12629                    mProvidersByAuthority.remove(names[j]);
12630                    if (DEBUG_REMOVE) {
12631                        if (chatty)
12632                            Log.d(TAG, "Unregistered content provider: " + names[j]
12633                                    + ", className = " + p.info.name + ", isSyncable = "
12634                                    + p.info.isSyncable);
12635                    }
12636                }
12637            }
12638            if (DEBUG_REMOVE && chatty) {
12639                if (r == null) {
12640                    r = new StringBuilder(256);
12641                } else {
12642                    r.append(' ');
12643                }
12644                r.append(p.info.name);
12645            }
12646        }
12647        if (r != null) {
12648            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12649        }
12650
12651        N = pkg.services.size();
12652        r = null;
12653        for (i=0; i<N; i++) {
12654            PackageParser.Service s = pkg.services.get(i);
12655            mServices.removeService(s);
12656            if (chatty) {
12657                if (r == null) {
12658                    r = new StringBuilder(256);
12659                } else {
12660                    r.append(' ');
12661                }
12662                r.append(s.info.name);
12663            }
12664        }
12665        if (r != null) {
12666            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12667        }
12668
12669        N = pkg.receivers.size();
12670        r = null;
12671        for (i=0; i<N; i++) {
12672            PackageParser.Activity a = pkg.receivers.get(i);
12673            mReceivers.removeActivity(a, "receiver");
12674            if (DEBUG_REMOVE && chatty) {
12675                if (r == null) {
12676                    r = new StringBuilder(256);
12677                } else {
12678                    r.append(' ');
12679                }
12680                r.append(a.info.name);
12681            }
12682        }
12683        if (r != null) {
12684            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12685        }
12686
12687        N = pkg.activities.size();
12688        r = null;
12689        for (i=0; i<N; i++) {
12690            PackageParser.Activity a = pkg.activities.get(i);
12691            mActivities.removeActivity(a, "activity");
12692            if (DEBUG_REMOVE && chatty) {
12693                if (r == null) {
12694                    r = new StringBuilder(256);
12695                } else {
12696                    r.append(' ');
12697                }
12698                r.append(a.info.name);
12699            }
12700        }
12701        if (r != null) {
12702            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12703        }
12704
12705        N = pkg.permissions.size();
12706        r = null;
12707        for (i=0; i<N; i++) {
12708            PackageParser.Permission p = pkg.permissions.get(i);
12709            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12710            if (bp == null) {
12711                bp = mSettings.mPermissionTrees.get(p.info.name);
12712            }
12713            if (bp != null && bp.perm == p) {
12714                bp.perm = null;
12715                if (DEBUG_REMOVE && chatty) {
12716                    if (r == null) {
12717                        r = new StringBuilder(256);
12718                    } else {
12719                        r.append(' ');
12720                    }
12721                    r.append(p.info.name);
12722                }
12723            }
12724            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12725                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12726                if (appOpPkgs != null) {
12727                    appOpPkgs.remove(pkg.packageName);
12728                }
12729            }
12730        }
12731        if (r != null) {
12732            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12733        }
12734
12735        N = pkg.requestedPermissions.size();
12736        r = null;
12737        for (i=0; i<N; i++) {
12738            String perm = pkg.requestedPermissions.get(i);
12739            BasePermission bp = mSettings.mPermissions.get(perm);
12740            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12741                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12742                if (appOpPkgs != null) {
12743                    appOpPkgs.remove(pkg.packageName);
12744                    if (appOpPkgs.isEmpty()) {
12745                        mAppOpPermissionPackages.remove(perm);
12746                    }
12747                }
12748            }
12749        }
12750        if (r != null) {
12751            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12752        }
12753
12754        N = pkg.instrumentation.size();
12755        r = null;
12756        for (i=0; i<N; i++) {
12757            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12758            mInstrumentation.remove(a.getComponentName());
12759            if (DEBUG_REMOVE && chatty) {
12760                if (r == null) {
12761                    r = new StringBuilder(256);
12762                } else {
12763                    r.append(' ');
12764                }
12765                r.append(a.info.name);
12766            }
12767        }
12768        if (r != null) {
12769            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12770        }
12771
12772        r = null;
12773        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12774            // Only system apps can hold shared libraries.
12775            if (pkg.libraryNames != null) {
12776                for (i = 0; i < pkg.libraryNames.size(); i++) {
12777                    String name = pkg.libraryNames.get(i);
12778                    if (removeSharedLibraryLPw(name, 0)) {
12779                        if (DEBUG_REMOVE && chatty) {
12780                            if (r == null) {
12781                                r = new StringBuilder(256);
12782                            } else {
12783                                r.append(' ');
12784                            }
12785                            r.append(name);
12786                        }
12787                    }
12788                }
12789            }
12790        }
12791
12792        r = null;
12793
12794        // Any package can hold static shared libraries.
12795        if (pkg.staticSharedLibName != null) {
12796            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12797                if (DEBUG_REMOVE && chatty) {
12798                    if (r == null) {
12799                        r = new StringBuilder(256);
12800                    } else {
12801                        r.append(' ');
12802                    }
12803                    r.append(pkg.staticSharedLibName);
12804                }
12805            }
12806        }
12807
12808        if (r != null) {
12809            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12810        }
12811    }
12812
12813    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12814        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12815            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12816                return true;
12817            }
12818        }
12819        return false;
12820    }
12821
12822    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12823    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12824    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12825
12826    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12827        // Update the parent permissions
12828        updatePermissionsLPw(pkg.packageName, pkg, flags);
12829        // Update the child permissions
12830        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12831        for (int i = 0; i < childCount; i++) {
12832            PackageParser.Package childPkg = pkg.childPackages.get(i);
12833            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12834        }
12835    }
12836
12837    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12838            int flags) {
12839        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12840        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12841    }
12842
12843    private void updatePermissionsLPw(String changingPkg,
12844            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12845        // Make sure there are no dangling permission trees.
12846        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12847        while (it.hasNext()) {
12848            final BasePermission bp = it.next();
12849            if (bp.packageSetting == null) {
12850                // We may not yet have parsed the package, so just see if
12851                // we still know about its settings.
12852                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12853            }
12854            if (bp.packageSetting == null) {
12855                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12856                        + " from package " + bp.sourcePackage);
12857                it.remove();
12858            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12859                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12860                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12861                            + " from package " + bp.sourcePackage);
12862                    flags |= UPDATE_PERMISSIONS_ALL;
12863                    it.remove();
12864                }
12865            }
12866        }
12867
12868        // Make sure all dynamic permissions have been assigned to a package,
12869        // and make sure there are no dangling permissions.
12870        it = mSettings.mPermissions.values().iterator();
12871        while (it.hasNext()) {
12872            final BasePermission bp = it.next();
12873            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12874                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12875                        + bp.name + " pkg=" + bp.sourcePackage
12876                        + " info=" + bp.pendingInfo);
12877                if (bp.packageSetting == null && bp.pendingInfo != null) {
12878                    final BasePermission tree = findPermissionTreeLP(bp.name);
12879                    if (tree != null && tree.perm != null) {
12880                        bp.packageSetting = tree.packageSetting;
12881                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12882                                new PermissionInfo(bp.pendingInfo));
12883                        bp.perm.info.packageName = tree.perm.info.packageName;
12884                        bp.perm.info.name = bp.name;
12885                        bp.uid = tree.uid;
12886                    }
12887                }
12888            }
12889            if (bp.packageSetting == null) {
12890                // We may not yet have parsed the package, so just see if
12891                // we still know about its settings.
12892                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12893            }
12894            if (bp.packageSetting == null) {
12895                Slog.w(TAG, "Removing dangling permission: " + bp.name
12896                        + " from package " + bp.sourcePackage);
12897                it.remove();
12898            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12899                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12900                    Slog.i(TAG, "Removing old permission: " + bp.name
12901                            + " from package " + bp.sourcePackage);
12902                    flags |= UPDATE_PERMISSIONS_ALL;
12903                    it.remove();
12904                }
12905            }
12906        }
12907
12908        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12909        // Now update the permissions for all packages, in particular
12910        // replace the granted permissions of the system packages.
12911        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12912            for (PackageParser.Package pkg : mPackages.values()) {
12913                if (pkg != pkgInfo) {
12914                    // Only replace for packages on requested volume
12915                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12916                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12917                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12918                    grantPermissionsLPw(pkg, replace, changingPkg);
12919                }
12920            }
12921        }
12922
12923        if (pkgInfo != null) {
12924            // Only replace for packages on requested volume
12925            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12926            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12927                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12928            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12929        }
12930        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12931    }
12932
12933    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12934            String packageOfInterest) {
12935        // IMPORTANT: There are two types of permissions: install and runtime.
12936        // Install time permissions are granted when the app is installed to
12937        // all device users and users added in the future. Runtime permissions
12938        // are granted at runtime explicitly to specific users. Normal and signature
12939        // protected permissions are install time permissions. Dangerous permissions
12940        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12941        // otherwise they are runtime permissions. This function does not manage
12942        // runtime permissions except for the case an app targeting Lollipop MR1
12943        // being upgraded to target a newer SDK, in which case dangerous permissions
12944        // are transformed from install time to runtime ones.
12945
12946        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12947        if (ps == null) {
12948            return;
12949        }
12950
12951        PermissionsState permissionsState = ps.getPermissionsState();
12952        PermissionsState origPermissions = permissionsState;
12953
12954        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12955
12956        boolean runtimePermissionsRevoked = false;
12957        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12958
12959        boolean changedInstallPermission = false;
12960
12961        if (replace) {
12962            ps.installPermissionsFixed = false;
12963            if (!ps.isSharedUser()) {
12964                origPermissions = new PermissionsState(permissionsState);
12965                permissionsState.reset();
12966            } else {
12967                // We need to know only about runtime permission changes since the
12968                // calling code always writes the install permissions state but
12969                // the runtime ones are written only if changed. The only cases of
12970                // changed runtime permissions here are promotion of an install to
12971                // runtime and revocation of a runtime from a shared user.
12972                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12973                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12974                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12975                    runtimePermissionsRevoked = true;
12976                }
12977            }
12978        }
12979
12980        permissionsState.setGlobalGids(mGlobalGids);
12981
12982        final int N = pkg.requestedPermissions.size();
12983        for (int i=0; i<N; i++) {
12984            final String name = pkg.requestedPermissions.get(i);
12985            final BasePermission bp = mSettings.mPermissions.get(name);
12986            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12987                    >= Build.VERSION_CODES.M;
12988
12989            if (DEBUG_INSTALL) {
12990                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12991            }
12992
12993            if (bp == null || bp.packageSetting == null) {
12994                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12995                    if (DEBUG_PERMISSIONS) {
12996                        Slog.i(TAG, "Unknown permission " + name
12997                                + " in package " + pkg.packageName);
12998                    }
12999                }
13000                continue;
13001            }
13002
13003
13004            // Limit ephemeral apps to ephemeral allowed permissions.
13005            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
13006                if (DEBUG_PERMISSIONS) {
13007                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
13008                            + pkg.packageName);
13009                }
13010                continue;
13011            }
13012
13013            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
13014                if (DEBUG_PERMISSIONS) {
13015                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
13016                            + pkg.packageName);
13017                }
13018                continue;
13019            }
13020
13021            final String perm = bp.name;
13022            boolean allowedSig = false;
13023            int grant = GRANT_DENIED;
13024
13025            // Keep track of app op permissions.
13026            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
13027                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
13028                if (pkgs == null) {
13029                    pkgs = new ArraySet<>();
13030                    mAppOpPermissionPackages.put(bp.name, pkgs);
13031                }
13032                pkgs.add(pkg.packageName);
13033            }
13034
13035            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
13036            switch (level) {
13037                case PermissionInfo.PROTECTION_NORMAL: {
13038                    // For all apps normal permissions are install time ones.
13039                    grant = GRANT_INSTALL;
13040                } break;
13041
13042                case PermissionInfo.PROTECTION_DANGEROUS: {
13043                    // If a permission review is required for legacy apps we represent
13044                    // their permissions as always granted runtime ones since we need
13045                    // to keep the review required permission flag per user while an
13046                    // install permission's state is shared across all users.
13047                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
13048                        // For legacy apps dangerous permissions are install time ones.
13049                        grant = GRANT_INSTALL;
13050                    } else if (origPermissions.hasInstallPermission(bp.name)) {
13051                        // For legacy apps that became modern, install becomes runtime.
13052                        grant = GRANT_UPGRADE;
13053                    } else if (mPromoteSystemApps
13054                            && isSystemApp(ps)
13055                            && mExistingSystemPackages.contains(ps.name)) {
13056                        // For legacy system apps, install becomes runtime.
13057                        // We cannot check hasInstallPermission() for system apps since those
13058                        // permissions were granted implicitly and not persisted pre-M.
13059                        grant = GRANT_UPGRADE;
13060                    } else {
13061                        // For modern apps keep runtime permissions unchanged.
13062                        grant = GRANT_RUNTIME;
13063                    }
13064                } break;
13065
13066                case PermissionInfo.PROTECTION_SIGNATURE: {
13067                    // For all apps signature permissions are install time ones.
13068                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
13069                    if (allowedSig) {
13070                        grant = GRANT_INSTALL;
13071                    }
13072                } break;
13073            }
13074
13075            if (DEBUG_PERMISSIONS) {
13076                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
13077            }
13078
13079            if (grant != GRANT_DENIED) {
13080                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
13081                    // If this is an existing, non-system package, then
13082                    // we can't add any new permissions to it.
13083                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
13084                        // Except...  if this is a permission that was added
13085                        // to the platform (note: need to only do this when
13086                        // updating the platform).
13087                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
13088                            grant = GRANT_DENIED;
13089                        }
13090                    }
13091                }
13092
13093                switch (grant) {
13094                    case GRANT_INSTALL: {
13095                        // Revoke this as runtime permission to handle the case of
13096                        // a runtime permission being downgraded to an install one.
13097                        // Also in permission review mode we keep dangerous permissions
13098                        // for legacy apps
13099                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13100                            if (origPermissions.getRuntimePermissionState(
13101                                    bp.name, userId) != null) {
13102                                // Revoke the runtime permission and clear the flags.
13103                                origPermissions.revokeRuntimePermission(bp, userId);
13104                                origPermissions.updatePermissionFlags(bp, userId,
13105                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
13106                                // If we revoked a permission permission, we have to write.
13107                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13108                                        changedRuntimePermissionUserIds, userId);
13109                            }
13110                        }
13111                        // Grant an install permission.
13112                        if (permissionsState.grantInstallPermission(bp) !=
13113                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
13114                            changedInstallPermission = true;
13115                        }
13116                    } break;
13117
13118                    case GRANT_RUNTIME: {
13119                        // Grant previously granted runtime permissions.
13120                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13121                            PermissionState permissionState = origPermissions
13122                                    .getRuntimePermissionState(bp.name, userId);
13123                            int flags = permissionState != null
13124                                    ? permissionState.getFlags() : 0;
13125                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
13126                                // Don't propagate the permission in a permission review mode if
13127                                // the former was revoked, i.e. marked to not propagate on upgrade.
13128                                // Note that in a permission review mode install permissions are
13129                                // represented as constantly granted runtime ones since we need to
13130                                // keep a per user state associated with the permission. Also the
13131                                // revoke on upgrade flag is no longer applicable and is reset.
13132                                final boolean revokeOnUpgrade = (flags & PackageManager
13133                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
13134                                if (revokeOnUpgrade) {
13135                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13136                                    // Since we changed the flags, we have to write.
13137                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13138                                            changedRuntimePermissionUserIds, userId);
13139                                }
13140                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
13141                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
13142                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
13143                                        // If we cannot put the permission as it was,
13144                                        // we have to write.
13145                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13146                                                changedRuntimePermissionUserIds, userId);
13147                                    }
13148                                }
13149
13150                                // If the app supports runtime permissions no need for a review.
13151                                if (mPermissionReviewRequired
13152                                        && appSupportsRuntimePermissions
13153                                        && (flags & PackageManager
13154                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
13155                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
13156                                    // Since we changed the flags, we have to write.
13157                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13158                                            changedRuntimePermissionUserIds, userId);
13159                                }
13160                            } else if (mPermissionReviewRequired
13161                                    && !appSupportsRuntimePermissions) {
13162                                // For legacy apps that need a permission review, every new
13163                                // runtime permission is granted but it is pending a review.
13164                                // We also need to review only platform defined runtime
13165                                // permissions as these are the only ones the platform knows
13166                                // how to disable the API to simulate revocation as legacy
13167                                // apps don't expect to run with revoked permissions.
13168                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
13169                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
13170                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
13171                                        // We changed the flags, hence have to write.
13172                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13173                                                changedRuntimePermissionUserIds, userId);
13174                                    }
13175                                }
13176                                if (permissionsState.grantRuntimePermission(bp, userId)
13177                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13178                                    // We changed the permission, hence have to write.
13179                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13180                                            changedRuntimePermissionUserIds, userId);
13181                                }
13182                            }
13183                            // Propagate the permission flags.
13184                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
13185                        }
13186                    } break;
13187
13188                    case GRANT_UPGRADE: {
13189                        // Grant runtime permissions for a previously held install permission.
13190                        PermissionState permissionState = origPermissions
13191                                .getInstallPermissionState(bp.name);
13192                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
13193
13194                        if (origPermissions.revokeInstallPermission(bp)
13195                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13196                            // We will be transferring the permission flags, so clear them.
13197                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
13198                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
13199                            changedInstallPermission = true;
13200                        }
13201
13202                        // If the permission is not to be promoted to runtime we ignore it and
13203                        // also its other flags as they are not applicable to install permissions.
13204                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
13205                            for (int userId : currentUserIds) {
13206                                if (permissionsState.grantRuntimePermission(bp, userId) !=
13207                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13208                                    // Transfer the permission flags.
13209                                    permissionsState.updatePermissionFlags(bp, userId,
13210                                            flags, flags);
13211                                    // If we granted the permission, we have to write.
13212                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13213                                            changedRuntimePermissionUserIds, userId);
13214                                }
13215                            }
13216                        }
13217                    } break;
13218
13219                    default: {
13220                        if (packageOfInterest == null
13221                                || packageOfInterest.equals(pkg.packageName)) {
13222                            if (DEBUG_PERMISSIONS) {
13223                                Slog.i(TAG, "Not granting permission " + perm
13224                                        + " to package " + pkg.packageName
13225                                        + " because it was previously installed without");
13226                            }
13227                        }
13228                    } break;
13229                }
13230            } else {
13231                if (permissionsState.revokeInstallPermission(bp) !=
13232                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13233                    // Also drop the permission flags.
13234                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13235                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13236                    changedInstallPermission = true;
13237                    Slog.i(TAG, "Un-granting permission " + perm
13238                            + " from package " + pkg.packageName
13239                            + " (protectionLevel=" + bp.protectionLevel
13240                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13241                            + ")");
13242                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13243                    // Don't print warning for app op permissions, since it is fine for them
13244                    // not to be granted, there is a UI for the user to decide.
13245                    if (DEBUG_PERMISSIONS
13246                            && (packageOfInterest == null
13247                                    || packageOfInterest.equals(pkg.packageName))) {
13248                        Slog.i(TAG, "Not granting permission " + perm
13249                                + " to package " + pkg.packageName
13250                                + " (protectionLevel=" + bp.protectionLevel
13251                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13252                                + ")");
13253                    }
13254                }
13255            }
13256        }
13257
13258        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13259                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13260            // This is the first that we have heard about this package, so the
13261            // permissions we have now selected are fixed until explicitly
13262            // changed.
13263            ps.installPermissionsFixed = true;
13264        }
13265
13266        // Persist the runtime permissions state for users with changes. If permissions
13267        // were revoked because no app in the shared user declares them we have to
13268        // write synchronously to avoid losing runtime permissions state.
13269        for (int userId : changedRuntimePermissionUserIds) {
13270            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13271        }
13272    }
13273
13274    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13275        boolean allowed = false;
13276        final int NP = PackageParser.NEW_PERMISSIONS.length;
13277        for (int ip=0; ip<NP; ip++) {
13278            final PackageParser.NewPermissionInfo npi
13279                    = PackageParser.NEW_PERMISSIONS[ip];
13280            if (npi.name.equals(perm)
13281                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13282                allowed = true;
13283                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13284                        + pkg.packageName);
13285                break;
13286            }
13287        }
13288        return allowed;
13289    }
13290
13291    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13292            BasePermission bp, PermissionsState origPermissions) {
13293        boolean privilegedPermission = (bp.protectionLevel
13294                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13295        boolean privappPermissionsDisable =
13296                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13297        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13298        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13299        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13300                && !platformPackage && platformPermission) {
13301            final ArraySet<String> allowedPermissions = SystemConfig.getInstance()
13302                    .getPrivAppPermissions(pkg.packageName);
13303            final boolean whitelisted =
13304                    allowedPermissions != null && allowedPermissions.contains(perm);
13305            if (!whitelisted) {
13306                Slog.w(TAG, "Privileged permission " + perm + " for package "
13307                        + pkg.packageName + " - not in privapp-permissions whitelist");
13308                // Only report violations for apps on system image
13309                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13310                    // it's only a reportable violation if the permission isn't explicitly denied
13311                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
13312                            .getPrivAppDenyPermissions(pkg.packageName);
13313                    final boolean permissionViolation =
13314                            deniedPermissions == null || !deniedPermissions.contains(perm);
13315                    if (permissionViolation) {
13316                        if (mPrivappPermissionsViolations == null) {
13317                            mPrivappPermissionsViolations = new ArraySet<>();
13318                        }
13319                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13320                    } else {
13321                        return false;
13322                    }
13323                }
13324                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13325                    return false;
13326                }
13327            }
13328        }
13329        boolean allowed = (compareSignatures(
13330                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13331                        == PackageManager.SIGNATURE_MATCH)
13332                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13333                        == PackageManager.SIGNATURE_MATCH);
13334        if (!allowed && privilegedPermission) {
13335            if (isSystemApp(pkg)) {
13336                // For updated system applications, a system permission
13337                // is granted only if it had been defined by the original application.
13338                if (pkg.isUpdatedSystemApp()) {
13339                    final PackageSetting sysPs = mSettings
13340                            .getDisabledSystemPkgLPr(pkg.packageName);
13341                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13342                        // If the original was granted this permission, we take
13343                        // that grant decision as read and propagate it to the
13344                        // update.
13345                        if (sysPs.isPrivileged()) {
13346                            allowed = true;
13347                        }
13348                    } else {
13349                        // The system apk may have been updated with an older
13350                        // version of the one on the data partition, but which
13351                        // granted a new system permission that it didn't have
13352                        // before.  In this case we do want to allow the app to
13353                        // now get the new permission if the ancestral apk is
13354                        // privileged to get it.
13355                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13356                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13357                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13358                                    allowed = true;
13359                                    break;
13360                                }
13361                            }
13362                        }
13363                        // Also if a privileged parent package on the system image or any of
13364                        // its children requested a privileged permission, the updated child
13365                        // packages can also get the permission.
13366                        if (pkg.parentPackage != null) {
13367                            final PackageSetting disabledSysParentPs = mSettings
13368                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13369                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13370                                    && disabledSysParentPs.isPrivileged()) {
13371                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13372                                    allowed = true;
13373                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13374                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13375                                    for (int i = 0; i < count; i++) {
13376                                        PackageParser.Package disabledSysChildPkg =
13377                                                disabledSysParentPs.pkg.childPackages.get(i);
13378                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13379                                                perm)) {
13380                                            allowed = true;
13381                                            break;
13382                                        }
13383                                    }
13384                                }
13385                            }
13386                        }
13387                    }
13388                } else {
13389                    allowed = isPrivilegedApp(pkg);
13390                }
13391            }
13392        }
13393        if (!allowed) {
13394            if (!allowed && (bp.protectionLevel
13395                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13396                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13397                // If this was a previously normal/dangerous permission that got moved
13398                // to a system permission as part of the runtime permission redesign, then
13399                // we still want to blindly grant it to old apps.
13400                allowed = true;
13401            }
13402            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13403                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13404                // If this permission is to be granted to the system installer and
13405                // this app is an installer, then it gets the permission.
13406                allowed = true;
13407            }
13408            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13409                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13410                // If this permission is to be granted to the system verifier and
13411                // this app is a verifier, then it gets the permission.
13412                allowed = true;
13413            }
13414            if (!allowed && (bp.protectionLevel
13415                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13416                    && isSystemApp(pkg)) {
13417                // Any pre-installed system app is allowed to get this permission.
13418                allowed = true;
13419            }
13420            if (!allowed && (bp.protectionLevel
13421                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13422                // For development permissions, a development permission
13423                // is granted only if it was already granted.
13424                allowed = origPermissions.hasInstallPermission(perm);
13425            }
13426            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13427                    && pkg.packageName.equals(mSetupWizardPackage)) {
13428                // If this permission is to be granted to the system setup wizard and
13429                // this app is a setup wizard, then it gets the permission.
13430                allowed = true;
13431            }
13432        }
13433        return allowed;
13434    }
13435
13436    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13437        final int permCount = pkg.requestedPermissions.size();
13438        for (int j = 0; j < permCount; j++) {
13439            String requestedPermission = pkg.requestedPermissions.get(j);
13440            if (permission.equals(requestedPermission)) {
13441                return true;
13442            }
13443        }
13444        return false;
13445    }
13446
13447    final class ActivityIntentResolver
13448            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13449        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13450                boolean defaultOnly, int userId) {
13451            if (!sUserManager.exists(userId)) return null;
13452            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13453            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13454        }
13455
13456        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13457                int userId) {
13458            if (!sUserManager.exists(userId)) return null;
13459            mFlags = flags;
13460            return super.queryIntent(intent, resolvedType,
13461                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13462                    userId);
13463        }
13464
13465        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13466                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13467            if (!sUserManager.exists(userId)) return null;
13468            if (packageActivities == null) {
13469                return null;
13470            }
13471            mFlags = flags;
13472            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13473            final int N = packageActivities.size();
13474            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13475                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13476
13477            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13478            for (int i = 0; i < N; ++i) {
13479                intentFilters = packageActivities.get(i).intents;
13480                if (intentFilters != null && intentFilters.size() > 0) {
13481                    PackageParser.ActivityIntentInfo[] array =
13482                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13483                    intentFilters.toArray(array);
13484                    listCut.add(array);
13485                }
13486            }
13487            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13488        }
13489
13490        /**
13491         * Finds a privileged activity that matches the specified activity names.
13492         */
13493        private PackageParser.Activity findMatchingActivity(
13494                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13495            for (PackageParser.Activity sysActivity : activityList) {
13496                if (sysActivity.info.name.equals(activityInfo.name)) {
13497                    return sysActivity;
13498                }
13499                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13500                    return sysActivity;
13501                }
13502                if (sysActivity.info.targetActivity != null) {
13503                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13504                        return sysActivity;
13505                    }
13506                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13507                        return sysActivity;
13508                    }
13509                }
13510            }
13511            return null;
13512        }
13513
13514        public class IterGenerator<E> {
13515            public Iterator<E> generate(ActivityIntentInfo info) {
13516                return null;
13517            }
13518        }
13519
13520        public class ActionIterGenerator extends IterGenerator<String> {
13521            @Override
13522            public Iterator<String> generate(ActivityIntentInfo info) {
13523                return info.actionsIterator();
13524            }
13525        }
13526
13527        public class CategoriesIterGenerator extends IterGenerator<String> {
13528            @Override
13529            public Iterator<String> generate(ActivityIntentInfo info) {
13530                return info.categoriesIterator();
13531            }
13532        }
13533
13534        public class SchemesIterGenerator extends IterGenerator<String> {
13535            @Override
13536            public Iterator<String> generate(ActivityIntentInfo info) {
13537                return info.schemesIterator();
13538            }
13539        }
13540
13541        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13542            @Override
13543            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13544                return info.authoritiesIterator();
13545            }
13546        }
13547
13548        /**
13549         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13550         * MODIFIED. Do not pass in a list that should not be changed.
13551         */
13552        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13553                IterGenerator<T> generator, Iterator<T> searchIterator) {
13554            // loop through the set of actions; every one must be found in the intent filter
13555            while (searchIterator.hasNext()) {
13556                // we must have at least one filter in the list to consider a match
13557                if (intentList.size() == 0) {
13558                    break;
13559                }
13560
13561                final T searchAction = searchIterator.next();
13562
13563                // loop through the set of intent filters
13564                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13565                while (intentIter.hasNext()) {
13566                    final ActivityIntentInfo intentInfo = intentIter.next();
13567                    boolean selectionFound = false;
13568
13569                    // loop through the intent filter's selection criteria; at least one
13570                    // of them must match the searched criteria
13571                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13572                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13573                        final T intentSelection = intentSelectionIter.next();
13574                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13575                            selectionFound = true;
13576                            break;
13577                        }
13578                    }
13579
13580                    // the selection criteria wasn't found in this filter's set; this filter
13581                    // is not a potential match
13582                    if (!selectionFound) {
13583                        intentIter.remove();
13584                    }
13585                }
13586            }
13587        }
13588
13589        private boolean isProtectedAction(ActivityIntentInfo filter) {
13590            final Iterator<String> actionsIter = filter.actionsIterator();
13591            while (actionsIter != null && actionsIter.hasNext()) {
13592                final String filterAction = actionsIter.next();
13593                if (PROTECTED_ACTIONS.contains(filterAction)) {
13594                    return true;
13595                }
13596            }
13597            return false;
13598        }
13599
13600        /**
13601         * Adjusts the priority of the given intent filter according to policy.
13602         * <p>
13603         * <ul>
13604         * <li>The priority for non privileged applications is capped to '0'</li>
13605         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13606         * <li>The priority for unbundled updates to privileged applications is capped to the
13607         *      priority defined on the system partition</li>
13608         * </ul>
13609         * <p>
13610         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13611         * allowed to obtain any priority on any action.
13612         */
13613        private void adjustPriority(
13614                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13615            // nothing to do; priority is fine as-is
13616            if (intent.getPriority() <= 0) {
13617                return;
13618            }
13619
13620            final ActivityInfo activityInfo = intent.activity.info;
13621            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13622
13623            final boolean privilegedApp =
13624                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13625            if (!privilegedApp) {
13626                // non-privileged applications can never define a priority >0
13627                if (DEBUG_FILTERS) {
13628                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13629                            + " package: " + applicationInfo.packageName
13630                            + " activity: " + intent.activity.className
13631                            + " origPrio: " + intent.getPriority());
13632                }
13633                intent.setPriority(0);
13634                return;
13635            }
13636
13637            if (systemActivities == null) {
13638                // the system package is not disabled; we're parsing the system partition
13639                if (isProtectedAction(intent)) {
13640                    if (mDeferProtectedFilters) {
13641                        // We can't deal with these just yet. No component should ever obtain a
13642                        // >0 priority for a protected actions, with ONE exception -- the setup
13643                        // wizard. The setup wizard, however, cannot be known until we're able to
13644                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13645                        // until all intent filters have been processed. Chicken, meet egg.
13646                        // Let the filter temporarily have a high priority and rectify the
13647                        // priorities after all system packages have been scanned.
13648                        mProtectedFilters.add(intent);
13649                        if (DEBUG_FILTERS) {
13650                            Slog.i(TAG, "Protected action; save for later;"
13651                                    + " package: " + applicationInfo.packageName
13652                                    + " activity: " + intent.activity.className
13653                                    + " origPrio: " + intent.getPriority());
13654                        }
13655                        return;
13656                    } else {
13657                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13658                            Slog.i(TAG, "No setup wizard;"
13659                                + " All protected intents capped to priority 0");
13660                        }
13661                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13662                            if (DEBUG_FILTERS) {
13663                                Slog.i(TAG, "Found setup wizard;"
13664                                    + " allow priority " + intent.getPriority() + ";"
13665                                    + " package: " + intent.activity.info.packageName
13666                                    + " activity: " + intent.activity.className
13667                                    + " priority: " + intent.getPriority());
13668                            }
13669                            // setup wizard gets whatever it wants
13670                            return;
13671                        }
13672                        if (DEBUG_FILTERS) {
13673                            Slog.i(TAG, "Protected action; cap priority to 0;"
13674                                    + " package: " + intent.activity.info.packageName
13675                                    + " activity: " + intent.activity.className
13676                                    + " origPrio: " + intent.getPriority());
13677                        }
13678                        intent.setPriority(0);
13679                        return;
13680                    }
13681                }
13682                // privileged apps on the system image get whatever priority they request
13683                return;
13684            }
13685
13686            // privileged app unbundled update ... try to find the same activity
13687            final PackageParser.Activity foundActivity =
13688                    findMatchingActivity(systemActivities, activityInfo);
13689            if (foundActivity == null) {
13690                // this is a new activity; it cannot obtain >0 priority
13691                if (DEBUG_FILTERS) {
13692                    Slog.i(TAG, "New activity; cap priority to 0;"
13693                            + " package: " + applicationInfo.packageName
13694                            + " activity: " + intent.activity.className
13695                            + " origPrio: " + intent.getPriority());
13696                }
13697                intent.setPriority(0);
13698                return;
13699            }
13700
13701            // found activity, now check for filter equivalence
13702
13703            // a shallow copy is enough; we modify the list, not its contents
13704            final List<ActivityIntentInfo> intentListCopy =
13705                    new ArrayList<>(foundActivity.intents);
13706            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13707
13708            // find matching action subsets
13709            final Iterator<String> actionsIterator = intent.actionsIterator();
13710            if (actionsIterator != null) {
13711                getIntentListSubset(
13712                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13713                if (intentListCopy.size() == 0) {
13714                    // no more intents to match; we're not equivalent
13715                    if (DEBUG_FILTERS) {
13716                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13717                                + " package: " + applicationInfo.packageName
13718                                + " activity: " + intent.activity.className
13719                                + " origPrio: " + intent.getPriority());
13720                    }
13721                    intent.setPriority(0);
13722                    return;
13723                }
13724            }
13725
13726            // find matching category subsets
13727            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13728            if (categoriesIterator != null) {
13729                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13730                        categoriesIterator);
13731                if (intentListCopy.size() == 0) {
13732                    // no more intents to match; we're not equivalent
13733                    if (DEBUG_FILTERS) {
13734                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13735                                + " package: " + applicationInfo.packageName
13736                                + " activity: " + intent.activity.className
13737                                + " origPrio: " + intent.getPriority());
13738                    }
13739                    intent.setPriority(0);
13740                    return;
13741                }
13742            }
13743
13744            // find matching schemes subsets
13745            final Iterator<String> schemesIterator = intent.schemesIterator();
13746            if (schemesIterator != null) {
13747                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13748                        schemesIterator);
13749                if (intentListCopy.size() == 0) {
13750                    // no more intents to match; we're not equivalent
13751                    if (DEBUG_FILTERS) {
13752                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13753                                + " package: " + applicationInfo.packageName
13754                                + " activity: " + intent.activity.className
13755                                + " origPrio: " + intent.getPriority());
13756                    }
13757                    intent.setPriority(0);
13758                    return;
13759                }
13760            }
13761
13762            // find matching authorities subsets
13763            final Iterator<IntentFilter.AuthorityEntry>
13764                    authoritiesIterator = intent.authoritiesIterator();
13765            if (authoritiesIterator != null) {
13766                getIntentListSubset(intentListCopy,
13767                        new AuthoritiesIterGenerator(),
13768                        authoritiesIterator);
13769                if (intentListCopy.size() == 0) {
13770                    // no more intents to match; we're not equivalent
13771                    if (DEBUG_FILTERS) {
13772                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13773                                + " package: " + applicationInfo.packageName
13774                                + " activity: " + intent.activity.className
13775                                + " origPrio: " + intent.getPriority());
13776                    }
13777                    intent.setPriority(0);
13778                    return;
13779                }
13780            }
13781
13782            // we found matching filter(s); app gets the max priority of all intents
13783            int cappedPriority = 0;
13784            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13785                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13786            }
13787            if (intent.getPriority() > cappedPriority) {
13788                if (DEBUG_FILTERS) {
13789                    Slog.i(TAG, "Found matching filter(s);"
13790                            + " cap priority to " + cappedPriority + ";"
13791                            + " package: " + applicationInfo.packageName
13792                            + " activity: " + intent.activity.className
13793                            + " origPrio: " + intent.getPriority());
13794                }
13795                intent.setPriority(cappedPriority);
13796                return;
13797            }
13798            // all this for nothing; the requested priority was <= what was on the system
13799        }
13800
13801        public final void addActivity(PackageParser.Activity a, String type) {
13802            mActivities.put(a.getComponentName(), a);
13803            if (DEBUG_SHOW_INFO)
13804                Log.v(
13805                TAG, "  " + type + " " +
13806                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13807            if (DEBUG_SHOW_INFO)
13808                Log.v(TAG, "    Class=" + a.info.name);
13809            final int NI = a.intents.size();
13810            for (int j=0; j<NI; j++) {
13811                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13812                if ("activity".equals(type)) {
13813                    final PackageSetting ps =
13814                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13815                    final List<PackageParser.Activity> systemActivities =
13816                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13817                    adjustPriority(systemActivities, intent);
13818                }
13819                if (DEBUG_SHOW_INFO) {
13820                    Log.v(TAG, "    IntentFilter:");
13821                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13822                }
13823                if (!intent.debugCheck()) {
13824                    Log.w(TAG, "==> For Activity " + a.info.name);
13825                }
13826                addFilter(intent);
13827            }
13828        }
13829
13830        public final void removeActivity(PackageParser.Activity a, String type) {
13831            mActivities.remove(a.getComponentName());
13832            if (DEBUG_SHOW_INFO) {
13833                Log.v(TAG, "  " + type + " "
13834                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13835                                : a.info.name) + ":");
13836                Log.v(TAG, "    Class=" + a.info.name);
13837            }
13838            final int NI = a.intents.size();
13839            for (int j=0; j<NI; j++) {
13840                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13841                if (DEBUG_SHOW_INFO) {
13842                    Log.v(TAG, "    IntentFilter:");
13843                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13844                }
13845                removeFilter(intent);
13846            }
13847        }
13848
13849        @Override
13850        protected boolean allowFilterResult(
13851                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13852            ActivityInfo filterAi = filter.activity.info;
13853            for (int i=dest.size()-1; i>=0; i--) {
13854                ActivityInfo destAi = dest.get(i).activityInfo;
13855                if (destAi.name == filterAi.name
13856                        && destAi.packageName == filterAi.packageName) {
13857                    return false;
13858                }
13859            }
13860            return true;
13861        }
13862
13863        @Override
13864        protected ActivityIntentInfo[] newArray(int size) {
13865            return new ActivityIntentInfo[size];
13866        }
13867
13868        @Override
13869        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13870            if (!sUserManager.exists(userId)) return true;
13871            PackageParser.Package p = filter.activity.owner;
13872            if (p != null) {
13873                PackageSetting ps = (PackageSetting)p.mExtras;
13874                if (ps != null) {
13875                    // System apps are never considered stopped for purposes of
13876                    // filtering, because there may be no way for the user to
13877                    // actually re-launch them.
13878                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13879                            && ps.getStopped(userId);
13880                }
13881            }
13882            return false;
13883        }
13884
13885        @Override
13886        protected boolean isPackageForFilter(String packageName,
13887                PackageParser.ActivityIntentInfo info) {
13888            return packageName.equals(info.activity.owner.packageName);
13889        }
13890
13891        @Override
13892        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13893                int match, int userId) {
13894            if (!sUserManager.exists(userId)) return null;
13895            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13896                return null;
13897            }
13898            final PackageParser.Activity activity = info.activity;
13899            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13900            if (ps == null) {
13901                return null;
13902            }
13903            final PackageUserState userState = ps.readUserState(userId);
13904            ActivityInfo ai =
13905                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13906            if (ai == null) {
13907                return null;
13908            }
13909            final boolean matchExplicitlyVisibleOnly =
13910                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13911            final boolean matchVisibleToInstantApp =
13912                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13913            final boolean componentVisible =
13914                    matchVisibleToInstantApp
13915                    && info.isVisibleToInstantApp()
13916                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13917            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13918            // throw out filters that aren't visible to ephemeral apps
13919            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13920                return null;
13921            }
13922            // throw out instant app filters if we're not explicitly requesting them
13923            if (!matchInstantApp && userState.instantApp) {
13924                return null;
13925            }
13926            // throw out instant app filters if updates are available; will trigger
13927            // instant app resolution
13928            if (userState.instantApp && ps.isUpdateAvailable()) {
13929                return null;
13930            }
13931            final ResolveInfo res = new ResolveInfo();
13932            res.activityInfo = ai;
13933            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13934                res.filter = info;
13935            }
13936            if (info != null) {
13937                res.handleAllWebDataURI = info.handleAllWebDataURI();
13938            }
13939            res.priority = info.getPriority();
13940            res.preferredOrder = activity.owner.mPreferredOrder;
13941            //System.out.println("Result: " + res.activityInfo.className +
13942            //                   " = " + res.priority);
13943            res.match = match;
13944            res.isDefault = info.hasDefault;
13945            res.labelRes = info.labelRes;
13946            res.nonLocalizedLabel = info.nonLocalizedLabel;
13947            if (userNeedsBadging(userId)) {
13948                res.noResourceId = true;
13949            } else {
13950                res.icon = info.icon;
13951            }
13952            res.iconResourceId = info.icon;
13953            res.system = res.activityInfo.applicationInfo.isSystemApp();
13954            res.isInstantAppAvailable = userState.instantApp;
13955            return res;
13956        }
13957
13958        @Override
13959        protected void sortResults(List<ResolveInfo> results) {
13960            Collections.sort(results, mResolvePrioritySorter);
13961        }
13962
13963        @Override
13964        protected void dumpFilter(PrintWriter out, String prefix,
13965                PackageParser.ActivityIntentInfo filter) {
13966            out.print(prefix); out.print(
13967                    Integer.toHexString(System.identityHashCode(filter.activity)));
13968                    out.print(' ');
13969                    filter.activity.printComponentShortName(out);
13970                    out.print(" filter ");
13971                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13972        }
13973
13974        @Override
13975        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13976            return filter.activity;
13977        }
13978
13979        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13980            PackageParser.Activity activity = (PackageParser.Activity)label;
13981            out.print(prefix); out.print(
13982                    Integer.toHexString(System.identityHashCode(activity)));
13983                    out.print(' ');
13984                    activity.printComponentShortName(out);
13985            if (count > 1) {
13986                out.print(" ("); out.print(count); out.print(" filters)");
13987            }
13988            out.println();
13989        }
13990
13991        // Keys are String (activity class name), values are Activity.
13992        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13993                = new ArrayMap<ComponentName, PackageParser.Activity>();
13994        private int mFlags;
13995    }
13996
13997    private final class ServiceIntentResolver
13998            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13999        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14000                boolean defaultOnly, int userId) {
14001            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14002            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14003        }
14004
14005        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14006                int userId) {
14007            if (!sUserManager.exists(userId)) return null;
14008            mFlags = flags;
14009            return super.queryIntent(intent, resolvedType,
14010                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14011                    userId);
14012        }
14013
14014        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14015                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
14016            if (!sUserManager.exists(userId)) return null;
14017            if (packageServices == null) {
14018                return null;
14019            }
14020            mFlags = flags;
14021            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
14022            final int N = packageServices.size();
14023            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
14024                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
14025
14026            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
14027            for (int i = 0; i < N; ++i) {
14028                intentFilters = packageServices.get(i).intents;
14029                if (intentFilters != null && intentFilters.size() > 0) {
14030                    PackageParser.ServiceIntentInfo[] array =
14031                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
14032                    intentFilters.toArray(array);
14033                    listCut.add(array);
14034                }
14035            }
14036            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14037        }
14038
14039        public final void addService(PackageParser.Service s) {
14040            mServices.put(s.getComponentName(), s);
14041            if (DEBUG_SHOW_INFO) {
14042                Log.v(TAG, "  "
14043                        + (s.info.nonLocalizedLabel != null
14044                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14045                Log.v(TAG, "    Class=" + s.info.name);
14046            }
14047            final int NI = s.intents.size();
14048            int j;
14049            for (j=0; j<NI; j++) {
14050                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14051                if (DEBUG_SHOW_INFO) {
14052                    Log.v(TAG, "    IntentFilter:");
14053                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14054                }
14055                if (!intent.debugCheck()) {
14056                    Log.w(TAG, "==> For Service " + s.info.name);
14057                }
14058                addFilter(intent);
14059            }
14060        }
14061
14062        public final void removeService(PackageParser.Service s) {
14063            mServices.remove(s.getComponentName());
14064            if (DEBUG_SHOW_INFO) {
14065                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
14066                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14067                Log.v(TAG, "    Class=" + s.info.name);
14068            }
14069            final int NI = s.intents.size();
14070            int j;
14071            for (j=0; j<NI; j++) {
14072                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14073                if (DEBUG_SHOW_INFO) {
14074                    Log.v(TAG, "    IntentFilter:");
14075                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14076                }
14077                removeFilter(intent);
14078            }
14079        }
14080
14081        @Override
14082        protected boolean allowFilterResult(
14083                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
14084            ServiceInfo filterSi = filter.service.info;
14085            for (int i=dest.size()-1; i>=0; i--) {
14086                ServiceInfo destAi = dest.get(i).serviceInfo;
14087                if (destAi.name == filterSi.name
14088                        && destAi.packageName == filterSi.packageName) {
14089                    return false;
14090                }
14091            }
14092            return true;
14093        }
14094
14095        @Override
14096        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
14097            return new PackageParser.ServiceIntentInfo[size];
14098        }
14099
14100        @Override
14101        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
14102            if (!sUserManager.exists(userId)) return true;
14103            PackageParser.Package p = filter.service.owner;
14104            if (p != null) {
14105                PackageSetting ps = (PackageSetting)p.mExtras;
14106                if (ps != null) {
14107                    // System apps are never considered stopped for purposes of
14108                    // filtering, because there may be no way for the user to
14109                    // actually re-launch them.
14110                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14111                            && ps.getStopped(userId);
14112                }
14113            }
14114            return false;
14115        }
14116
14117        @Override
14118        protected boolean isPackageForFilter(String packageName,
14119                PackageParser.ServiceIntentInfo info) {
14120            return packageName.equals(info.service.owner.packageName);
14121        }
14122
14123        @Override
14124        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
14125                int match, int userId) {
14126            if (!sUserManager.exists(userId)) return null;
14127            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
14128            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
14129                return null;
14130            }
14131            final PackageParser.Service service = info.service;
14132            PackageSetting ps = (PackageSetting) service.owner.mExtras;
14133            if (ps == null) {
14134                return null;
14135            }
14136            final PackageUserState userState = ps.readUserState(userId);
14137            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
14138                    userState, userId);
14139            if (si == null) {
14140                return null;
14141            }
14142            final boolean matchVisibleToInstantApp =
14143                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14144            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14145            // throw out filters that aren't visible to ephemeral apps
14146            if (matchVisibleToInstantApp
14147                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14148                return null;
14149            }
14150            // throw out ephemeral filters if we're not explicitly requesting them
14151            if (!isInstantApp && userState.instantApp) {
14152                return null;
14153            }
14154            // throw out instant app filters if updates are available; will trigger
14155            // instant app resolution
14156            if (userState.instantApp && ps.isUpdateAvailable()) {
14157                return null;
14158            }
14159            final ResolveInfo res = new ResolveInfo();
14160            res.serviceInfo = si;
14161            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
14162                res.filter = filter;
14163            }
14164            res.priority = info.getPriority();
14165            res.preferredOrder = service.owner.mPreferredOrder;
14166            res.match = match;
14167            res.isDefault = info.hasDefault;
14168            res.labelRes = info.labelRes;
14169            res.nonLocalizedLabel = info.nonLocalizedLabel;
14170            res.icon = info.icon;
14171            res.system = res.serviceInfo.applicationInfo.isSystemApp();
14172            return res;
14173        }
14174
14175        @Override
14176        protected void sortResults(List<ResolveInfo> results) {
14177            Collections.sort(results, mResolvePrioritySorter);
14178        }
14179
14180        @Override
14181        protected void dumpFilter(PrintWriter out, String prefix,
14182                PackageParser.ServiceIntentInfo filter) {
14183            out.print(prefix); out.print(
14184                    Integer.toHexString(System.identityHashCode(filter.service)));
14185                    out.print(' ');
14186                    filter.service.printComponentShortName(out);
14187                    out.print(" filter ");
14188                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14189        }
14190
14191        @Override
14192        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14193            return filter.service;
14194        }
14195
14196        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14197            PackageParser.Service service = (PackageParser.Service)label;
14198            out.print(prefix); out.print(
14199                    Integer.toHexString(System.identityHashCode(service)));
14200                    out.print(' ');
14201                    service.printComponentShortName(out);
14202            if (count > 1) {
14203                out.print(" ("); out.print(count); out.print(" filters)");
14204            }
14205            out.println();
14206        }
14207
14208//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14209//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14210//            final List<ResolveInfo> retList = Lists.newArrayList();
14211//            while (i.hasNext()) {
14212//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14213//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14214//                    retList.add(resolveInfo);
14215//                }
14216//            }
14217//            return retList;
14218//        }
14219
14220        // Keys are String (activity class name), values are Activity.
14221        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14222                = new ArrayMap<ComponentName, PackageParser.Service>();
14223        private int mFlags;
14224    }
14225
14226    private final class ProviderIntentResolver
14227            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14228        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14229                boolean defaultOnly, int userId) {
14230            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14231            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14232        }
14233
14234        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14235                int userId) {
14236            if (!sUserManager.exists(userId))
14237                return null;
14238            mFlags = flags;
14239            return super.queryIntent(intent, resolvedType,
14240                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14241                    userId);
14242        }
14243
14244        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14245                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14246            if (!sUserManager.exists(userId))
14247                return null;
14248            if (packageProviders == null) {
14249                return null;
14250            }
14251            mFlags = flags;
14252            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14253            final int N = packageProviders.size();
14254            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14255                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14256
14257            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14258            for (int i = 0; i < N; ++i) {
14259                intentFilters = packageProviders.get(i).intents;
14260                if (intentFilters != null && intentFilters.size() > 0) {
14261                    PackageParser.ProviderIntentInfo[] array =
14262                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14263                    intentFilters.toArray(array);
14264                    listCut.add(array);
14265                }
14266            }
14267            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14268        }
14269
14270        public final void addProvider(PackageParser.Provider p) {
14271            if (mProviders.containsKey(p.getComponentName())) {
14272                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14273                return;
14274            }
14275
14276            mProviders.put(p.getComponentName(), p);
14277            if (DEBUG_SHOW_INFO) {
14278                Log.v(TAG, "  "
14279                        + (p.info.nonLocalizedLabel != null
14280                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14281                Log.v(TAG, "    Class=" + p.info.name);
14282            }
14283            final int NI = p.intents.size();
14284            int j;
14285            for (j = 0; j < NI; j++) {
14286                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14287                if (DEBUG_SHOW_INFO) {
14288                    Log.v(TAG, "    IntentFilter:");
14289                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14290                }
14291                if (!intent.debugCheck()) {
14292                    Log.w(TAG, "==> For Provider " + p.info.name);
14293                }
14294                addFilter(intent);
14295            }
14296        }
14297
14298        public final void removeProvider(PackageParser.Provider p) {
14299            mProviders.remove(p.getComponentName());
14300            if (DEBUG_SHOW_INFO) {
14301                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14302                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14303                Log.v(TAG, "    Class=" + p.info.name);
14304            }
14305            final int NI = p.intents.size();
14306            int j;
14307            for (j = 0; j < NI; j++) {
14308                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14309                if (DEBUG_SHOW_INFO) {
14310                    Log.v(TAG, "    IntentFilter:");
14311                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14312                }
14313                removeFilter(intent);
14314            }
14315        }
14316
14317        @Override
14318        protected boolean allowFilterResult(
14319                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14320            ProviderInfo filterPi = filter.provider.info;
14321            for (int i = dest.size() - 1; i >= 0; i--) {
14322                ProviderInfo destPi = dest.get(i).providerInfo;
14323                if (destPi.name == filterPi.name
14324                        && destPi.packageName == filterPi.packageName) {
14325                    return false;
14326                }
14327            }
14328            return true;
14329        }
14330
14331        @Override
14332        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14333            return new PackageParser.ProviderIntentInfo[size];
14334        }
14335
14336        @Override
14337        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14338            if (!sUserManager.exists(userId))
14339                return true;
14340            PackageParser.Package p = filter.provider.owner;
14341            if (p != null) {
14342                PackageSetting ps = (PackageSetting) p.mExtras;
14343                if (ps != null) {
14344                    // System apps are never considered stopped for purposes of
14345                    // filtering, because there may be no way for the user to
14346                    // actually re-launch them.
14347                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14348                            && ps.getStopped(userId);
14349                }
14350            }
14351            return false;
14352        }
14353
14354        @Override
14355        protected boolean isPackageForFilter(String packageName,
14356                PackageParser.ProviderIntentInfo info) {
14357            return packageName.equals(info.provider.owner.packageName);
14358        }
14359
14360        @Override
14361        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14362                int match, int userId) {
14363            if (!sUserManager.exists(userId))
14364                return null;
14365            final PackageParser.ProviderIntentInfo info = filter;
14366            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14367                return null;
14368            }
14369            final PackageParser.Provider provider = info.provider;
14370            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14371            if (ps == null) {
14372                return null;
14373            }
14374            final PackageUserState userState = ps.readUserState(userId);
14375            final boolean matchVisibleToInstantApp =
14376                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14377            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14378            // throw out filters that aren't visible to instant applications
14379            if (matchVisibleToInstantApp
14380                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14381                return null;
14382            }
14383            // throw out instant application filters if we're not explicitly requesting them
14384            if (!isInstantApp && userState.instantApp) {
14385                return null;
14386            }
14387            // throw out instant application filters if updates are available; will trigger
14388            // instant application resolution
14389            if (userState.instantApp && ps.isUpdateAvailable()) {
14390                return null;
14391            }
14392            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14393                    userState, userId);
14394            if (pi == null) {
14395                return null;
14396            }
14397            final ResolveInfo res = new ResolveInfo();
14398            res.providerInfo = pi;
14399            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14400                res.filter = filter;
14401            }
14402            res.priority = info.getPriority();
14403            res.preferredOrder = provider.owner.mPreferredOrder;
14404            res.match = match;
14405            res.isDefault = info.hasDefault;
14406            res.labelRes = info.labelRes;
14407            res.nonLocalizedLabel = info.nonLocalizedLabel;
14408            res.icon = info.icon;
14409            res.system = res.providerInfo.applicationInfo.isSystemApp();
14410            return res;
14411        }
14412
14413        @Override
14414        protected void sortResults(List<ResolveInfo> results) {
14415            Collections.sort(results, mResolvePrioritySorter);
14416        }
14417
14418        @Override
14419        protected void dumpFilter(PrintWriter out, String prefix,
14420                PackageParser.ProviderIntentInfo filter) {
14421            out.print(prefix);
14422            out.print(
14423                    Integer.toHexString(System.identityHashCode(filter.provider)));
14424            out.print(' ');
14425            filter.provider.printComponentShortName(out);
14426            out.print(" filter ");
14427            out.println(Integer.toHexString(System.identityHashCode(filter)));
14428        }
14429
14430        @Override
14431        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14432            return filter.provider;
14433        }
14434
14435        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14436            PackageParser.Provider provider = (PackageParser.Provider)label;
14437            out.print(prefix); out.print(
14438                    Integer.toHexString(System.identityHashCode(provider)));
14439                    out.print(' ');
14440                    provider.printComponentShortName(out);
14441            if (count > 1) {
14442                out.print(" ("); out.print(count); out.print(" filters)");
14443            }
14444            out.println();
14445        }
14446
14447        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14448                = new ArrayMap<ComponentName, PackageParser.Provider>();
14449        private int mFlags;
14450    }
14451
14452    static final class EphemeralIntentResolver
14453            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14454        /**
14455         * The result that has the highest defined order. Ordering applies on a
14456         * per-package basis. Mapping is from package name to Pair of order and
14457         * EphemeralResolveInfo.
14458         * <p>
14459         * NOTE: This is implemented as a field variable for convenience and efficiency.
14460         * By having a field variable, we're able to track filter ordering as soon as
14461         * a non-zero order is defined. Otherwise, multiple loops across the result set
14462         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14463         * this needs to be contained entirely within {@link #filterResults}.
14464         */
14465        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14466
14467        @Override
14468        protected AuxiliaryResolveInfo[] newArray(int size) {
14469            return new AuxiliaryResolveInfo[size];
14470        }
14471
14472        @Override
14473        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14474            return true;
14475        }
14476
14477        @Override
14478        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14479                int userId) {
14480            if (!sUserManager.exists(userId)) {
14481                return null;
14482            }
14483            final String packageName = responseObj.resolveInfo.getPackageName();
14484            final Integer order = responseObj.getOrder();
14485            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14486                    mOrderResult.get(packageName);
14487            // ordering is enabled and this item's order isn't high enough
14488            if (lastOrderResult != null && lastOrderResult.first >= order) {
14489                return null;
14490            }
14491            final InstantAppResolveInfo res = responseObj.resolveInfo;
14492            if (order > 0) {
14493                // non-zero order, enable ordering
14494                mOrderResult.put(packageName, new Pair<>(order, res));
14495            }
14496            return responseObj;
14497        }
14498
14499        @Override
14500        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14501            // only do work if ordering is enabled [most of the time it won't be]
14502            if (mOrderResult.size() == 0) {
14503                return;
14504            }
14505            int resultSize = results.size();
14506            for (int i = 0; i < resultSize; i++) {
14507                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14508                final String packageName = info.getPackageName();
14509                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14510                if (savedInfo == null) {
14511                    // package doesn't having ordering
14512                    continue;
14513                }
14514                if (savedInfo.second == info) {
14515                    // circled back to the highest ordered item; remove from order list
14516                    mOrderResult.remove(packageName);
14517                    if (mOrderResult.size() == 0) {
14518                        // no more ordered items
14519                        break;
14520                    }
14521                    continue;
14522                }
14523                // item has a worse order, remove it from the result list
14524                results.remove(i);
14525                resultSize--;
14526                i--;
14527            }
14528        }
14529    }
14530
14531    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14532            new Comparator<ResolveInfo>() {
14533        public int compare(ResolveInfo r1, ResolveInfo r2) {
14534            int v1 = r1.priority;
14535            int v2 = r2.priority;
14536            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14537            if (v1 != v2) {
14538                return (v1 > v2) ? -1 : 1;
14539            }
14540            v1 = r1.preferredOrder;
14541            v2 = r2.preferredOrder;
14542            if (v1 != v2) {
14543                return (v1 > v2) ? -1 : 1;
14544            }
14545            if (r1.isDefault != r2.isDefault) {
14546                return r1.isDefault ? -1 : 1;
14547            }
14548            v1 = r1.match;
14549            v2 = r2.match;
14550            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14551            if (v1 != v2) {
14552                return (v1 > v2) ? -1 : 1;
14553            }
14554            if (r1.system != r2.system) {
14555                return r1.system ? -1 : 1;
14556            }
14557            if (r1.activityInfo != null) {
14558                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14559            }
14560            if (r1.serviceInfo != null) {
14561                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14562            }
14563            if (r1.providerInfo != null) {
14564                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14565            }
14566            return 0;
14567        }
14568    };
14569
14570    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14571            new Comparator<ProviderInfo>() {
14572        public int compare(ProviderInfo p1, ProviderInfo p2) {
14573            final int v1 = p1.initOrder;
14574            final int v2 = p2.initOrder;
14575            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14576        }
14577    };
14578
14579    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14580            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14581            final int[] userIds) {
14582        mHandler.post(new Runnable() {
14583            @Override
14584            public void run() {
14585                try {
14586                    final IActivityManager am = ActivityManager.getService();
14587                    if (am == null) return;
14588                    final int[] resolvedUserIds;
14589                    if (userIds == null) {
14590                        resolvedUserIds = am.getRunningUserIds();
14591                    } else {
14592                        resolvedUserIds = userIds;
14593                    }
14594                    for (int id : resolvedUserIds) {
14595                        final Intent intent = new Intent(action,
14596                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14597                        if (extras != null) {
14598                            intent.putExtras(extras);
14599                        }
14600                        if (targetPkg != null) {
14601                            intent.setPackage(targetPkg);
14602                        }
14603                        // Modify the UID when posting to other users
14604                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14605                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14606                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14607                            intent.putExtra(Intent.EXTRA_UID, uid);
14608                        }
14609                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14610                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14611                        if (DEBUG_BROADCASTS) {
14612                            RuntimeException here = new RuntimeException("here");
14613                            here.fillInStackTrace();
14614                            Slog.d(TAG, "Sending to user " + id + ": "
14615                                    + intent.toShortString(false, true, false, false)
14616                                    + " " + intent.getExtras(), here);
14617                        }
14618                        am.broadcastIntent(null, intent, null, finishedReceiver,
14619                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14620                                null, finishedReceiver != null, false, id);
14621                    }
14622                } catch (RemoteException ex) {
14623                }
14624            }
14625        });
14626    }
14627
14628    /**
14629     * Check if the external storage media is available. This is true if there
14630     * is a mounted external storage medium or if the external storage is
14631     * emulated.
14632     */
14633    private boolean isExternalMediaAvailable() {
14634        return mMediaMounted || Environment.isExternalStorageEmulated();
14635    }
14636
14637    @Override
14638    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14639        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14640            return null;
14641        }
14642        if (!isExternalMediaAvailable()) {
14643                // If the external storage is no longer mounted at this point,
14644                // the caller may not have been able to delete all of this
14645                // packages files and can not delete any more.  Bail.
14646            return null;
14647        }
14648        synchronized (mPackages) {
14649            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14650            if (lastPackage != null) {
14651                pkgs.remove(lastPackage);
14652            }
14653            if (pkgs.size() > 0) {
14654                return pkgs.get(0);
14655            }
14656        }
14657        return null;
14658    }
14659
14660    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14661        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14662                userId, andCode ? 1 : 0, packageName);
14663        if (mSystemReady) {
14664            msg.sendToTarget();
14665        } else {
14666            if (mPostSystemReadyMessages == null) {
14667                mPostSystemReadyMessages = new ArrayList<>();
14668            }
14669            mPostSystemReadyMessages.add(msg);
14670        }
14671    }
14672
14673    void startCleaningPackages() {
14674        // reader
14675        if (!isExternalMediaAvailable()) {
14676            return;
14677        }
14678        synchronized (mPackages) {
14679            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14680                return;
14681            }
14682        }
14683        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14684        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14685        IActivityManager am = ActivityManager.getService();
14686        if (am != null) {
14687            int dcsUid = -1;
14688            synchronized (mPackages) {
14689                if (!mDefaultContainerWhitelisted) {
14690                    mDefaultContainerWhitelisted = true;
14691                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14692                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14693                }
14694            }
14695            try {
14696                if (dcsUid > 0) {
14697                    am.backgroundWhitelistUid(dcsUid);
14698                }
14699                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14700                        UserHandle.USER_SYSTEM);
14701            } catch (RemoteException e) {
14702            }
14703        }
14704    }
14705
14706    @Override
14707    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14708            int installFlags, String installerPackageName, int userId) {
14709        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14710
14711        final int callingUid = Binder.getCallingUid();
14712        enforceCrossUserPermission(callingUid, userId,
14713                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14714
14715        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14716            try {
14717                if (observer != null) {
14718                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14719                }
14720            } catch (RemoteException re) {
14721            }
14722            return;
14723        }
14724
14725        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14726            installFlags |= PackageManager.INSTALL_FROM_ADB;
14727
14728        } else {
14729            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14730            // about installerPackageName.
14731
14732            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14733            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14734        }
14735
14736        UserHandle user;
14737        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14738            user = UserHandle.ALL;
14739        } else {
14740            user = new UserHandle(userId);
14741        }
14742
14743        // Only system components can circumvent runtime permissions when installing.
14744        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14745                && mContext.checkCallingOrSelfPermission(Manifest.permission
14746                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14747            throw new SecurityException("You need the "
14748                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14749                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14750        }
14751
14752        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14753                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14754            throw new IllegalArgumentException(
14755                    "New installs into ASEC containers no longer supported");
14756        }
14757
14758        final File originFile = new File(originPath);
14759        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14760
14761        final Message msg = mHandler.obtainMessage(INIT_COPY);
14762        final VerificationInfo verificationInfo = new VerificationInfo(
14763                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14764        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14765                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14766                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14767                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14768        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14769        msg.obj = params;
14770
14771        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14772                System.identityHashCode(msg.obj));
14773        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14774                System.identityHashCode(msg.obj));
14775
14776        mHandler.sendMessage(msg);
14777    }
14778
14779
14780    /**
14781     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14782     * it is acting on behalf on an enterprise or the user).
14783     *
14784     * Note that the ordering of the conditionals in this method is important. The checks we perform
14785     * are as follows, in this order:
14786     *
14787     * 1) If the install is being performed by a system app, we can trust the app to have set the
14788     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14789     *    what it is.
14790     * 2) If the install is being performed by a device or profile owner app, the install reason
14791     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14792     *    set the install reason correctly. If the app targets an older SDK version where install
14793     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14794     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14795     * 3) In all other cases, the install is being performed by a regular app that is neither part
14796     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14797     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14798     *    set to enterprise policy and if so, change it to unknown instead.
14799     */
14800    private int fixUpInstallReason(String installerPackageName, int installerUid,
14801            int installReason) {
14802        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14803                == PERMISSION_GRANTED) {
14804            // If the install is being performed by a system app, we trust that app to have set the
14805            // install reason correctly.
14806            return installReason;
14807        }
14808
14809        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14810            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14811        if (dpm != null) {
14812            ComponentName owner = null;
14813            try {
14814                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14815                if (owner == null) {
14816                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14817                }
14818            } catch (RemoteException e) {
14819            }
14820            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14821                // If the install is being performed by a device or profile owner, the install
14822                // reason should be enterprise policy.
14823                return PackageManager.INSTALL_REASON_POLICY;
14824            }
14825        }
14826
14827        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14828            // If the install is being performed by a regular app (i.e. neither system app nor
14829            // device or profile owner), we have no reason to believe that the app is acting on
14830            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14831            // change it to unknown instead.
14832            return PackageManager.INSTALL_REASON_UNKNOWN;
14833        }
14834
14835        // If the install is being performed by a regular app and the install reason was set to any
14836        // value but enterprise policy, leave the install reason unchanged.
14837        return installReason;
14838    }
14839
14840    void installStage(String packageName, File stagedDir, String stagedCid,
14841            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14842            String installerPackageName, int installerUid, UserHandle user,
14843            Certificate[][] certificates) {
14844        if (DEBUG_EPHEMERAL) {
14845            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14846                Slog.d(TAG, "Ephemeral install of " + packageName);
14847            }
14848        }
14849        final VerificationInfo verificationInfo = new VerificationInfo(
14850                sessionParams.originatingUri, sessionParams.referrerUri,
14851                sessionParams.originatingUid, installerUid);
14852
14853        final OriginInfo origin;
14854        if (stagedDir != null) {
14855            origin = OriginInfo.fromStagedFile(stagedDir);
14856        } else {
14857            origin = OriginInfo.fromStagedContainer(stagedCid);
14858        }
14859
14860        final Message msg = mHandler.obtainMessage(INIT_COPY);
14861        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14862                sessionParams.installReason);
14863        final InstallParams params = new InstallParams(origin, null, observer,
14864                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14865                verificationInfo, user, sessionParams.abiOverride,
14866                sessionParams.grantedRuntimePermissions, certificates, installReason);
14867        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14868        msg.obj = params;
14869
14870        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14871                System.identityHashCode(msg.obj));
14872        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14873                System.identityHashCode(msg.obj));
14874
14875        mHandler.sendMessage(msg);
14876    }
14877
14878    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14879            int userId) {
14880        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14881        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14882                false /*startReceiver*/, pkgSetting.appId, userId);
14883
14884        // Send a session commit broadcast
14885        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14886        info.installReason = pkgSetting.getInstallReason(userId);
14887        info.appPackageName = packageName;
14888        sendSessionCommitBroadcast(info, userId);
14889    }
14890
14891    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14892            boolean includeStopped, int appId, int... userIds) {
14893        if (ArrayUtils.isEmpty(userIds)) {
14894            return;
14895        }
14896        Bundle extras = new Bundle(1);
14897        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14898        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14899
14900        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14901                packageName, extras, 0, null, null, userIds);
14902        if (sendBootCompleted) {
14903            mHandler.post(() -> {
14904                        for (int userId : userIds) {
14905                            sendBootCompletedBroadcastToSystemApp(
14906                                    packageName, includeStopped, userId);
14907                        }
14908                    }
14909            );
14910        }
14911    }
14912
14913    /**
14914     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14915     * automatically without needing an explicit launch.
14916     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14917     */
14918    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14919            int userId) {
14920        // If user is not running, the app didn't miss any broadcast
14921        if (!mUserManagerInternal.isUserRunning(userId)) {
14922            return;
14923        }
14924        final IActivityManager am = ActivityManager.getService();
14925        try {
14926            // Deliver LOCKED_BOOT_COMPLETED first
14927            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14928                    .setPackage(packageName);
14929            if (includeStopped) {
14930                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14931            }
14932            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14933            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14934                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14935
14936            // Deliver BOOT_COMPLETED only if user is unlocked
14937            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14938                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14939                if (includeStopped) {
14940                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14941                }
14942                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14943                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14944            }
14945        } catch (RemoteException e) {
14946            throw e.rethrowFromSystemServer();
14947        }
14948    }
14949
14950    @Override
14951    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14952            int userId) {
14953        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14954        PackageSetting pkgSetting;
14955        final int callingUid = Binder.getCallingUid();
14956        enforceCrossUserPermission(callingUid, userId,
14957                true /* requireFullPermission */, true /* checkShell */,
14958                "setApplicationHiddenSetting for user " + userId);
14959
14960        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14961            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14962            return false;
14963        }
14964
14965        long callingId = Binder.clearCallingIdentity();
14966        try {
14967            boolean sendAdded = false;
14968            boolean sendRemoved = false;
14969            // writer
14970            synchronized (mPackages) {
14971                pkgSetting = mSettings.mPackages.get(packageName);
14972                if (pkgSetting == null) {
14973                    return false;
14974                }
14975                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14976                    return false;
14977                }
14978                // Do not allow "android" is being disabled
14979                if ("android".equals(packageName)) {
14980                    Slog.w(TAG, "Cannot hide package: android");
14981                    return false;
14982                }
14983                // Cannot hide static shared libs as they are considered
14984                // a part of the using app (emulating static linking). Also
14985                // static libs are installed always on internal storage.
14986                PackageParser.Package pkg = mPackages.get(packageName);
14987                if (pkg != null && pkg.staticSharedLibName != null) {
14988                    Slog.w(TAG, "Cannot hide package: " + packageName
14989                            + " providing static shared library: "
14990                            + pkg.staticSharedLibName);
14991                    return false;
14992                }
14993                // Only allow protected packages to hide themselves.
14994                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14995                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14996                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14997                    return false;
14998                }
14999
15000                if (pkgSetting.getHidden(userId) != hidden) {
15001                    pkgSetting.setHidden(hidden, userId);
15002                    mSettings.writePackageRestrictionsLPr(userId);
15003                    if (hidden) {
15004                        sendRemoved = true;
15005                    } else {
15006                        sendAdded = true;
15007                    }
15008                }
15009            }
15010            if (sendAdded) {
15011                sendPackageAddedForUser(packageName, pkgSetting, userId);
15012                return true;
15013            }
15014            if (sendRemoved) {
15015                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
15016                        "hiding pkg");
15017                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
15018                return true;
15019            }
15020        } finally {
15021            Binder.restoreCallingIdentity(callingId);
15022        }
15023        return false;
15024    }
15025
15026    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
15027            int userId) {
15028        final PackageRemovedInfo info = new PackageRemovedInfo(this);
15029        info.removedPackage = packageName;
15030        info.installerPackageName = pkgSetting.installerPackageName;
15031        info.removedUsers = new int[] {userId};
15032        info.broadcastUsers = new int[] {userId};
15033        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
15034        info.sendPackageRemovedBroadcasts(true /*killApp*/);
15035    }
15036
15037    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
15038        if (pkgList.length > 0) {
15039            Bundle extras = new Bundle(1);
15040            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15041
15042            sendPackageBroadcast(
15043                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
15044                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
15045                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
15046                    new int[] {userId});
15047        }
15048    }
15049
15050    /**
15051     * Returns true if application is not found or there was an error. Otherwise it returns
15052     * the hidden state of the package for the given user.
15053     */
15054    @Override
15055    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
15056        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15057        final int callingUid = Binder.getCallingUid();
15058        enforceCrossUserPermission(callingUid, userId,
15059                true /* requireFullPermission */, false /* checkShell */,
15060                "getApplicationHidden for user " + userId);
15061        PackageSetting ps;
15062        long callingId = Binder.clearCallingIdentity();
15063        try {
15064            // writer
15065            synchronized (mPackages) {
15066                ps = mSettings.mPackages.get(packageName);
15067                if (ps == null) {
15068                    return true;
15069                }
15070                if (filterAppAccessLPr(ps, callingUid, userId)) {
15071                    return true;
15072                }
15073                return ps.getHidden(userId);
15074            }
15075        } finally {
15076            Binder.restoreCallingIdentity(callingId);
15077        }
15078    }
15079
15080    /**
15081     * @hide
15082     */
15083    @Override
15084    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
15085            int installReason) {
15086        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
15087                null);
15088        PackageSetting pkgSetting;
15089        final int callingUid = Binder.getCallingUid();
15090        enforceCrossUserPermission(callingUid, userId,
15091                true /* requireFullPermission */, true /* checkShell */,
15092                "installExistingPackage for user " + userId);
15093        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
15094            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
15095        }
15096
15097        long callingId = Binder.clearCallingIdentity();
15098        try {
15099            boolean installed = false;
15100            final boolean instantApp =
15101                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15102            final boolean fullApp =
15103                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
15104
15105            // writer
15106            synchronized (mPackages) {
15107                pkgSetting = mSettings.mPackages.get(packageName);
15108                if (pkgSetting == null) {
15109                    return PackageManager.INSTALL_FAILED_INVALID_URI;
15110                }
15111                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
15112                    // only allow the existing package to be used if it's installed as a full
15113                    // application for at least one user
15114                    boolean installAllowed = false;
15115                    for (int checkUserId : sUserManager.getUserIds()) {
15116                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
15117                        if (installAllowed) {
15118                            break;
15119                        }
15120                    }
15121                    if (!installAllowed) {
15122                        return PackageManager.INSTALL_FAILED_INVALID_URI;
15123                    }
15124                }
15125                if (!pkgSetting.getInstalled(userId)) {
15126                    pkgSetting.setInstalled(true, userId);
15127                    pkgSetting.setHidden(false, userId);
15128                    pkgSetting.setInstallReason(installReason, userId);
15129                    mSettings.writePackageRestrictionsLPr(userId);
15130                    mSettings.writeKernelMappingLPr(pkgSetting);
15131                    installed = true;
15132                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15133                    // upgrade app from instant to full; we don't allow app downgrade
15134                    installed = true;
15135                }
15136                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
15137            }
15138
15139            if (installed) {
15140                if (pkgSetting.pkg != null) {
15141                    synchronized (mInstallLock) {
15142                        // We don't need to freeze for a brand new install
15143                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
15144                    }
15145                }
15146                sendPackageAddedForUser(packageName, pkgSetting, userId);
15147                synchronized (mPackages) {
15148                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
15149                }
15150            }
15151        } finally {
15152            Binder.restoreCallingIdentity(callingId);
15153        }
15154
15155        return PackageManager.INSTALL_SUCCEEDED;
15156    }
15157
15158    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
15159            boolean instantApp, boolean fullApp) {
15160        // no state specified; do nothing
15161        if (!instantApp && !fullApp) {
15162            return;
15163        }
15164        if (userId != UserHandle.USER_ALL) {
15165            if (instantApp && !pkgSetting.getInstantApp(userId)) {
15166                pkgSetting.setInstantApp(true /*instantApp*/, userId);
15167            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15168                pkgSetting.setInstantApp(false /*instantApp*/, userId);
15169            }
15170        } else {
15171            for (int currentUserId : sUserManager.getUserIds()) {
15172                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
15173                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
15174                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
15175                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
15176                }
15177            }
15178        }
15179    }
15180
15181    boolean isUserRestricted(int userId, String restrictionKey) {
15182        Bundle restrictions = sUserManager.getUserRestrictions(userId);
15183        if (restrictions.getBoolean(restrictionKey, false)) {
15184            Log.w(TAG, "User is restricted: " + restrictionKey);
15185            return true;
15186        }
15187        return false;
15188    }
15189
15190    @Override
15191    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15192            int userId) {
15193        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15194        final int callingUid = Binder.getCallingUid();
15195        enforceCrossUserPermission(callingUid, userId,
15196                true /* requireFullPermission */, true /* checkShell */,
15197                "setPackagesSuspended for user " + userId);
15198
15199        if (ArrayUtils.isEmpty(packageNames)) {
15200            return packageNames;
15201        }
15202
15203        // List of package names for whom the suspended state has changed.
15204        List<String> changedPackages = new ArrayList<>(packageNames.length);
15205        // List of package names for whom the suspended state is not set as requested in this
15206        // method.
15207        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15208        long callingId = Binder.clearCallingIdentity();
15209        try {
15210            for (int i = 0; i < packageNames.length; i++) {
15211                String packageName = packageNames[i];
15212                boolean changed = false;
15213                final int appId;
15214                synchronized (mPackages) {
15215                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15216                    if (pkgSetting == null
15217                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15218                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15219                                + "\". Skipping suspending/un-suspending.");
15220                        unactionedPackages.add(packageName);
15221                        continue;
15222                    }
15223                    appId = pkgSetting.appId;
15224                    if (pkgSetting.getSuspended(userId) != suspended) {
15225                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15226                            unactionedPackages.add(packageName);
15227                            continue;
15228                        }
15229                        pkgSetting.setSuspended(suspended, userId);
15230                        mSettings.writePackageRestrictionsLPr(userId);
15231                        changed = true;
15232                        changedPackages.add(packageName);
15233                    }
15234                }
15235
15236                if (changed && suspended) {
15237                    killApplication(packageName, UserHandle.getUid(userId, appId),
15238                            "suspending package");
15239                }
15240            }
15241        } finally {
15242            Binder.restoreCallingIdentity(callingId);
15243        }
15244
15245        if (!changedPackages.isEmpty()) {
15246            sendPackagesSuspendedForUser(changedPackages.toArray(
15247                    new String[changedPackages.size()]), userId, suspended);
15248        }
15249
15250        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15251    }
15252
15253    @Override
15254    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15255        final int callingUid = Binder.getCallingUid();
15256        enforceCrossUserPermission(callingUid, userId,
15257                true /* requireFullPermission */, false /* checkShell */,
15258                "isPackageSuspendedForUser for user " + userId);
15259        synchronized (mPackages) {
15260            final PackageSetting ps = mSettings.mPackages.get(packageName);
15261            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15262                throw new IllegalArgumentException("Unknown target package: " + packageName);
15263            }
15264            return ps.getSuspended(userId);
15265        }
15266    }
15267
15268    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15269        if (isPackageDeviceAdmin(packageName, userId)) {
15270            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15271                    + "\": has an active device admin");
15272            return false;
15273        }
15274
15275        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15276        if (packageName.equals(activeLauncherPackageName)) {
15277            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15278                    + "\": contains the active launcher");
15279            return false;
15280        }
15281
15282        if (packageName.equals(mRequiredInstallerPackage)) {
15283            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15284                    + "\": required for package installation");
15285            return false;
15286        }
15287
15288        if (packageName.equals(mRequiredUninstallerPackage)) {
15289            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15290                    + "\": required for package uninstallation");
15291            return false;
15292        }
15293
15294        if (packageName.equals(mRequiredVerifierPackage)) {
15295            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15296                    + "\": required for package verification");
15297            return false;
15298        }
15299
15300        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15301            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15302                    + "\": is the default dialer");
15303            return false;
15304        }
15305
15306        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15307            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15308                    + "\": protected package");
15309            return false;
15310        }
15311
15312        // Cannot suspend static shared libs as they are considered
15313        // a part of the using app (emulating static linking). Also
15314        // static libs are installed always on internal storage.
15315        PackageParser.Package pkg = mPackages.get(packageName);
15316        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15317            Slog.w(TAG, "Cannot suspend package: " + packageName
15318                    + " providing static shared library: "
15319                    + pkg.staticSharedLibName);
15320            return false;
15321        }
15322
15323        return true;
15324    }
15325
15326    private String getActiveLauncherPackageName(int userId) {
15327        Intent intent = new Intent(Intent.ACTION_MAIN);
15328        intent.addCategory(Intent.CATEGORY_HOME);
15329        ResolveInfo resolveInfo = resolveIntent(
15330                intent,
15331                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15332                PackageManager.MATCH_DEFAULT_ONLY,
15333                userId);
15334
15335        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15336    }
15337
15338    private String getDefaultDialerPackageName(int userId) {
15339        synchronized (mPackages) {
15340            return mSettings.getDefaultDialerPackageNameLPw(userId);
15341        }
15342    }
15343
15344    @Override
15345    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15346        mContext.enforceCallingOrSelfPermission(
15347                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15348                "Only package verification agents can verify applications");
15349
15350        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15351        final PackageVerificationResponse response = new PackageVerificationResponse(
15352                verificationCode, Binder.getCallingUid());
15353        msg.arg1 = id;
15354        msg.obj = response;
15355        mHandler.sendMessage(msg);
15356    }
15357
15358    @Override
15359    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15360            long millisecondsToDelay) {
15361        mContext.enforceCallingOrSelfPermission(
15362                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15363                "Only package verification agents can extend verification timeouts");
15364
15365        final PackageVerificationState state = mPendingVerification.get(id);
15366        final PackageVerificationResponse response = new PackageVerificationResponse(
15367                verificationCodeAtTimeout, Binder.getCallingUid());
15368
15369        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15370            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15371        }
15372        if (millisecondsToDelay < 0) {
15373            millisecondsToDelay = 0;
15374        }
15375        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15376                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15377            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15378        }
15379
15380        if ((state != null) && !state.timeoutExtended()) {
15381            state.extendTimeout();
15382
15383            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15384            msg.arg1 = id;
15385            msg.obj = response;
15386            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15387        }
15388    }
15389
15390    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15391            int verificationCode, UserHandle user) {
15392        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15393        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15394        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15395        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15396        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15397
15398        mContext.sendBroadcastAsUser(intent, user,
15399                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15400    }
15401
15402    private ComponentName matchComponentForVerifier(String packageName,
15403            List<ResolveInfo> receivers) {
15404        ActivityInfo targetReceiver = null;
15405
15406        final int NR = receivers.size();
15407        for (int i = 0; i < NR; i++) {
15408            final ResolveInfo info = receivers.get(i);
15409            if (info.activityInfo == null) {
15410                continue;
15411            }
15412
15413            if (packageName.equals(info.activityInfo.packageName)) {
15414                targetReceiver = info.activityInfo;
15415                break;
15416            }
15417        }
15418
15419        if (targetReceiver == null) {
15420            return null;
15421        }
15422
15423        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15424    }
15425
15426    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15427            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15428        if (pkgInfo.verifiers.length == 0) {
15429            return null;
15430        }
15431
15432        final int N = pkgInfo.verifiers.length;
15433        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15434        for (int i = 0; i < N; i++) {
15435            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15436
15437            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15438                    receivers);
15439            if (comp == null) {
15440                continue;
15441            }
15442
15443            final int verifierUid = getUidForVerifier(verifierInfo);
15444            if (verifierUid == -1) {
15445                continue;
15446            }
15447
15448            if (DEBUG_VERIFY) {
15449                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15450                        + " with the correct signature");
15451            }
15452            sufficientVerifiers.add(comp);
15453            verificationState.addSufficientVerifier(verifierUid);
15454        }
15455
15456        return sufficientVerifiers;
15457    }
15458
15459    private int getUidForVerifier(VerifierInfo verifierInfo) {
15460        synchronized (mPackages) {
15461            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15462            if (pkg == null) {
15463                return -1;
15464            } else if (pkg.mSignatures.length != 1) {
15465                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15466                        + " has more than one signature; ignoring");
15467                return -1;
15468            }
15469
15470            /*
15471             * If the public key of the package's signature does not match
15472             * our expected public key, then this is a different package and
15473             * we should skip.
15474             */
15475
15476            final byte[] expectedPublicKey;
15477            try {
15478                final Signature verifierSig = pkg.mSignatures[0];
15479                final PublicKey publicKey = verifierSig.getPublicKey();
15480                expectedPublicKey = publicKey.getEncoded();
15481            } catch (CertificateException e) {
15482                return -1;
15483            }
15484
15485            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15486
15487            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15488                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15489                        + " does not have the expected public key; ignoring");
15490                return -1;
15491            }
15492
15493            return pkg.applicationInfo.uid;
15494        }
15495    }
15496
15497    @Override
15498    public void finishPackageInstall(int token, boolean didLaunch) {
15499        enforceSystemOrRoot("Only the system is allowed to finish installs");
15500
15501        if (DEBUG_INSTALL) {
15502            Slog.v(TAG, "BM finishing package install for " + token);
15503        }
15504        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15505
15506        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15507        mHandler.sendMessage(msg);
15508    }
15509
15510    /**
15511     * Get the verification agent timeout.  Used for both the APK verifier and the
15512     * intent filter verifier.
15513     *
15514     * @return verification timeout in milliseconds
15515     */
15516    private long getVerificationTimeout() {
15517        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15518                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15519                DEFAULT_VERIFICATION_TIMEOUT);
15520    }
15521
15522    /**
15523     * Get the default verification agent response code.
15524     *
15525     * @return default verification response code
15526     */
15527    private int getDefaultVerificationResponse(UserHandle user) {
15528        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15529            return PackageManager.VERIFICATION_REJECT;
15530        }
15531        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15532                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15533                DEFAULT_VERIFICATION_RESPONSE);
15534    }
15535
15536    /**
15537     * Check whether or not package verification has been enabled.
15538     *
15539     * @return true if verification should be performed
15540     */
15541    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15542        if (!DEFAULT_VERIFY_ENABLE) {
15543            return false;
15544        }
15545
15546        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15547
15548        // Check if installing from ADB
15549        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15550            // Do not run verification in a test harness environment
15551            if (ActivityManager.isRunningInTestHarness()) {
15552                return false;
15553            }
15554            if (ensureVerifyAppsEnabled) {
15555                return true;
15556            }
15557            // Check if the developer does not want package verification for ADB installs
15558            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15559                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15560                return false;
15561            }
15562        } else {
15563            // only when not installed from ADB, skip verification for instant apps when
15564            // the installer and verifier are the same.
15565            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15566                if (mInstantAppInstallerActivity != null
15567                        && mInstantAppInstallerActivity.packageName.equals(
15568                                mRequiredVerifierPackage)) {
15569                    try {
15570                        mContext.getSystemService(AppOpsManager.class)
15571                                .checkPackage(installerUid, mRequiredVerifierPackage);
15572                        if (DEBUG_VERIFY) {
15573                            Slog.i(TAG, "disable verification for instant app");
15574                        }
15575                        return false;
15576                    } catch (SecurityException ignore) { }
15577                }
15578            }
15579        }
15580
15581        if (ensureVerifyAppsEnabled) {
15582            return true;
15583        }
15584
15585        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15586                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15587    }
15588
15589    @Override
15590    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15591            throws RemoteException {
15592        mContext.enforceCallingOrSelfPermission(
15593                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15594                "Only intentfilter verification agents can verify applications");
15595
15596        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15597        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15598                Binder.getCallingUid(), verificationCode, failedDomains);
15599        msg.arg1 = id;
15600        msg.obj = response;
15601        mHandler.sendMessage(msg);
15602    }
15603
15604    @Override
15605    public int getIntentVerificationStatus(String packageName, int userId) {
15606        final int callingUid = Binder.getCallingUid();
15607        if (UserHandle.getUserId(callingUid) != userId) {
15608            mContext.enforceCallingOrSelfPermission(
15609                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15610                    "getIntentVerificationStatus" + userId);
15611        }
15612        if (getInstantAppPackageName(callingUid) != null) {
15613            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15614        }
15615        synchronized (mPackages) {
15616            final PackageSetting ps = mSettings.mPackages.get(packageName);
15617            if (ps == null
15618                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15619                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15620            }
15621            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15622        }
15623    }
15624
15625    @Override
15626    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15627        mContext.enforceCallingOrSelfPermission(
15628                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15629
15630        boolean result = false;
15631        synchronized (mPackages) {
15632            final PackageSetting ps = mSettings.mPackages.get(packageName);
15633            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15634                return false;
15635            }
15636            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15637        }
15638        if (result) {
15639            scheduleWritePackageRestrictionsLocked(userId);
15640        }
15641        return result;
15642    }
15643
15644    @Override
15645    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15646            String packageName) {
15647        final int callingUid = Binder.getCallingUid();
15648        if (getInstantAppPackageName(callingUid) != null) {
15649            return ParceledListSlice.emptyList();
15650        }
15651        synchronized (mPackages) {
15652            final PackageSetting ps = mSettings.mPackages.get(packageName);
15653            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15654                return ParceledListSlice.emptyList();
15655            }
15656            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15657        }
15658    }
15659
15660    @Override
15661    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15662        if (TextUtils.isEmpty(packageName)) {
15663            return ParceledListSlice.emptyList();
15664        }
15665        final int callingUid = Binder.getCallingUid();
15666        final int callingUserId = UserHandle.getUserId(callingUid);
15667        synchronized (mPackages) {
15668            PackageParser.Package pkg = mPackages.get(packageName);
15669            if (pkg == null || pkg.activities == null) {
15670                return ParceledListSlice.emptyList();
15671            }
15672            if (pkg.mExtras == null) {
15673                return ParceledListSlice.emptyList();
15674            }
15675            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15676            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15677                return ParceledListSlice.emptyList();
15678            }
15679            final int count = pkg.activities.size();
15680            ArrayList<IntentFilter> result = new ArrayList<>();
15681            for (int n=0; n<count; n++) {
15682                PackageParser.Activity activity = pkg.activities.get(n);
15683                if (activity.intents != null && activity.intents.size() > 0) {
15684                    result.addAll(activity.intents);
15685                }
15686            }
15687            return new ParceledListSlice<>(result);
15688        }
15689    }
15690
15691    @Override
15692    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15693        mContext.enforceCallingOrSelfPermission(
15694                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15695        if (UserHandle.getCallingUserId() != userId) {
15696            mContext.enforceCallingOrSelfPermission(
15697                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15698        }
15699
15700        synchronized (mPackages) {
15701            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15702            if (packageName != null) {
15703                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15704                        packageName, userId);
15705            }
15706            return result;
15707        }
15708    }
15709
15710    @Override
15711    public String getDefaultBrowserPackageName(int userId) {
15712        if (UserHandle.getCallingUserId() != userId) {
15713            mContext.enforceCallingOrSelfPermission(
15714                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15715        }
15716        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15717            return null;
15718        }
15719        synchronized (mPackages) {
15720            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15721        }
15722    }
15723
15724    /**
15725     * Get the "allow unknown sources" setting.
15726     *
15727     * @return the current "allow unknown sources" setting
15728     */
15729    private int getUnknownSourcesSettings() {
15730        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15731                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15732                -1);
15733    }
15734
15735    @Override
15736    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15737        final int callingUid = Binder.getCallingUid();
15738        if (getInstantAppPackageName(callingUid) != null) {
15739            return;
15740        }
15741        // writer
15742        synchronized (mPackages) {
15743            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15744            if (targetPackageSetting == null
15745                    || filterAppAccessLPr(
15746                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15747                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15748            }
15749
15750            PackageSetting installerPackageSetting;
15751            if (installerPackageName != null) {
15752                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15753                if (installerPackageSetting == null) {
15754                    throw new IllegalArgumentException("Unknown installer package: "
15755                            + installerPackageName);
15756                }
15757            } else {
15758                installerPackageSetting = null;
15759            }
15760
15761            Signature[] callerSignature;
15762            Object obj = mSettings.getUserIdLPr(callingUid);
15763            if (obj != null) {
15764                if (obj instanceof SharedUserSetting) {
15765                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15766                } else if (obj instanceof PackageSetting) {
15767                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15768                } else {
15769                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15770                }
15771            } else {
15772                throw new SecurityException("Unknown calling UID: " + callingUid);
15773            }
15774
15775            // Verify: can't set installerPackageName to a package that is
15776            // not signed with the same cert as the caller.
15777            if (installerPackageSetting != null) {
15778                if (compareSignatures(callerSignature,
15779                        installerPackageSetting.signatures.mSignatures)
15780                        != PackageManager.SIGNATURE_MATCH) {
15781                    throw new SecurityException(
15782                            "Caller does not have same cert as new installer package "
15783                            + installerPackageName);
15784                }
15785            }
15786
15787            // Verify: if target already has an installer package, it must
15788            // be signed with the same cert as the caller.
15789            if (targetPackageSetting.installerPackageName != null) {
15790                PackageSetting setting = mSettings.mPackages.get(
15791                        targetPackageSetting.installerPackageName);
15792                // If the currently set package isn't valid, then it's always
15793                // okay to change it.
15794                if (setting != null) {
15795                    if (compareSignatures(callerSignature,
15796                            setting.signatures.mSignatures)
15797                            != PackageManager.SIGNATURE_MATCH) {
15798                        throw new SecurityException(
15799                                "Caller does not have same cert as old installer package "
15800                                + targetPackageSetting.installerPackageName);
15801                    }
15802                }
15803            }
15804
15805            // Okay!
15806            targetPackageSetting.installerPackageName = installerPackageName;
15807            if (installerPackageName != null) {
15808                mSettings.mInstallerPackages.add(installerPackageName);
15809            }
15810            scheduleWriteSettingsLocked();
15811        }
15812    }
15813
15814    @Override
15815    public void setApplicationCategoryHint(String packageName, int categoryHint,
15816            String callerPackageName) {
15817        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15818            throw new SecurityException("Instant applications don't have access to this method");
15819        }
15820        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15821                callerPackageName);
15822        synchronized (mPackages) {
15823            PackageSetting ps = mSettings.mPackages.get(packageName);
15824            if (ps == null) {
15825                throw new IllegalArgumentException("Unknown target package " + packageName);
15826            }
15827            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15828                throw new IllegalArgumentException("Unknown target package " + packageName);
15829            }
15830            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15831                throw new IllegalArgumentException("Calling package " + callerPackageName
15832                        + " is not installer for " + packageName);
15833            }
15834
15835            if (ps.categoryHint != categoryHint) {
15836                ps.categoryHint = categoryHint;
15837                scheduleWriteSettingsLocked();
15838            }
15839        }
15840    }
15841
15842    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15843        // Queue up an async operation since the package installation may take a little while.
15844        mHandler.post(new Runnable() {
15845            public void run() {
15846                mHandler.removeCallbacks(this);
15847                 // Result object to be returned
15848                PackageInstalledInfo res = new PackageInstalledInfo();
15849                res.setReturnCode(currentStatus);
15850                res.uid = -1;
15851                res.pkg = null;
15852                res.removedInfo = null;
15853                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15854                    args.doPreInstall(res.returnCode);
15855                    synchronized (mInstallLock) {
15856                        installPackageTracedLI(args, res);
15857                    }
15858                    args.doPostInstall(res.returnCode, res.uid);
15859                }
15860
15861                // A restore should be performed at this point if (a) the install
15862                // succeeded, (b) the operation is not an update, and (c) the new
15863                // package has not opted out of backup participation.
15864                final boolean update = res.removedInfo != null
15865                        && res.removedInfo.removedPackage != null;
15866                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15867                boolean doRestore = !update
15868                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15869
15870                // Set up the post-install work request bookkeeping.  This will be used
15871                // and cleaned up by the post-install event handling regardless of whether
15872                // there's a restore pass performed.  Token values are >= 1.
15873                int token;
15874                if (mNextInstallToken < 0) mNextInstallToken = 1;
15875                token = mNextInstallToken++;
15876
15877                PostInstallData data = new PostInstallData(args, res);
15878                mRunningInstalls.put(token, data);
15879                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15880
15881                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15882                    // Pass responsibility to the Backup Manager.  It will perform a
15883                    // restore if appropriate, then pass responsibility back to the
15884                    // Package Manager to run the post-install observer callbacks
15885                    // and broadcasts.
15886                    IBackupManager bm = IBackupManager.Stub.asInterface(
15887                            ServiceManager.getService(Context.BACKUP_SERVICE));
15888                    if (bm != null) {
15889                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15890                                + " to BM for possible restore");
15891                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15892                        try {
15893                            // TODO: http://b/22388012
15894                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15895                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15896                            } else {
15897                                doRestore = false;
15898                            }
15899                        } catch (RemoteException e) {
15900                            // can't happen; the backup manager is local
15901                        } catch (Exception e) {
15902                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15903                            doRestore = false;
15904                        }
15905                    } else {
15906                        Slog.e(TAG, "Backup Manager not found!");
15907                        doRestore = false;
15908                    }
15909                }
15910
15911                if (!doRestore) {
15912                    // No restore possible, or the Backup Manager was mysteriously not
15913                    // available -- just fire the post-install work request directly.
15914                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15915
15916                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15917
15918                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15919                    mHandler.sendMessage(msg);
15920                }
15921            }
15922        });
15923    }
15924
15925    /**
15926     * Callback from PackageSettings whenever an app is first transitioned out of the
15927     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15928     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15929     * here whether the app is the target of an ongoing install, and only send the
15930     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15931     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15932     * handling.
15933     */
15934    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15935        // Serialize this with the rest of the install-process message chain.  In the
15936        // restore-at-install case, this Runnable will necessarily run before the
15937        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15938        // are coherent.  In the non-restore case, the app has already completed install
15939        // and been launched through some other means, so it is not in a problematic
15940        // state for observers to see the FIRST_LAUNCH signal.
15941        mHandler.post(new Runnable() {
15942            @Override
15943            public void run() {
15944                for (int i = 0; i < mRunningInstalls.size(); i++) {
15945                    final PostInstallData data = mRunningInstalls.valueAt(i);
15946                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15947                        continue;
15948                    }
15949                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15950                        // right package; but is it for the right user?
15951                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15952                            if (userId == data.res.newUsers[uIndex]) {
15953                                if (DEBUG_BACKUP) {
15954                                    Slog.i(TAG, "Package " + pkgName
15955                                            + " being restored so deferring FIRST_LAUNCH");
15956                                }
15957                                return;
15958                            }
15959                        }
15960                    }
15961                }
15962                // didn't find it, so not being restored
15963                if (DEBUG_BACKUP) {
15964                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15965                }
15966                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15967            }
15968        });
15969    }
15970
15971    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15972        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15973                installerPkg, null, userIds);
15974    }
15975
15976    private abstract class HandlerParams {
15977        private static final int MAX_RETRIES = 4;
15978
15979        /**
15980         * Number of times startCopy() has been attempted and had a non-fatal
15981         * error.
15982         */
15983        private int mRetries = 0;
15984
15985        /** User handle for the user requesting the information or installation. */
15986        private final UserHandle mUser;
15987        String traceMethod;
15988        int traceCookie;
15989
15990        HandlerParams(UserHandle user) {
15991            mUser = user;
15992        }
15993
15994        UserHandle getUser() {
15995            return mUser;
15996        }
15997
15998        HandlerParams setTraceMethod(String traceMethod) {
15999            this.traceMethod = traceMethod;
16000            return this;
16001        }
16002
16003        HandlerParams setTraceCookie(int traceCookie) {
16004            this.traceCookie = traceCookie;
16005            return this;
16006        }
16007
16008        final boolean startCopy() {
16009            boolean res;
16010            try {
16011                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
16012
16013                if (++mRetries > MAX_RETRIES) {
16014                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
16015                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
16016                    handleServiceError();
16017                    return false;
16018                } else {
16019                    handleStartCopy();
16020                    res = true;
16021                }
16022            } catch (RemoteException e) {
16023                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
16024                mHandler.sendEmptyMessage(MCS_RECONNECT);
16025                res = false;
16026            }
16027            handleReturnCode();
16028            return res;
16029        }
16030
16031        final void serviceError() {
16032            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
16033            handleServiceError();
16034            handleReturnCode();
16035        }
16036
16037        abstract void handleStartCopy() throws RemoteException;
16038        abstract void handleServiceError();
16039        abstract void handleReturnCode();
16040    }
16041
16042    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
16043        for (File path : paths) {
16044            try {
16045                mcs.clearDirectory(path.getAbsolutePath());
16046            } catch (RemoteException e) {
16047            }
16048        }
16049    }
16050
16051    static class OriginInfo {
16052        /**
16053         * Location where install is coming from, before it has been
16054         * copied/renamed into place. This could be a single monolithic APK
16055         * file, or a cluster directory. This location may be untrusted.
16056         */
16057        final File file;
16058        final String cid;
16059
16060        /**
16061         * Flag indicating that {@link #file} or {@link #cid} has already been
16062         * staged, meaning downstream users don't need to defensively copy the
16063         * contents.
16064         */
16065        final boolean staged;
16066
16067        /**
16068         * Flag indicating that {@link #file} or {@link #cid} is an already
16069         * installed app that is being moved.
16070         */
16071        final boolean existing;
16072
16073        final String resolvedPath;
16074        final File resolvedFile;
16075
16076        static OriginInfo fromNothing() {
16077            return new OriginInfo(null, null, false, false);
16078        }
16079
16080        static OriginInfo fromUntrustedFile(File file) {
16081            return new OriginInfo(file, null, false, false);
16082        }
16083
16084        static OriginInfo fromExistingFile(File file) {
16085            return new OriginInfo(file, null, false, true);
16086        }
16087
16088        static OriginInfo fromStagedFile(File file) {
16089            return new OriginInfo(file, null, true, false);
16090        }
16091
16092        static OriginInfo fromStagedContainer(String cid) {
16093            return new OriginInfo(null, cid, true, false);
16094        }
16095
16096        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
16097            this.file = file;
16098            this.cid = cid;
16099            this.staged = staged;
16100            this.existing = existing;
16101
16102            if (cid != null) {
16103                resolvedPath = PackageHelper.getSdDir(cid);
16104                resolvedFile = new File(resolvedPath);
16105            } else if (file != null) {
16106                resolvedPath = file.getAbsolutePath();
16107                resolvedFile = file;
16108            } else {
16109                resolvedPath = null;
16110                resolvedFile = null;
16111            }
16112        }
16113    }
16114
16115    static class MoveInfo {
16116        final int moveId;
16117        final String fromUuid;
16118        final String toUuid;
16119        final String packageName;
16120        final String dataAppName;
16121        final int appId;
16122        final String seinfo;
16123        final int targetSdkVersion;
16124
16125        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
16126                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
16127            this.moveId = moveId;
16128            this.fromUuid = fromUuid;
16129            this.toUuid = toUuid;
16130            this.packageName = packageName;
16131            this.dataAppName = dataAppName;
16132            this.appId = appId;
16133            this.seinfo = seinfo;
16134            this.targetSdkVersion = targetSdkVersion;
16135        }
16136    }
16137
16138    static class VerificationInfo {
16139        /** A constant used to indicate that a uid value is not present. */
16140        public static final int NO_UID = -1;
16141
16142        /** URI referencing where the package was downloaded from. */
16143        final Uri originatingUri;
16144
16145        /** HTTP referrer URI associated with the originatingURI. */
16146        final Uri referrer;
16147
16148        /** UID of the application that the install request originated from. */
16149        final int originatingUid;
16150
16151        /** UID of application requesting the install */
16152        final int installerUid;
16153
16154        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
16155            this.originatingUri = originatingUri;
16156            this.referrer = referrer;
16157            this.originatingUid = originatingUid;
16158            this.installerUid = installerUid;
16159        }
16160    }
16161
16162    class InstallParams extends HandlerParams {
16163        final OriginInfo origin;
16164        final MoveInfo move;
16165        final IPackageInstallObserver2 observer;
16166        int installFlags;
16167        final String installerPackageName;
16168        final String volumeUuid;
16169        private InstallArgs mArgs;
16170        private int mRet;
16171        final String packageAbiOverride;
16172        final String[] grantedRuntimePermissions;
16173        final VerificationInfo verificationInfo;
16174        final Certificate[][] certificates;
16175        final int installReason;
16176
16177        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16178                int installFlags, String installerPackageName, String volumeUuid,
16179                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16180                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16181            super(user);
16182            this.origin = origin;
16183            this.move = move;
16184            this.observer = observer;
16185            this.installFlags = installFlags;
16186            this.installerPackageName = installerPackageName;
16187            this.volumeUuid = volumeUuid;
16188            this.verificationInfo = verificationInfo;
16189            this.packageAbiOverride = packageAbiOverride;
16190            this.grantedRuntimePermissions = grantedPermissions;
16191            this.certificates = certificates;
16192            this.installReason = installReason;
16193        }
16194
16195        @Override
16196        public String toString() {
16197            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16198                    + " file=" + origin.file + " cid=" + origin.cid + "}";
16199        }
16200
16201        private int installLocationPolicy(PackageInfoLite pkgLite) {
16202            String packageName = pkgLite.packageName;
16203            int installLocation = pkgLite.installLocation;
16204            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16205            // reader
16206            synchronized (mPackages) {
16207                // Currently installed package which the new package is attempting to replace or
16208                // null if no such package is installed.
16209                PackageParser.Package installedPkg = mPackages.get(packageName);
16210                // Package which currently owns the data which the new package will own if installed.
16211                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16212                // will be null whereas dataOwnerPkg will contain information about the package
16213                // which was uninstalled while keeping its data.
16214                PackageParser.Package dataOwnerPkg = installedPkg;
16215                if (dataOwnerPkg  == null) {
16216                    PackageSetting ps = mSettings.mPackages.get(packageName);
16217                    if (ps != null) {
16218                        dataOwnerPkg = ps.pkg;
16219                    }
16220                }
16221
16222                if (dataOwnerPkg != null) {
16223                    // If installed, the package will get access to data left on the device by its
16224                    // predecessor. As a security measure, this is permited only if this is not a
16225                    // version downgrade or if the predecessor package is marked as debuggable and
16226                    // a downgrade is explicitly requested.
16227                    //
16228                    // On debuggable platform builds, downgrades are permitted even for
16229                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16230                    // not offer security guarantees and thus it's OK to disable some security
16231                    // mechanisms to make debugging/testing easier on those builds. However, even on
16232                    // debuggable builds downgrades of packages are permitted only if requested via
16233                    // installFlags. This is because we aim to keep the behavior of debuggable
16234                    // platform builds as close as possible to the behavior of non-debuggable
16235                    // platform builds.
16236                    final boolean downgradeRequested =
16237                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16238                    final boolean packageDebuggable =
16239                                (dataOwnerPkg.applicationInfo.flags
16240                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16241                    final boolean downgradePermitted =
16242                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16243                    if (!downgradePermitted) {
16244                        try {
16245                            checkDowngrade(dataOwnerPkg, pkgLite);
16246                        } catch (PackageManagerException e) {
16247                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16248                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16249                        }
16250                    }
16251                }
16252
16253                if (installedPkg != null) {
16254                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16255                        // Check for updated system application.
16256                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16257                            if (onSd) {
16258                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16259                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16260                            }
16261                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16262                        } else {
16263                            if (onSd) {
16264                                // Install flag overrides everything.
16265                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16266                            }
16267                            // If current upgrade specifies particular preference
16268                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16269                                // Application explicitly specified internal.
16270                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16271                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16272                                // App explictly prefers external. Let policy decide
16273                            } else {
16274                                // Prefer previous location
16275                                if (isExternal(installedPkg)) {
16276                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16277                                }
16278                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16279                            }
16280                        }
16281                    } else {
16282                        // Invalid install. Return error code
16283                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16284                    }
16285                }
16286            }
16287            // All the special cases have been taken care of.
16288            // Return result based on recommended install location.
16289            if (onSd) {
16290                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16291            }
16292            return pkgLite.recommendedInstallLocation;
16293        }
16294
16295        /*
16296         * Invoke remote method to get package information and install
16297         * location values. Override install location based on default
16298         * policy if needed and then create install arguments based
16299         * on the install location.
16300         */
16301        public void handleStartCopy() throws RemoteException {
16302            int ret = PackageManager.INSTALL_SUCCEEDED;
16303
16304            // If we're already staged, we've firmly committed to an install location
16305            if (origin.staged) {
16306                if (origin.file != null) {
16307                    installFlags |= PackageManager.INSTALL_INTERNAL;
16308                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16309                } else if (origin.cid != null) {
16310                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16311                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16312                } else {
16313                    throw new IllegalStateException("Invalid stage location");
16314                }
16315            }
16316
16317            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16318            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16319            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16320            PackageInfoLite pkgLite = null;
16321
16322            if (onInt && onSd) {
16323                // Check if both bits are set.
16324                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16325                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16326            } else if (onSd && ephemeral) {
16327                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16328                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16329            } else {
16330                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16331                        packageAbiOverride);
16332
16333                if (DEBUG_EPHEMERAL && ephemeral) {
16334                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16335                }
16336
16337                /*
16338                 * If we have too little free space, try to free cache
16339                 * before giving up.
16340                 */
16341                if (!origin.staged && pkgLite.recommendedInstallLocation
16342                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16343                    // TODO: focus freeing disk space on the target device
16344                    final StorageManager storage = StorageManager.from(mContext);
16345                    final long lowThreshold = storage.getStorageLowBytes(
16346                            Environment.getDataDirectory());
16347
16348                    final long sizeBytes = mContainerService.calculateInstalledSize(
16349                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16350
16351                    try {
16352                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16353                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16354                                installFlags, packageAbiOverride);
16355                    } catch (InstallerException e) {
16356                        Slog.w(TAG, "Failed to free cache", e);
16357                    }
16358
16359                    /*
16360                     * The cache free must have deleted the file we
16361                     * downloaded to install.
16362                     *
16363                     * TODO: fix the "freeCache" call to not delete
16364                     *       the file we care about.
16365                     */
16366                    if (pkgLite.recommendedInstallLocation
16367                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16368                        pkgLite.recommendedInstallLocation
16369                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16370                    }
16371                }
16372            }
16373
16374            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16375                int loc = pkgLite.recommendedInstallLocation;
16376                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16377                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16378                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16379                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16380                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16381                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16382                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16383                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16384                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16385                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16386                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16387                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16388                } else {
16389                    // Override with defaults if needed.
16390                    loc = installLocationPolicy(pkgLite);
16391                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16392                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16393                    } else if (!onSd && !onInt) {
16394                        // Override install location with flags
16395                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16396                            // Set the flag to install on external media.
16397                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16398                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16399                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16400                            if (DEBUG_EPHEMERAL) {
16401                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16402                            }
16403                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16404                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16405                                    |PackageManager.INSTALL_INTERNAL);
16406                        } else {
16407                            // Make sure the flag for installing on external
16408                            // media is unset
16409                            installFlags |= PackageManager.INSTALL_INTERNAL;
16410                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16411                        }
16412                    }
16413                }
16414            }
16415
16416            final InstallArgs args = createInstallArgs(this);
16417            mArgs = args;
16418
16419            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16420                // TODO: http://b/22976637
16421                // Apps installed for "all" users use the device owner to verify the app
16422                UserHandle verifierUser = getUser();
16423                if (verifierUser == UserHandle.ALL) {
16424                    verifierUser = UserHandle.SYSTEM;
16425                }
16426
16427                /*
16428                 * Determine if we have any installed package verifiers. If we
16429                 * do, then we'll defer to them to verify the packages.
16430                 */
16431                final int requiredUid = mRequiredVerifierPackage == null ? -1
16432                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16433                                verifierUser.getIdentifier());
16434                final int installerUid =
16435                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16436                if (!origin.existing && requiredUid != -1
16437                        && isVerificationEnabled(
16438                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16439                    final Intent verification = new Intent(
16440                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16441                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16442                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16443                            PACKAGE_MIME_TYPE);
16444                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16445
16446                    // Query all live verifiers based on current user state
16447                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16448                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16449                            false /*allowDynamicSplits*/);
16450
16451                    if (DEBUG_VERIFY) {
16452                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16453                                + verification.toString() + " with " + pkgLite.verifiers.length
16454                                + " optional verifiers");
16455                    }
16456
16457                    final int verificationId = mPendingVerificationToken++;
16458
16459                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16460
16461                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16462                            installerPackageName);
16463
16464                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16465                            installFlags);
16466
16467                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16468                            pkgLite.packageName);
16469
16470                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16471                            pkgLite.versionCode);
16472
16473                    if (verificationInfo != null) {
16474                        if (verificationInfo.originatingUri != null) {
16475                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16476                                    verificationInfo.originatingUri);
16477                        }
16478                        if (verificationInfo.referrer != null) {
16479                            verification.putExtra(Intent.EXTRA_REFERRER,
16480                                    verificationInfo.referrer);
16481                        }
16482                        if (verificationInfo.originatingUid >= 0) {
16483                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16484                                    verificationInfo.originatingUid);
16485                        }
16486                        if (verificationInfo.installerUid >= 0) {
16487                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16488                                    verificationInfo.installerUid);
16489                        }
16490                    }
16491
16492                    final PackageVerificationState verificationState = new PackageVerificationState(
16493                            requiredUid, args);
16494
16495                    mPendingVerification.append(verificationId, verificationState);
16496
16497                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16498                            receivers, verificationState);
16499
16500                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16501                    final long idleDuration = getVerificationTimeout();
16502
16503                    /*
16504                     * If any sufficient verifiers were listed in the package
16505                     * manifest, attempt to ask them.
16506                     */
16507                    if (sufficientVerifiers != null) {
16508                        final int N = sufficientVerifiers.size();
16509                        if (N == 0) {
16510                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16511                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16512                        } else {
16513                            for (int i = 0; i < N; i++) {
16514                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16515                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16516                                        verifierComponent.getPackageName(), idleDuration,
16517                                        verifierUser.getIdentifier(), false, "package verifier");
16518
16519                                final Intent sufficientIntent = new Intent(verification);
16520                                sufficientIntent.setComponent(verifierComponent);
16521                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16522                            }
16523                        }
16524                    }
16525
16526                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16527                            mRequiredVerifierPackage, receivers);
16528                    if (ret == PackageManager.INSTALL_SUCCEEDED
16529                            && mRequiredVerifierPackage != null) {
16530                        Trace.asyncTraceBegin(
16531                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16532                        /*
16533                         * Send the intent to the required verification agent,
16534                         * but only start the verification timeout after the
16535                         * target BroadcastReceivers have run.
16536                         */
16537                        verification.setComponent(requiredVerifierComponent);
16538                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16539                                mRequiredVerifierPackage, idleDuration,
16540                                verifierUser.getIdentifier(), false, "package verifier");
16541                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16542                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16543                                new BroadcastReceiver() {
16544                                    @Override
16545                                    public void onReceive(Context context, Intent intent) {
16546                                        final Message msg = mHandler
16547                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16548                                        msg.arg1 = verificationId;
16549                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16550                                    }
16551                                }, null, 0, null, null);
16552
16553                        /*
16554                         * We don't want the copy to proceed until verification
16555                         * succeeds, so null out this field.
16556                         */
16557                        mArgs = null;
16558                    }
16559                } else {
16560                    /*
16561                     * No package verification is enabled, so immediately start
16562                     * the remote call to initiate copy using temporary file.
16563                     */
16564                    ret = args.copyApk(mContainerService, true);
16565                }
16566            }
16567
16568            mRet = ret;
16569        }
16570
16571        @Override
16572        void handleReturnCode() {
16573            // If mArgs is null, then MCS couldn't be reached. When it
16574            // reconnects, it will try again to install. At that point, this
16575            // will succeed.
16576            if (mArgs != null) {
16577                processPendingInstall(mArgs, mRet);
16578            }
16579        }
16580
16581        @Override
16582        void handleServiceError() {
16583            mArgs = createInstallArgs(this);
16584            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16585        }
16586
16587        public boolean isForwardLocked() {
16588            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16589        }
16590    }
16591
16592    /**
16593     * Used during creation of InstallArgs
16594     *
16595     * @param installFlags package installation flags
16596     * @return true if should be installed on external storage
16597     */
16598    private static boolean installOnExternalAsec(int installFlags) {
16599        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16600            return false;
16601        }
16602        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16603            return true;
16604        }
16605        return false;
16606    }
16607
16608    /**
16609     * Used during creation of InstallArgs
16610     *
16611     * @param installFlags package installation flags
16612     * @return true if should be installed as forward locked
16613     */
16614    private static boolean installForwardLocked(int installFlags) {
16615        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16616    }
16617
16618    private InstallArgs createInstallArgs(InstallParams params) {
16619        if (params.move != null) {
16620            return new MoveInstallArgs(params);
16621        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16622            return new AsecInstallArgs(params);
16623        } else {
16624            return new FileInstallArgs(params);
16625        }
16626    }
16627
16628    /**
16629     * Create args that describe an existing installed package. Typically used
16630     * when cleaning up old installs, or used as a move source.
16631     */
16632    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16633            String resourcePath, String[] instructionSets) {
16634        final boolean isInAsec;
16635        if (installOnExternalAsec(installFlags)) {
16636            /* Apps on SD card are always in ASEC containers. */
16637            isInAsec = true;
16638        } else if (installForwardLocked(installFlags)
16639                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16640            /*
16641             * Forward-locked apps are only in ASEC containers if they're the
16642             * new style
16643             */
16644            isInAsec = true;
16645        } else {
16646            isInAsec = false;
16647        }
16648
16649        if (isInAsec) {
16650            return new AsecInstallArgs(codePath, instructionSets,
16651                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16652        } else {
16653            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16654        }
16655    }
16656
16657    static abstract class InstallArgs {
16658        /** @see InstallParams#origin */
16659        final OriginInfo origin;
16660        /** @see InstallParams#move */
16661        final MoveInfo move;
16662
16663        final IPackageInstallObserver2 observer;
16664        // Always refers to PackageManager flags only
16665        final int installFlags;
16666        final String installerPackageName;
16667        final String volumeUuid;
16668        final UserHandle user;
16669        final String abiOverride;
16670        final String[] installGrantPermissions;
16671        /** If non-null, drop an async trace when the install completes */
16672        final String traceMethod;
16673        final int traceCookie;
16674        final Certificate[][] certificates;
16675        final int installReason;
16676
16677        // The list of instruction sets supported by this app. This is currently
16678        // only used during the rmdex() phase to clean up resources. We can get rid of this
16679        // if we move dex files under the common app path.
16680        /* nullable */ String[] instructionSets;
16681
16682        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16683                int installFlags, String installerPackageName, String volumeUuid,
16684                UserHandle user, String[] instructionSets,
16685                String abiOverride, String[] installGrantPermissions,
16686                String traceMethod, int traceCookie, Certificate[][] certificates,
16687                int installReason) {
16688            this.origin = origin;
16689            this.move = move;
16690            this.installFlags = installFlags;
16691            this.observer = observer;
16692            this.installerPackageName = installerPackageName;
16693            this.volumeUuid = volumeUuid;
16694            this.user = user;
16695            this.instructionSets = instructionSets;
16696            this.abiOverride = abiOverride;
16697            this.installGrantPermissions = installGrantPermissions;
16698            this.traceMethod = traceMethod;
16699            this.traceCookie = traceCookie;
16700            this.certificates = certificates;
16701            this.installReason = installReason;
16702        }
16703
16704        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16705        abstract int doPreInstall(int status);
16706
16707        /**
16708         * Rename package into final resting place. All paths on the given
16709         * scanned package should be updated to reflect the rename.
16710         */
16711        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16712        abstract int doPostInstall(int status, int uid);
16713
16714        /** @see PackageSettingBase#codePathString */
16715        abstract String getCodePath();
16716        /** @see PackageSettingBase#resourcePathString */
16717        abstract String getResourcePath();
16718
16719        // Need installer lock especially for dex file removal.
16720        abstract void cleanUpResourcesLI();
16721        abstract boolean doPostDeleteLI(boolean delete);
16722
16723        /**
16724         * Called before the source arguments are copied. This is used mostly
16725         * for MoveParams when it needs to read the source file to put it in the
16726         * destination.
16727         */
16728        int doPreCopy() {
16729            return PackageManager.INSTALL_SUCCEEDED;
16730        }
16731
16732        /**
16733         * Called after the source arguments are copied. This is used mostly for
16734         * MoveParams when it needs to read the source file to put it in the
16735         * destination.
16736         */
16737        int doPostCopy(int uid) {
16738            return PackageManager.INSTALL_SUCCEEDED;
16739        }
16740
16741        protected boolean isFwdLocked() {
16742            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16743        }
16744
16745        protected boolean isExternalAsec() {
16746            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16747        }
16748
16749        protected boolean isEphemeral() {
16750            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16751        }
16752
16753        UserHandle getUser() {
16754            return user;
16755        }
16756    }
16757
16758    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16759        if (!allCodePaths.isEmpty()) {
16760            if (instructionSets == null) {
16761                throw new IllegalStateException("instructionSet == null");
16762            }
16763            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16764            for (String codePath : allCodePaths) {
16765                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16766                    try {
16767                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16768                    } catch (InstallerException ignored) {
16769                    }
16770                }
16771            }
16772        }
16773    }
16774
16775    /**
16776     * Logic to handle installation of non-ASEC applications, including copying
16777     * and renaming logic.
16778     */
16779    class FileInstallArgs extends InstallArgs {
16780        private File codeFile;
16781        private File resourceFile;
16782
16783        // Example topology:
16784        // /data/app/com.example/base.apk
16785        // /data/app/com.example/split_foo.apk
16786        // /data/app/com.example/lib/arm/libfoo.so
16787        // /data/app/com.example/lib/arm64/libfoo.so
16788        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16789
16790        /** New install */
16791        FileInstallArgs(InstallParams params) {
16792            super(params.origin, params.move, params.observer, params.installFlags,
16793                    params.installerPackageName, params.volumeUuid,
16794                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16795                    params.grantedRuntimePermissions,
16796                    params.traceMethod, params.traceCookie, params.certificates,
16797                    params.installReason);
16798            if (isFwdLocked()) {
16799                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16800            }
16801        }
16802
16803        /** Existing install */
16804        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16805            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16806                    null, null, null, 0, null /*certificates*/,
16807                    PackageManager.INSTALL_REASON_UNKNOWN);
16808            this.codeFile = (codePath != null) ? new File(codePath) : null;
16809            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16810        }
16811
16812        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16813            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16814            try {
16815                return doCopyApk(imcs, temp);
16816            } finally {
16817                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16818            }
16819        }
16820
16821        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16822            if (origin.staged) {
16823                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16824                codeFile = origin.file;
16825                resourceFile = origin.file;
16826                return PackageManager.INSTALL_SUCCEEDED;
16827            }
16828
16829            try {
16830                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16831                final File tempDir =
16832                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16833                codeFile = tempDir;
16834                resourceFile = tempDir;
16835            } catch (IOException e) {
16836                Slog.w(TAG, "Failed to create copy file: " + e);
16837                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16838            }
16839
16840            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16841                @Override
16842                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16843                    if (!FileUtils.isValidExtFilename(name)) {
16844                        throw new IllegalArgumentException("Invalid filename: " + name);
16845                    }
16846                    try {
16847                        final File file = new File(codeFile, name);
16848                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16849                                O_RDWR | O_CREAT, 0644);
16850                        Os.chmod(file.getAbsolutePath(), 0644);
16851                        return new ParcelFileDescriptor(fd);
16852                    } catch (ErrnoException e) {
16853                        throw new RemoteException("Failed to open: " + e.getMessage());
16854                    }
16855                }
16856            };
16857
16858            int ret = PackageManager.INSTALL_SUCCEEDED;
16859            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16860            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16861                Slog.e(TAG, "Failed to copy package");
16862                return ret;
16863            }
16864
16865            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16866            NativeLibraryHelper.Handle handle = null;
16867            try {
16868                handle = NativeLibraryHelper.Handle.create(codeFile);
16869                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16870                        abiOverride);
16871            } catch (IOException e) {
16872                Slog.e(TAG, "Copying native libraries failed", e);
16873                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16874            } finally {
16875                IoUtils.closeQuietly(handle);
16876            }
16877
16878            return ret;
16879        }
16880
16881        int doPreInstall(int status) {
16882            if (status != PackageManager.INSTALL_SUCCEEDED) {
16883                cleanUp();
16884            }
16885            return status;
16886        }
16887
16888        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16889            if (status != PackageManager.INSTALL_SUCCEEDED) {
16890                cleanUp();
16891                return false;
16892            }
16893
16894            final File targetDir = codeFile.getParentFile();
16895            final File beforeCodeFile = codeFile;
16896            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16897
16898            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16899            try {
16900                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16901            } catch (ErrnoException e) {
16902                Slog.w(TAG, "Failed to rename", e);
16903                return false;
16904            }
16905
16906            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16907                Slog.w(TAG, "Failed to restorecon");
16908                return false;
16909            }
16910
16911            // Reflect the rename internally
16912            codeFile = afterCodeFile;
16913            resourceFile = afterCodeFile;
16914
16915            // Reflect the rename in scanned details
16916            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16917            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16918                    afterCodeFile, pkg.baseCodePath));
16919            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16920                    afterCodeFile, pkg.splitCodePaths));
16921
16922            // Reflect the rename in app info
16923            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16924            pkg.setApplicationInfoCodePath(pkg.codePath);
16925            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16926            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16927            pkg.setApplicationInfoResourcePath(pkg.codePath);
16928            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16929            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16930
16931            return true;
16932        }
16933
16934        int doPostInstall(int status, int uid) {
16935            if (status != PackageManager.INSTALL_SUCCEEDED) {
16936                cleanUp();
16937            }
16938            return status;
16939        }
16940
16941        @Override
16942        String getCodePath() {
16943            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16944        }
16945
16946        @Override
16947        String getResourcePath() {
16948            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16949        }
16950
16951        private boolean cleanUp() {
16952            if (codeFile == null || !codeFile.exists()) {
16953                return false;
16954            }
16955
16956            removeCodePathLI(codeFile);
16957
16958            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16959                resourceFile.delete();
16960            }
16961
16962            return true;
16963        }
16964
16965        void cleanUpResourcesLI() {
16966            // Try enumerating all code paths before deleting
16967            List<String> allCodePaths = Collections.EMPTY_LIST;
16968            if (codeFile != null && codeFile.exists()) {
16969                try {
16970                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16971                    allCodePaths = pkg.getAllCodePaths();
16972                } catch (PackageParserException e) {
16973                    // Ignored; we tried our best
16974                }
16975            }
16976
16977            cleanUp();
16978            removeDexFiles(allCodePaths, instructionSets);
16979        }
16980
16981        boolean doPostDeleteLI(boolean delete) {
16982            // XXX err, shouldn't we respect the delete flag?
16983            cleanUpResourcesLI();
16984            return true;
16985        }
16986    }
16987
16988    private boolean isAsecExternal(String cid) {
16989        final String asecPath = PackageHelper.getSdFilesystem(cid);
16990        return !asecPath.startsWith(mAsecInternalPath);
16991    }
16992
16993    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16994            PackageManagerException {
16995        if (copyRet < 0) {
16996            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16997                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16998                throw new PackageManagerException(copyRet, message);
16999            }
17000        }
17001    }
17002
17003    /**
17004     * Extract the StorageManagerService "container ID" from the full code path of an
17005     * .apk.
17006     */
17007    static String cidFromCodePath(String fullCodePath) {
17008        int eidx = fullCodePath.lastIndexOf("/");
17009        String subStr1 = fullCodePath.substring(0, eidx);
17010        int sidx = subStr1.lastIndexOf("/");
17011        return subStr1.substring(sidx+1, eidx);
17012    }
17013
17014    /**
17015     * Logic to handle installation of ASEC applications, including copying and
17016     * renaming logic.
17017     */
17018    class AsecInstallArgs extends InstallArgs {
17019        static final String RES_FILE_NAME = "pkg.apk";
17020        static final String PUBLIC_RES_FILE_NAME = "res.zip";
17021
17022        String cid;
17023        String packagePath;
17024        String resourcePath;
17025
17026        /** New install */
17027        AsecInstallArgs(InstallParams params) {
17028            super(params.origin, params.move, params.observer, params.installFlags,
17029                    params.installerPackageName, params.volumeUuid,
17030                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17031                    params.grantedRuntimePermissions,
17032                    params.traceMethod, params.traceCookie, params.certificates,
17033                    params.installReason);
17034        }
17035
17036        /** Existing install */
17037        AsecInstallArgs(String fullCodePath, String[] instructionSets,
17038                        boolean isExternal, boolean isForwardLocked) {
17039            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
17040                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
17041                    instructionSets, null, null, null, 0, null /*certificates*/,
17042                    PackageManager.INSTALL_REASON_UNKNOWN);
17043            // Hackily pretend we're still looking at a full code path
17044            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
17045                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
17046            }
17047
17048            // Extract cid from fullCodePath
17049            int eidx = fullCodePath.lastIndexOf("/");
17050            String subStr1 = fullCodePath.substring(0, eidx);
17051            int sidx = subStr1.lastIndexOf("/");
17052            cid = subStr1.substring(sidx+1, eidx);
17053            setMountPath(subStr1);
17054        }
17055
17056        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
17057            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
17058                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
17059                    instructionSets, null, null, null, 0, null /*certificates*/,
17060                    PackageManager.INSTALL_REASON_UNKNOWN);
17061            this.cid = cid;
17062            setMountPath(PackageHelper.getSdDir(cid));
17063        }
17064
17065        void createCopyFile() {
17066            cid = mInstallerService.allocateExternalStageCidLegacy();
17067        }
17068
17069        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
17070            if (origin.staged && origin.cid != null) {
17071                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
17072                cid = origin.cid;
17073                setMountPath(PackageHelper.getSdDir(cid));
17074                return PackageManager.INSTALL_SUCCEEDED;
17075            }
17076
17077            if (temp) {
17078                createCopyFile();
17079            } else {
17080                /*
17081                 * Pre-emptively destroy the container since it's destroyed if
17082                 * copying fails due to it existing anyway.
17083                 */
17084                PackageHelper.destroySdDir(cid);
17085            }
17086
17087            final String newMountPath = imcs.copyPackageToContainer(
17088                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
17089                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
17090
17091            if (newMountPath != null) {
17092                setMountPath(newMountPath);
17093                return PackageManager.INSTALL_SUCCEEDED;
17094            } else {
17095                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17096            }
17097        }
17098
17099        @Override
17100        String getCodePath() {
17101            return packagePath;
17102        }
17103
17104        @Override
17105        String getResourcePath() {
17106            return resourcePath;
17107        }
17108
17109        int doPreInstall(int status) {
17110            if (status != PackageManager.INSTALL_SUCCEEDED) {
17111                // Destroy container
17112                PackageHelper.destroySdDir(cid);
17113            } else {
17114                boolean mounted = PackageHelper.isContainerMounted(cid);
17115                if (!mounted) {
17116                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
17117                            Process.SYSTEM_UID);
17118                    if (newMountPath != null) {
17119                        setMountPath(newMountPath);
17120                    } else {
17121                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17122                    }
17123                }
17124            }
17125            return status;
17126        }
17127
17128        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17129            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
17130            String newMountPath = null;
17131            if (PackageHelper.isContainerMounted(cid)) {
17132                // Unmount the container
17133                if (!PackageHelper.unMountSdDir(cid)) {
17134                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
17135                    return false;
17136                }
17137            }
17138            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17139                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
17140                        " which might be stale. Will try to clean up.");
17141                // Clean up the stale container and proceed to recreate.
17142                if (!PackageHelper.destroySdDir(newCacheId)) {
17143                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
17144                    return false;
17145                }
17146                // Successfully cleaned up stale container. Try to rename again.
17147                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17148                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
17149                            + " inspite of cleaning it up.");
17150                    return false;
17151                }
17152            }
17153            if (!PackageHelper.isContainerMounted(newCacheId)) {
17154                Slog.w(TAG, "Mounting container " + newCacheId);
17155                newMountPath = PackageHelper.mountSdDir(newCacheId,
17156                        getEncryptKey(), Process.SYSTEM_UID);
17157            } else {
17158                newMountPath = PackageHelper.getSdDir(newCacheId);
17159            }
17160            if (newMountPath == null) {
17161                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
17162                return false;
17163            }
17164            Log.i(TAG, "Succesfully renamed " + cid +
17165                    " to " + newCacheId +
17166                    " at new path: " + newMountPath);
17167            cid = newCacheId;
17168
17169            final File beforeCodeFile = new File(packagePath);
17170            setMountPath(newMountPath);
17171            final File afterCodeFile = new File(packagePath);
17172
17173            // Reflect the rename in scanned details
17174            pkg.setCodePath(afterCodeFile.getAbsolutePath());
17175            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
17176                    afterCodeFile, pkg.baseCodePath));
17177            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
17178                    afterCodeFile, pkg.splitCodePaths));
17179
17180            // Reflect the rename in app info
17181            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17182            pkg.setApplicationInfoCodePath(pkg.codePath);
17183            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17184            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17185            pkg.setApplicationInfoResourcePath(pkg.codePath);
17186            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17187            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17188
17189            return true;
17190        }
17191
17192        private void setMountPath(String mountPath) {
17193            final File mountFile = new File(mountPath);
17194
17195            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
17196            if (monolithicFile.exists()) {
17197                packagePath = monolithicFile.getAbsolutePath();
17198                if (isFwdLocked()) {
17199                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
17200                } else {
17201                    resourcePath = packagePath;
17202                }
17203            } else {
17204                packagePath = mountFile.getAbsolutePath();
17205                resourcePath = packagePath;
17206            }
17207        }
17208
17209        int doPostInstall(int status, int uid) {
17210            if (status != PackageManager.INSTALL_SUCCEEDED) {
17211                cleanUp();
17212            } else {
17213                final int groupOwner;
17214                final String protectedFile;
17215                if (isFwdLocked()) {
17216                    groupOwner = UserHandle.getSharedAppGid(uid);
17217                    protectedFile = RES_FILE_NAME;
17218                } else {
17219                    groupOwner = -1;
17220                    protectedFile = null;
17221                }
17222
17223                if (uid < Process.FIRST_APPLICATION_UID
17224                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
17225                    Slog.e(TAG, "Failed to finalize " + cid);
17226                    PackageHelper.destroySdDir(cid);
17227                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17228                }
17229
17230                boolean mounted = PackageHelper.isContainerMounted(cid);
17231                if (!mounted) {
17232                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17233                }
17234            }
17235            return status;
17236        }
17237
17238        private void cleanUp() {
17239            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17240
17241            // Destroy secure container
17242            PackageHelper.destroySdDir(cid);
17243        }
17244
17245        private List<String> getAllCodePaths() {
17246            final File codeFile = new File(getCodePath());
17247            if (codeFile != null && codeFile.exists()) {
17248                try {
17249                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17250                    return pkg.getAllCodePaths();
17251                } catch (PackageParserException e) {
17252                    // Ignored; we tried our best
17253                }
17254            }
17255            return Collections.EMPTY_LIST;
17256        }
17257
17258        void cleanUpResourcesLI() {
17259            // Enumerate all code paths before deleting
17260            cleanUpResourcesLI(getAllCodePaths());
17261        }
17262
17263        private void cleanUpResourcesLI(List<String> allCodePaths) {
17264            cleanUp();
17265            removeDexFiles(allCodePaths, instructionSets);
17266        }
17267
17268        String getPackageName() {
17269            return getAsecPackageName(cid);
17270        }
17271
17272        boolean doPostDeleteLI(boolean delete) {
17273            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17274            final List<String> allCodePaths = getAllCodePaths();
17275            boolean mounted = PackageHelper.isContainerMounted(cid);
17276            if (mounted) {
17277                // Unmount first
17278                if (PackageHelper.unMountSdDir(cid)) {
17279                    mounted = false;
17280                }
17281            }
17282            if (!mounted && delete) {
17283                cleanUpResourcesLI(allCodePaths);
17284            }
17285            return !mounted;
17286        }
17287
17288        @Override
17289        int doPreCopy() {
17290            if (isFwdLocked()) {
17291                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17292                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17293                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17294                }
17295            }
17296
17297            return PackageManager.INSTALL_SUCCEEDED;
17298        }
17299
17300        @Override
17301        int doPostCopy(int uid) {
17302            if (isFwdLocked()) {
17303                if (uid < Process.FIRST_APPLICATION_UID
17304                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17305                                RES_FILE_NAME)) {
17306                    Slog.e(TAG, "Failed to finalize " + cid);
17307                    PackageHelper.destroySdDir(cid);
17308                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17309                }
17310            }
17311
17312            return PackageManager.INSTALL_SUCCEEDED;
17313        }
17314    }
17315
17316    /**
17317     * Logic to handle movement of existing installed applications.
17318     */
17319    class MoveInstallArgs extends InstallArgs {
17320        private File codeFile;
17321        private File resourceFile;
17322
17323        /** New install */
17324        MoveInstallArgs(InstallParams params) {
17325            super(params.origin, params.move, params.observer, params.installFlags,
17326                    params.installerPackageName, params.volumeUuid,
17327                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17328                    params.grantedRuntimePermissions,
17329                    params.traceMethod, params.traceCookie, params.certificates,
17330                    params.installReason);
17331        }
17332
17333        int copyApk(IMediaContainerService imcs, boolean temp) {
17334            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17335                    + move.fromUuid + " to " + move.toUuid);
17336            synchronized (mInstaller) {
17337                try {
17338                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17339                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17340                } catch (InstallerException e) {
17341                    Slog.w(TAG, "Failed to move app", e);
17342                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17343                }
17344            }
17345
17346            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17347            resourceFile = codeFile;
17348            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17349
17350            return PackageManager.INSTALL_SUCCEEDED;
17351        }
17352
17353        int doPreInstall(int status) {
17354            if (status != PackageManager.INSTALL_SUCCEEDED) {
17355                cleanUp(move.toUuid);
17356            }
17357            return status;
17358        }
17359
17360        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17361            if (status != PackageManager.INSTALL_SUCCEEDED) {
17362                cleanUp(move.toUuid);
17363                return false;
17364            }
17365
17366            // Reflect the move in app info
17367            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17368            pkg.setApplicationInfoCodePath(pkg.codePath);
17369            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17370            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17371            pkg.setApplicationInfoResourcePath(pkg.codePath);
17372            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17373            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17374
17375            return true;
17376        }
17377
17378        int doPostInstall(int status, int uid) {
17379            if (status == PackageManager.INSTALL_SUCCEEDED) {
17380                cleanUp(move.fromUuid);
17381            } else {
17382                cleanUp(move.toUuid);
17383            }
17384            return status;
17385        }
17386
17387        @Override
17388        String getCodePath() {
17389            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17390        }
17391
17392        @Override
17393        String getResourcePath() {
17394            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17395        }
17396
17397        private boolean cleanUp(String volumeUuid) {
17398            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17399                    move.dataAppName);
17400            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17401            final int[] userIds = sUserManager.getUserIds();
17402            synchronized (mInstallLock) {
17403                // Clean up both app data and code
17404                // All package moves are frozen until finished
17405                for (int userId : userIds) {
17406                    try {
17407                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17408                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17409                    } catch (InstallerException e) {
17410                        Slog.w(TAG, String.valueOf(e));
17411                    }
17412                }
17413                removeCodePathLI(codeFile);
17414            }
17415            return true;
17416        }
17417
17418        void cleanUpResourcesLI() {
17419            throw new UnsupportedOperationException();
17420        }
17421
17422        boolean doPostDeleteLI(boolean delete) {
17423            throw new UnsupportedOperationException();
17424        }
17425    }
17426
17427    static String getAsecPackageName(String packageCid) {
17428        int idx = packageCid.lastIndexOf("-");
17429        if (idx == -1) {
17430            return packageCid;
17431        }
17432        return packageCid.substring(0, idx);
17433    }
17434
17435    // Utility method used to create code paths based on package name and available index.
17436    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17437        String idxStr = "";
17438        int idx = 1;
17439        // Fall back to default value of idx=1 if prefix is not
17440        // part of oldCodePath
17441        if (oldCodePath != null) {
17442            String subStr = oldCodePath;
17443            // Drop the suffix right away
17444            if (suffix != null && subStr.endsWith(suffix)) {
17445                subStr = subStr.substring(0, subStr.length() - suffix.length());
17446            }
17447            // If oldCodePath already contains prefix find out the
17448            // ending index to either increment or decrement.
17449            int sidx = subStr.lastIndexOf(prefix);
17450            if (sidx != -1) {
17451                subStr = subStr.substring(sidx + prefix.length());
17452                if (subStr != null) {
17453                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17454                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17455                    }
17456                    try {
17457                        idx = Integer.parseInt(subStr);
17458                        if (idx <= 1) {
17459                            idx++;
17460                        } else {
17461                            idx--;
17462                        }
17463                    } catch(NumberFormatException e) {
17464                    }
17465                }
17466            }
17467        }
17468        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17469        return prefix + idxStr;
17470    }
17471
17472    private File getNextCodePath(File targetDir, String packageName) {
17473        File result;
17474        SecureRandom random = new SecureRandom();
17475        byte[] bytes = new byte[16];
17476        do {
17477            random.nextBytes(bytes);
17478            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17479            result = new File(targetDir, packageName + "-" + suffix);
17480        } while (result.exists());
17481        return result;
17482    }
17483
17484    // Utility method that returns the relative package path with respect
17485    // to the installation directory. Like say for /data/data/com.test-1.apk
17486    // string com.test-1 is returned.
17487    static String deriveCodePathName(String codePath) {
17488        if (codePath == null) {
17489            return null;
17490        }
17491        final File codeFile = new File(codePath);
17492        final String name = codeFile.getName();
17493        if (codeFile.isDirectory()) {
17494            return name;
17495        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17496            final int lastDot = name.lastIndexOf('.');
17497            return name.substring(0, lastDot);
17498        } else {
17499            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17500            return null;
17501        }
17502    }
17503
17504    static class PackageInstalledInfo {
17505        String name;
17506        int uid;
17507        // The set of users that originally had this package installed.
17508        int[] origUsers;
17509        // The set of users that now have this package installed.
17510        int[] newUsers;
17511        PackageParser.Package pkg;
17512        int returnCode;
17513        String returnMsg;
17514        String installerPackageName;
17515        PackageRemovedInfo removedInfo;
17516        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17517
17518        public void setError(int code, String msg) {
17519            setReturnCode(code);
17520            setReturnMessage(msg);
17521            Slog.w(TAG, msg);
17522        }
17523
17524        public void setError(String msg, PackageParserException e) {
17525            setReturnCode(e.error);
17526            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17527            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17528            for (int i = 0; i < childCount; i++) {
17529                addedChildPackages.valueAt(i).setError(msg, e);
17530            }
17531            Slog.w(TAG, msg, e);
17532        }
17533
17534        public void setError(String msg, PackageManagerException e) {
17535            returnCode = e.error;
17536            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17537            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17538            for (int i = 0; i < childCount; i++) {
17539                addedChildPackages.valueAt(i).setError(msg, e);
17540            }
17541            Slog.w(TAG, msg, e);
17542        }
17543
17544        public void setReturnCode(int returnCode) {
17545            this.returnCode = returnCode;
17546            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17547            for (int i = 0; i < childCount; i++) {
17548                addedChildPackages.valueAt(i).returnCode = returnCode;
17549            }
17550        }
17551
17552        private void setReturnMessage(String returnMsg) {
17553            this.returnMsg = returnMsg;
17554            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17555            for (int i = 0; i < childCount; i++) {
17556                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17557            }
17558        }
17559
17560        // In some error cases we want to convey more info back to the observer
17561        String origPackage;
17562        String origPermission;
17563    }
17564
17565    /*
17566     * Install a non-existing package.
17567     */
17568    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17569            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17570            PackageInstalledInfo res, int installReason) {
17571        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17572
17573        // Remember this for later, in case we need to rollback this install
17574        String pkgName = pkg.packageName;
17575
17576        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17577
17578        synchronized(mPackages) {
17579            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17580            if (renamedPackage != null) {
17581                // A package with the same name is already installed, though
17582                // it has been renamed to an older name.  The package we
17583                // are trying to install should be installed as an update to
17584                // the existing one, but that has not been requested, so bail.
17585                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17586                        + " without first uninstalling package running as "
17587                        + renamedPackage);
17588                return;
17589            }
17590            if (mPackages.containsKey(pkgName)) {
17591                // Don't allow installation over an existing package with the same name.
17592                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17593                        + " without first uninstalling.");
17594                return;
17595            }
17596        }
17597
17598        try {
17599            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17600                    System.currentTimeMillis(), user);
17601
17602            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17603
17604            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17605                prepareAppDataAfterInstallLIF(newPackage);
17606
17607            } else {
17608                // Remove package from internal structures, but keep around any
17609                // data that might have already existed
17610                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17611                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17612            }
17613        } catch (PackageManagerException e) {
17614            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17615        }
17616
17617        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17618    }
17619
17620    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17621        // Can't rotate keys during boot or if sharedUser.
17622        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17623                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17624            return false;
17625        }
17626        // app is using upgradeKeySets; make sure all are valid
17627        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17628        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17629        for (int i = 0; i < upgradeKeySets.length; i++) {
17630            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17631                Slog.wtf(TAG, "Package "
17632                         + (oldPs.name != null ? oldPs.name : "<null>")
17633                         + " contains upgrade-key-set reference to unknown key-set: "
17634                         + upgradeKeySets[i]
17635                         + " reverting to signatures check.");
17636                return false;
17637            }
17638        }
17639        return true;
17640    }
17641
17642    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17643        // Upgrade keysets are being used.  Determine if new package has a superset of the
17644        // required keys.
17645        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17646        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17647        for (int i = 0; i < upgradeKeySets.length; i++) {
17648            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17649            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17650                return true;
17651            }
17652        }
17653        return false;
17654    }
17655
17656    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17657        try (DigestInputStream digestStream =
17658                new DigestInputStream(new FileInputStream(file), digest)) {
17659            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17660        }
17661    }
17662
17663    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17664            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17665            int installReason) {
17666        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17667
17668        final PackageParser.Package oldPackage;
17669        final PackageSetting ps;
17670        final String pkgName = pkg.packageName;
17671        final int[] allUsers;
17672        final int[] installedUsers;
17673
17674        synchronized(mPackages) {
17675            oldPackage = mPackages.get(pkgName);
17676            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17677
17678            // don't allow upgrade to target a release SDK from a pre-release SDK
17679            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17680                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17681            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17682                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17683            if (oldTargetsPreRelease
17684                    && !newTargetsPreRelease
17685                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17686                Slog.w(TAG, "Can't install package targeting released sdk");
17687                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17688                return;
17689            }
17690
17691            ps = mSettings.mPackages.get(pkgName);
17692
17693            // verify signatures are valid
17694            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17695                if (!checkUpgradeKeySetLP(ps, pkg)) {
17696                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17697                            "New package not signed by keys specified by upgrade-keysets: "
17698                                    + pkgName);
17699                    return;
17700                }
17701            } else {
17702                // default to original signature matching
17703                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17704                        != PackageManager.SIGNATURE_MATCH) {
17705                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17706                            "New package has a different signature: " + pkgName);
17707                    return;
17708                }
17709            }
17710
17711            // don't allow a system upgrade unless the upgrade hash matches
17712            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17713                byte[] digestBytes = null;
17714                try {
17715                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17716                    updateDigest(digest, new File(pkg.baseCodePath));
17717                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17718                        for (String path : pkg.splitCodePaths) {
17719                            updateDigest(digest, new File(path));
17720                        }
17721                    }
17722                    digestBytes = digest.digest();
17723                } catch (NoSuchAlgorithmException | IOException e) {
17724                    res.setError(INSTALL_FAILED_INVALID_APK,
17725                            "Could not compute hash: " + pkgName);
17726                    return;
17727                }
17728                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17729                    res.setError(INSTALL_FAILED_INVALID_APK,
17730                            "New package fails restrict-update check: " + pkgName);
17731                    return;
17732                }
17733                // retain upgrade restriction
17734                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17735            }
17736
17737            // Check for shared user id changes
17738            String invalidPackageName =
17739                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17740            if (invalidPackageName != null) {
17741                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17742                        "Package " + invalidPackageName + " tried to change user "
17743                                + oldPackage.mSharedUserId);
17744                return;
17745            }
17746
17747            // check if the new package supports all of the abis which the old package supports
17748            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
17749            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
17750            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
17751                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17752                        "Update to package " + pkgName + " doesn't support multi arch");
17753                return;
17754            }
17755
17756            // In case of rollback, remember per-user/profile install state
17757            allUsers = sUserManager.getUserIds();
17758            installedUsers = ps.queryInstalledUsers(allUsers, true);
17759
17760            // don't allow an upgrade from full to ephemeral
17761            if (isInstantApp) {
17762                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17763                    for (int currentUser : allUsers) {
17764                        if (!ps.getInstantApp(currentUser)) {
17765                            // can't downgrade from full to instant
17766                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17767                                    + " for user: " + currentUser);
17768                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17769                            return;
17770                        }
17771                    }
17772                } else if (!ps.getInstantApp(user.getIdentifier())) {
17773                    // can't downgrade from full to instant
17774                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17775                            + " for user: " + user.getIdentifier());
17776                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17777                    return;
17778                }
17779            }
17780        }
17781
17782        // Update what is removed
17783        res.removedInfo = new PackageRemovedInfo(this);
17784        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17785        res.removedInfo.removedPackage = oldPackage.packageName;
17786        res.removedInfo.installerPackageName = ps.installerPackageName;
17787        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17788        res.removedInfo.isUpdate = true;
17789        res.removedInfo.origUsers = installedUsers;
17790        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17791        for (int i = 0; i < installedUsers.length; i++) {
17792            final int userId = installedUsers[i];
17793            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17794        }
17795
17796        final int childCount = (oldPackage.childPackages != null)
17797                ? oldPackage.childPackages.size() : 0;
17798        for (int i = 0; i < childCount; i++) {
17799            boolean childPackageUpdated = false;
17800            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17801            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17802            if (res.addedChildPackages != null) {
17803                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17804                if (childRes != null) {
17805                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17806                    childRes.removedInfo.removedPackage = childPkg.packageName;
17807                    if (childPs != null) {
17808                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17809                    }
17810                    childRes.removedInfo.isUpdate = true;
17811                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17812                    childPackageUpdated = true;
17813                }
17814            }
17815            if (!childPackageUpdated) {
17816                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17817                childRemovedRes.removedPackage = childPkg.packageName;
17818                if (childPs != null) {
17819                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17820                }
17821                childRemovedRes.isUpdate = false;
17822                childRemovedRes.dataRemoved = true;
17823                synchronized (mPackages) {
17824                    if (childPs != null) {
17825                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17826                    }
17827                }
17828                if (res.removedInfo.removedChildPackages == null) {
17829                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17830                }
17831                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17832            }
17833        }
17834
17835        boolean sysPkg = (isSystemApp(oldPackage));
17836        if (sysPkg) {
17837            // Set the system/privileged flags as needed
17838            final boolean privileged =
17839                    (oldPackage.applicationInfo.privateFlags
17840                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17841            final int systemPolicyFlags = policyFlags
17842                    | PackageParser.PARSE_IS_SYSTEM
17843                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17844
17845            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17846                    user, allUsers, installerPackageName, res, installReason);
17847        } else {
17848            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17849                    user, allUsers, installerPackageName, res, installReason);
17850        }
17851    }
17852
17853    @Override
17854    public List<String> getPreviousCodePaths(String packageName) {
17855        final int callingUid = Binder.getCallingUid();
17856        final List<String> result = new ArrayList<>();
17857        if (getInstantAppPackageName(callingUid) != null) {
17858            return result;
17859        }
17860        final PackageSetting ps = mSettings.mPackages.get(packageName);
17861        if (ps != null
17862                && ps.oldCodePaths != null
17863                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17864            result.addAll(ps.oldCodePaths);
17865        }
17866        return result;
17867    }
17868
17869    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17870            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17871            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17872            int installReason) {
17873        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17874                + deletedPackage);
17875
17876        String pkgName = deletedPackage.packageName;
17877        boolean deletedPkg = true;
17878        boolean addedPkg = false;
17879        boolean updatedSettings = false;
17880        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17881        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17882                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17883
17884        final long origUpdateTime = (pkg.mExtras != null)
17885                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17886
17887        // First delete the existing package while retaining the data directory
17888        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17889                res.removedInfo, true, pkg)) {
17890            // If the existing package wasn't successfully deleted
17891            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17892            deletedPkg = false;
17893        } else {
17894            // Successfully deleted the old package; proceed with replace.
17895
17896            // If deleted package lived in a container, give users a chance to
17897            // relinquish resources before killing.
17898            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17899                if (DEBUG_INSTALL) {
17900                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17901                }
17902                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17903                final ArrayList<String> pkgList = new ArrayList<String>(1);
17904                pkgList.add(deletedPackage.applicationInfo.packageName);
17905                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17906            }
17907
17908            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17909                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17910            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17911
17912            try {
17913                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17914                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17915                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17916                        installReason);
17917
17918                // Update the in-memory copy of the previous code paths.
17919                PackageSetting ps = mSettings.mPackages.get(pkgName);
17920                if (!killApp) {
17921                    if (ps.oldCodePaths == null) {
17922                        ps.oldCodePaths = new ArraySet<>();
17923                    }
17924                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17925                    if (deletedPackage.splitCodePaths != null) {
17926                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17927                    }
17928                } else {
17929                    ps.oldCodePaths = null;
17930                }
17931                if (ps.childPackageNames != null) {
17932                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17933                        final String childPkgName = ps.childPackageNames.get(i);
17934                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17935                        childPs.oldCodePaths = ps.oldCodePaths;
17936                    }
17937                }
17938                // set instant app status, but, only if it's explicitly specified
17939                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17940                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17941                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17942                prepareAppDataAfterInstallLIF(newPackage);
17943                addedPkg = true;
17944                mDexManager.notifyPackageUpdated(newPackage.packageName,
17945                        newPackage.baseCodePath, newPackage.splitCodePaths);
17946            } catch (PackageManagerException e) {
17947                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17948            }
17949        }
17950
17951        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17952            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17953
17954            // Revert all internal state mutations and added folders for the failed install
17955            if (addedPkg) {
17956                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17957                        res.removedInfo, true, null);
17958            }
17959
17960            // Restore the old package
17961            if (deletedPkg) {
17962                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17963                File restoreFile = new File(deletedPackage.codePath);
17964                // Parse old package
17965                boolean oldExternal = isExternal(deletedPackage);
17966                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17967                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17968                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17969                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17970                try {
17971                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17972                            null);
17973                } catch (PackageManagerException e) {
17974                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17975                            + e.getMessage());
17976                    return;
17977                }
17978
17979                synchronized (mPackages) {
17980                    // Ensure the installer package name up to date
17981                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17982
17983                    // Update permissions for restored package
17984                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17985
17986                    mSettings.writeLPr();
17987                }
17988
17989                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17990            }
17991        } else {
17992            synchronized (mPackages) {
17993                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17994                if (ps != null) {
17995                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17996                    if (res.removedInfo.removedChildPackages != null) {
17997                        final int childCount = res.removedInfo.removedChildPackages.size();
17998                        // Iterate in reverse as we may modify the collection
17999                        for (int i = childCount - 1; i >= 0; i--) {
18000                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
18001                            if (res.addedChildPackages.containsKey(childPackageName)) {
18002                                res.removedInfo.removedChildPackages.removeAt(i);
18003                            } else {
18004                                PackageRemovedInfo childInfo = res.removedInfo
18005                                        .removedChildPackages.valueAt(i);
18006                                childInfo.removedForAllUsers = mPackages.get(
18007                                        childInfo.removedPackage) == null;
18008                            }
18009                        }
18010                    }
18011                }
18012            }
18013        }
18014    }
18015
18016    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
18017            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
18018            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
18019            int installReason) {
18020        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
18021                + ", old=" + deletedPackage);
18022
18023        final boolean disabledSystem;
18024
18025        // Remove existing system package
18026        removePackageLI(deletedPackage, true);
18027
18028        synchronized (mPackages) {
18029            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
18030        }
18031        if (!disabledSystem) {
18032            // We didn't need to disable the .apk as a current system package,
18033            // which means we are replacing another update that is already
18034            // installed.  We need to make sure to delete the older one's .apk.
18035            res.removedInfo.args = createInstallArgsForExisting(0,
18036                    deletedPackage.applicationInfo.getCodePath(),
18037                    deletedPackage.applicationInfo.getResourcePath(),
18038                    getAppDexInstructionSets(deletedPackage.applicationInfo));
18039        } else {
18040            res.removedInfo.args = null;
18041        }
18042
18043        // Successfully disabled the old package. Now proceed with re-installation
18044        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
18045                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18046        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
18047
18048        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18049        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
18050                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
18051
18052        PackageParser.Package newPackage = null;
18053        try {
18054            // Add the package to the internal data structures
18055            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
18056
18057            // Set the update and install times
18058            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
18059            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
18060                    System.currentTimeMillis());
18061
18062            // Update the package dynamic state if succeeded
18063            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18064                // Now that the install succeeded make sure we remove data
18065                // directories for any child package the update removed.
18066                final int deletedChildCount = (deletedPackage.childPackages != null)
18067                        ? deletedPackage.childPackages.size() : 0;
18068                final int newChildCount = (newPackage.childPackages != null)
18069                        ? newPackage.childPackages.size() : 0;
18070                for (int i = 0; i < deletedChildCount; i++) {
18071                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
18072                    boolean childPackageDeleted = true;
18073                    for (int j = 0; j < newChildCount; j++) {
18074                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
18075                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
18076                            childPackageDeleted = false;
18077                            break;
18078                        }
18079                    }
18080                    if (childPackageDeleted) {
18081                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
18082                                deletedChildPkg.packageName);
18083                        if (ps != null && res.removedInfo.removedChildPackages != null) {
18084                            PackageRemovedInfo removedChildRes = res.removedInfo
18085                                    .removedChildPackages.get(deletedChildPkg.packageName);
18086                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
18087                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
18088                        }
18089                    }
18090                }
18091
18092                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
18093                        installReason);
18094                prepareAppDataAfterInstallLIF(newPackage);
18095
18096                mDexManager.notifyPackageUpdated(newPackage.packageName,
18097                            newPackage.baseCodePath, newPackage.splitCodePaths);
18098            }
18099        } catch (PackageManagerException e) {
18100            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
18101            res.setError("Package couldn't be installed in " + pkg.codePath, e);
18102        }
18103
18104        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
18105            // Re installation failed. Restore old information
18106            // Remove new pkg information
18107            if (newPackage != null) {
18108                removeInstalledPackageLI(newPackage, true);
18109            }
18110            // Add back the old system package
18111            try {
18112                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
18113            } catch (PackageManagerException e) {
18114                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
18115            }
18116
18117            synchronized (mPackages) {
18118                if (disabledSystem) {
18119                    enableSystemPackageLPw(deletedPackage);
18120                }
18121
18122                // Ensure the installer package name up to date
18123                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
18124
18125                // Update permissions for restored package
18126                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
18127
18128                mSettings.writeLPr();
18129            }
18130
18131            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
18132                    + " after failed upgrade");
18133        }
18134    }
18135
18136    /**
18137     * Checks whether the parent or any of the child packages have a change shared
18138     * user. For a package to be a valid update the shred users of the parent and
18139     * the children should match. We may later support changing child shared users.
18140     * @param oldPkg The updated package.
18141     * @param newPkg The update package.
18142     * @return The shared user that change between the versions.
18143     */
18144    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
18145            PackageParser.Package newPkg) {
18146        // Check parent shared user
18147        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
18148            return newPkg.packageName;
18149        }
18150        // Check child shared users
18151        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18152        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
18153        for (int i = 0; i < newChildCount; i++) {
18154            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
18155            // If this child was present, did it have the same shared user?
18156            for (int j = 0; j < oldChildCount; j++) {
18157                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
18158                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
18159                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
18160                    return newChildPkg.packageName;
18161                }
18162            }
18163        }
18164        return null;
18165    }
18166
18167    private void removeNativeBinariesLI(PackageSetting ps) {
18168        // Remove the lib path for the parent package
18169        if (ps != null) {
18170            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
18171            // Remove the lib path for the child packages
18172            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18173            for (int i = 0; i < childCount; i++) {
18174                PackageSetting childPs = null;
18175                synchronized (mPackages) {
18176                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18177                }
18178                if (childPs != null) {
18179                    NativeLibraryHelper.removeNativeBinariesLI(childPs
18180                            .legacyNativeLibraryPathString);
18181                }
18182            }
18183        }
18184    }
18185
18186    private void enableSystemPackageLPw(PackageParser.Package pkg) {
18187        // Enable the parent package
18188        mSettings.enableSystemPackageLPw(pkg.packageName);
18189        // Enable the child packages
18190        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18191        for (int i = 0; i < childCount; i++) {
18192            PackageParser.Package childPkg = pkg.childPackages.get(i);
18193            mSettings.enableSystemPackageLPw(childPkg.packageName);
18194        }
18195    }
18196
18197    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
18198            PackageParser.Package newPkg) {
18199        // Disable the parent package (parent always replaced)
18200        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
18201        // Disable the child packages
18202        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18203        for (int i = 0; i < childCount; i++) {
18204            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
18205            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
18206            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
18207        }
18208        return disabled;
18209    }
18210
18211    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
18212            String installerPackageName) {
18213        // Enable the parent package
18214        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
18215        // Enable the child packages
18216        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18217        for (int i = 0; i < childCount; i++) {
18218            PackageParser.Package childPkg = pkg.childPackages.get(i);
18219            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
18220        }
18221    }
18222
18223    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
18224        // Collect all used permissions in the UID
18225        ArraySet<String> usedPermissions = new ArraySet<>();
18226        final int packageCount = su.packages.size();
18227        for (int i = 0; i < packageCount; i++) {
18228            PackageSetting ps = su.packages.valueAt(i);
18229            if (ps.pkg == null) {
18230                continue;
18231            }
18232            final int requestedPermCount = ps.pkg.requestedPermissions.size();
18233            for (int j = 0; j < requestedPermCount; j++) {
18234                String permission = ps.pkg.requestedPermissions.get(j);
18235                BasePermission bp = mSettings.mPermissions.get(permission);
18236                if (bp != null) {
18237                    usedPermissions.add(permission);
18238                }
18239            }
18240        }
18241
18242        PermissionsState permissionsState = su.getPermissionsState();
18243        // Prune install permissions
18244        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18245        final int installPermCount = installPermStates.size();
18246        for (int i = installPermCount - 1; i >= 0;  i--) {
18247            PermissionState permissionState = installPermStates.get(i);
18248            if (!usedPermissions.contains(permissionState.getName())) {
18249                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18250                if (bp != null) {
18251                    permissionsState.revokeInstallPermission(bp);
18252                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18253                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18254                }
18255            }
18256        }
18257
18258        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18259
18260        // Prune runtime permissions
18261        for (int userId : allUserIds) {
18262            List<PermissionState> runtimePermStates = permissionsState
18263                    .getRuntimePermissionStates(userId);
18264            final int runtimePermCount = runtimePermStates.size();
18265            for (int i = runtimePermCount - 1; i >= 0; i--) {
18266                PermissionState permissionState = runtimePermStates.get(i);
18267                if (!usedPermissions.contains(permissionState.getName())) {
18268                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18269                    if (bp != null) {
18270                        permissionsState.revokeRuntimePermission(bp, userId);
18271                        permissionsState.updatePermissionFlags(bp, userId,
18272                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18273                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18274                                runtimePermissionChangedUserIds, userId);
18275                    }
18276                }
18277            }
18278        }
18279
18280        return runtimePermissionChangedUserIds;
18281    }
18282
18283    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18284            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18285        // Update the parent package setting
18286        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18287                res, user, installReason);
18288        // Update the child packages setting
18289        final int childCount = (newPackage.childPackages != null)
18290                ? newPackage.childPackages.size() : 0;
18291        for (int i = 0; i < childCount; i++) {
18292            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18293            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18294            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18295                    childRes.origUsers, childRes, user, installReason);
18296        }
18297    }
18298
18299    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18300            String installerPackageName, int[] allUsers, int[] installedForUsers,
18301            PackageInstalledInfo res, UserHandle user, int installReason) {
18302        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18303
18304        String pkgName = newPackage.packageName;
18305        synchronized (mPackages) {
18306            //write settings. the installStatus will be incomplete at this stage.
18307            //note that the new package setting would have already been
18308            //added to mPackages. It hasn't been persisted yet.
18309            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18310            // TODO: Remove this write? It's also written at the end of this method
18311            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18312            mSettings.writeLPr();
18313            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18314        }
18315
18316        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18317        synchronized (mPackages) {
18318            updatePermissionsLPw(newPackage.packageName, newPackage,
18319                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18320                            ? UPDATE_PERMISSIONS_ALL : 0));
18321            // For system-bundled packages, we assume that installing an upgraded version
18322            // of the package implies that the user actually wants to run that new code,
18323            // so we enable the package.
18324            PackageSetting ps = mSettings.mPackages.get(pkgName);
18325            final int userId = user.getIdentifier();
18326            if (ps != null) {
18327                if (isSystemApp(newPackage)) {
18328                    if (DEBUG_INSTALL) {
18329                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18330                    }
18331                    // Enable system package for requested users
18332                    if (res.origUsers != null) {
18333                        for (int origUserId : res.origUsers) {
18334                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18335                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18336                                        origUserId, installerPackageName);
18337                            }
18338                        }
18339                    }
18340                    // Also convey the prior install/uninstall state
18341                    if (allUsers != null && installedForUsers != null) {
18342                        for (int currentUserId : allUsers) {
18343                            final boolean installed = ArrayUtils.contains(
18344                                    installedForUsers, currentUserId);
18345                            if (DEBUG_INSTALL) {
18346                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18347                            }
18348                            ps.setInstalled(installed, currentUserId);
18349                        }
18350                        // these install state changes will be persisted in the
18351                        // upcoming call to mSettings.writeLPr().
18352                    }
18353                }
18354                // It's implied that when a user requests installation, they want the app to be
18355                // installed and enabled.
18356                if (userId != UserHandle.USER_ALL) {
18357                    ps.setInstalled(true, userId);
18358                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18359                }
18360
18361                // When replacing an existing package, preserve the original install reason for all
18362                // users that had the package installed before.
18363                final Set<Integer> previousUserIds = new ArraySet<>();
18364                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18365                    final int installReasonCount = res.removedInfo.installReasons.size();
18366                    for (int i = 0; i < installReasonCount; i++) {
18367                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18368                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18369                        ps.setInstallReason(previousInstallReason, previousUserId);
18370                        previousUserIds.add(previousUserId);
18371                    }
18372                }
18373
18374                // Set install reason for users that are having the package newly installed.
18375                if (userId == UserHandle.USER_ALL) {
18376                    for (int currentUserId : sUserManager.getUserIds()) {
18377                        if (!previousUserIds.contains(currentUserId)) {
18378                            ps.setInstallReason(installReason, currentUserId);
18379                        }
18380                    }
18381                } else if (!previousUserIds.contains(userId)) {
18382                    ps.setInstallReason(installReason, userId);
18383                }
18384                mSettings.writeKernelMappingLPr(ps);
18385            }
18386            res.name = pkgName;
18387            res.uid = newPackage.applicationInfo.uid;
18388            res.pkg = newPackage;
18389            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18390            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18391            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18392            //to update install status
18393            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18394            mSettings.writeLPr();
18395            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18396        }
18397
18398        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18399    }
18400
18401    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18402        try {
18403            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18404            installPackageLI(args, res);
18405        } finally {
18406            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18407        }
18408    }
18409
18410    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18411        final int installFlags = args.installFlags;
18412        final String installerPackageName = args.installerPackageName;
18413        final String volumeUuid = args.volumeUuid;
18414        final File tmpPackageFile = new File(args.getCodePath());
18415        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18416        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18417                || (args.volumeUuid != null));
18418        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18419        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18420        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18421        final boolean virtualPreload =
18422                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18423        boolean replace = false;
18424        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18425        if (args.move != null) {
18426            // moving a complete application; perform an initial scan on the new install location
18427            scanFlags |= SCAN_INITIAL;
18428        }
18429        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18430            scanFlags |= SCAN_DONT_KILL_APP;
18431        }
18432        if (instantApp) {
18433            scanFlags |= SCAN_AS_INSTANT_APP;
18434        }
18435        if (fullApp) {
18436            scanFlags |= SCAN_AS_FULL_APP;
18437        }
18438        if (virtualPreload) {
18439            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18440        }
18441
18442        // Result object to be returned
18443        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18444        res.installerPackageName = installerPackageName;
18445
18446        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18447
18448        // Sanity check
18449        if (instantApp && (forwardLocked || onExternal)) {
18450            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18451                    + " external=" + onExternal);
18452            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18453            return;
18454        }
18455
18456        // Retrieve PackageSettings and parse package
18457        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18458                | PackageParser.PARSE_ENFORCE_CODE
18459                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18460                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18461                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18462                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18463        PackageParser pp = new PackageParser();
18464        pp.setSeparateProcesses(mSeparateProcesses);
18465        pp.setDisplayMetrics(mMetrics);
18466        pp.setCallback(mPackageParserCallback);
18467
18468        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18469        final PackageParser.Package pkg;
18470        try {
18471            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18472        } catch (PackageParserException e) {
18473            res.setError("Failed parse during installPackageLI", e);
18474            return;
18475        } finally {
18476            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18477        }
18478
18479        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18480        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18481            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18482            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18483                    "Instant app package must target O");
18484            return;
18485        }
18486        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18487            Slog.w(TAG, "Instant app package " + pkg.packageName
18488                    + " does not target targetSandboxVersion 2");
18489            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18490                    "Instant app package must use targetSanboxVersion 2");
18491            return;
18492        }
18493
18494        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18495            // Static shared libraries have synthetic package names
18496            renameStaticSharedLibraryPackage(pkg);
18497
18498            // No static shared libs on external storage
18499            if (onExternal) {
18500                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18501                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18502                        "Packages declaring static-shared libs cannot be updated");
18503                return;
18504            }
18505        }
18506
18507        // If we are installing a clustered package add results for the children
18508        if (pkg.childPackages != null) {
18509            synchronized (mPackages) {
18510                final int childCount = pkg.childPackages.size();
18511                for (int i = 0; i < childCount; i++) {
18512                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18513                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18514                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18515                    childRes.pkg = childPkg;
18516                    childRes.name = childPkg.packageName;
18517                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18518                    if (childPs != null) {
18519                        childRes.origUsers = childPs.queryInstalledUsers(
18520                                sUserManager.getUserIds(), true);
18521                    }
18522                    if ((mPackages.containsKey(childPkg.packageName))) {
18523                        childRes.removedInfo = new PackageRemovedInfo(this);
18524                        childRes.removedInfo.removedPackage = childPkg.packageName;
18525                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18526                    }
18527                    if (res.addedChildPackages == null) {
18528                        res.addedChildPackages = new ArrayMap<>();
18529                    }
18530                    res.addedChildPackages.put(childPkg.packageName, childRes);
18531                }
18532            }
18533        }
18534
18535        // If package doesn't declare API override, mark that we have an install
18536        // time CPU ABI override.
18537        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18538            pkg.cpuAbiOverride = args.abiOverride;
18539        }
18540
18541        String pkgName = res.name = pkg.packageName;
18542        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18543            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18544                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18545                return;
18546            }
18547        }
18548
18549        try {
18550            // either use what we've been given or parse directly from the APK
18551            if (args.certificates != null) {
18552                try {
18553                    PackageParser.populateCertificates(pkg, args.certificates);
18554                } catch (PackageParserException e) {
18555                    // there was something wrong with the certificates we were given;
18556                    // try to pull them from the APK
18557                    PackageParser.collectCertificates(pkg, parseFlags);
18558                }
18559            } else {
18560                PackageParser.collectCertificates(pkg, parseFlags);
18561            }
18562        } catch (PackageParserException e) {
18563            res.setError("Failed collect during installPackageLI", e);
18564            return;
18565        }
18566
18567        // Get rid of all references to package scan path via parser.
18568        pp = null;
18569        String oldCodePath = null;
18570        boolean systemApp = false;
18571        synchronized (mPackages) {
18572            // Check if installing already existing package
18573            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18574                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18575                if (pkg.mOriginalPackages != null
18576                        && pkg.mOriginalPackages.contains(oldName)
18577                        && mPackages.containsKey(oldName)) {
18578                    // This package is derived from an original package,
18579                    // and this device has been updating from that original
18580                    // name.  We must continue using the original name, so
18581                    // rename the new package here.
18582                    pkg.setPackageName(oldName);
18583                    pkgName = pkg.packageName;
18584                    replace = true;
18585                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18586                            + oldName + " pkgName=" + pkgName);
18587                } else if (mPackages.containsKey(pkgName)) {
18588                    // This package, under its official name, already exists
18589                    // on the device; we should replace it.
18590                    replace = true;
18591                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18592                }
18593
18594                // Child packages are installed through the parent package
18595                if (pkg.parentPackage != null) {
18596                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18597                            "Package " + pkg.packageName + " is child of package "
18598                                    + pkg.parentPackage.parentPackage + ". Child packages "
18599                                    + "can be updated only through the parent package.");
18600                    return;
18601                }
18602
18603                if (replace) {
18604                    // Prevent apps opting out from runtime permissions
18605                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18606                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18607                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18608                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18609                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18610                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18611                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18612                                        + " doesn't support runtime permissions but the old"
18613                                        + " target SDK " + oldTargetSdk + " does.");
18614                        return;
18615                    }
18616                    // Prevent persistent apps from being updated
18617                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
18618                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
18619                                "Package " + oldPackage.packageName + " is a persistent app. "
18620                                        + "Persistent apps are not updateable.");
18621                        return;
18622                    }
18623                    // Prevent apps from downgrading their targetSandbox.
18624                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18625                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18626                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18627                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18628                                "Package " + pkg.packageName + " new target sandbox "
18629                                + newTargetSandbox + " is incompatible with the previous value of"
18630                                + oldTargetSandbox + ".");
18631                        return;
18632                    }
18633
18634                    // Prevent installing of child packages
18635                    if (oldPackage.parentPackage != null) {
18636                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18637                                "Package " + pkg.packageName + " is child of package "
18638                                        + oldPackage.parentPackage + ". Child packages "
18639                                        + "can be updated only through the parent package.");
18640                        return;
18641                    }
18642                }
18643            }
18644
18645            PackageSetting ps = mSettings.mPackages.get(pkgName);
18646            if (ps != null) {
18647                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18648
18649                // Static shared libs have same package with different versions where
18650                // we internally use a synthetic package name to allow multiple versions
18651                // of the same package, therefore we need to compare signatures against
18652                // the package setting for the latest library version.
18653                PackageSetting signatureCheckPs = ps;
18654                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18655                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18656                    if (libraryEntry != null) {
18657                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18658                    }
18659                }
18660
18661                // Quick sanity check that we're signed correctly if updating;
18662                // we'll check this again later when scanning, but we want to
18663                // bail early here before tripping over redefined permissions.
18664                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18665                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18666                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18667                                + pkg.packageName + " upgrade keys do not match the "
18668                                + "previously installed version");
18669                        return;
18670                    }
18671                } else {
18672                    try {
18673                        verifySignaturesLP(signatureCheckPs, pkg);
18674                    } catch (PackageManagerException e) {
18675                        res.setError(e.error, e.getMessage());
18676                        return;
18677                    }
18678                }
18679
18680                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18681                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18682                    systemApp = (ps.pkg.applicationInfo.flags &
18683                            ApplicationInfo.FLAG_SYSTEM) != 0;
18684                }
18685                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18686            }
18687
18688            int N = pkg.permissions.size();
18689            for (int i = N-1; i >= 0; i--) {
18690                PackageParser.Permission perm = pkg.permissions.get(i);
18691                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18692
18693                // Don't allow anyone but the system to define ephemeral permissions.
18694                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
18695                        && !systemApp) {
18696                    Slog.w(TAG, "Non-System package " + pkg.packageName
18697                            + " attempting to delcare ephemeral permission "
18698                            + perm.info.name + "; Removing ephemeral.");
18699                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
18700                }
18701                // Check whether the newly-scanned package wants to define an already-defined perm
18702                if (bp != null) {
18703                    // If the defining package is signed with our cert, it's okay.  This
18704                    // also includes the "updating the same package" case, of course.
18705                    // "updating same package" could also involve key-rotation.
18706                    final boolean sigsOk;
18707                    if (bp.sourcePackage.equals(pkg.packageName)
18708                            && (bp.packageSetting instanceof PackageSetting)
18709                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18710                                    scanFlags))) {
18711                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18712                    } else {
18713                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18714                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18715                    }
18716                    if (!sigsOk) {
18717                        // If the owning package is the system itself, we log but allow
18718                        // install to proceed; we fail the install on all other permission
18719                        // redefinitions.
18720                        if (!bp.sourcePackage.equals("android")) {
18721                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18722                                    + pkg.packageName + " attempting to redeclare permission "
18723                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18724                            res.origPermission = perm.info.name;
18725                            res.origPackage = bp.sourcePackage;
18726                            return;
18727                        } else {
18728                            Slog.w(TAG, "Package " + pkg.packageName
18729                                    + " attempting to redeclare system permission "
18730                                    + perm.info.name + "; ignoring new declaration");
18731                            pkg.permissions.remove(i);
18732                        }
18733                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18734                        // Prevent apps to change protection level to dangerous from any other
18735                        // type as this would allow a privilege escalation where an app adds a
18736                        // normal/signature permission in other app's group and later redefines
18737                        // it as dangerous leading to the group auto-grant.
18738                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18739                                == PermissionInfo.PROTECTION_DANGEROUS) {
18740                            if (bp != null && !bp.isRuntime()) {
18741                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18742                                        + "non-runtime permission " + perm.info.name
18743                                        + " to runtime; keeping old protection level");
18744                                perm.info.protectionLevel = bp.protectionLevel;
18745                            }
18746                        }
18747                    }
18748                }
18749            }
18750        }
18751
18752        if (systemApp) {
18753            if (onExternal) {
18754                // Abort update; system app can't be replaced with app on sdcard
18755                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18756                        "Cannot install updates to system apps on sdcard");
18757                return;
18758            } else if (instantApp) {
18759                // Abort update; system app can't be replaced with an instant app
18760                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18761                        "Cannot update a system app with an instant app");
18762                return;
18763            }
18764        }
18765
18766        if (args.move != null) {
18767            // We did an in-place move, so dex is ready to roll
18768            scanFlags |= SCAN_NO_DEX;
18769            scanFlags |= SCAN_MOVE;
18770
18771            synchronized (mPackages) {
18772                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18773                if (ps == null) {
18774                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18775                            "Missing settings for moved package " + pkgName);
18776                }
18777
18778                // We moved the entire application as-is, so bring over the
18779                // previously derived ABI information.
18780                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18781                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18782            }
18783
18784        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18785            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18786            scanFlags |= SCAN_NO_DEX;
18787
18788            try {
18789                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18790                    args.abiOverride : pkg.cpuAbiOverride);
18791                final boolean extractNativeLibs = !pkg.isLibrary();
18792                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18793                        extractNativeLibs, mAppLib32InstallDir);
18794            } catch (PackageManagerException pme) {
18795                Slog.e(TAG, "Error deriving application ABI", pme);
18796                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18797                return;
18798            }
18799
18800            // Shared libraries for the package need to be updated.
18801            synchronized (mPackages) {
18802                try {
18803                    updateSharedLibrariesLPr(pkg, null);
18804                } catch (PackageManagerException e) {
18805                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18806                }
18807            }
18808        }
18809
18810        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18811            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18812            return;
18813        }
18814
18815        if (!instantApp) {
18816            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18817        } else {
18818            if (DEBUG_DOMAIN_VERIFICATION) {
18819                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
18820            }
18821        }
18822
18823        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18824                "installPackageLI")) {
18825            if (replace) {
18826                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18827                    // Static libs have a synthetic package name containing the version
18828                    // and cannot be updated as an update would get a new package name,
18829                    // unless this is the exact same version code which is useful for
18830                    // development.
18831                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18832                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18833                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18834                                + "static-shared libs cannot be updated");
18835                        return;
18836                    }
18837                }
18838                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18839                        installerPackageName, res, args.installReason);
18840            } else {
18841                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18842                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18843            }
18844        }
18845
18846        // Check whether we need to dexopt the app.
18847        //
18848        // NOTE: it is IMPORTANT to call dexopt:
18849        //   - after doRename which will sync the package data from PackageParser.Package and its
18850        //     corresponding ApplicationInfo.
18851        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
18852        //     uid of the application (pkg.applicationInfo.uid).
18853        //     This update happens in place!
18854        //
18855        // We only need to dexopt if the package meets ALL of the following conditions:
18856        //   1) it is not forward locked.
18857        //   2) it is not on on an external ASEC container.
18858        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18859        //
18860        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18861        // complete, so we skip this step during installation. Instead, we'll take extra time
18862        // the first time the instant app starts. It's preferred to do it this way to provide
18863        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18864        // middle of running an instant app. The default behaviour can be overridden
18865        // via gservices.
18866        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
18867                && !forwardLocked
18868                && !pkg.applicationInfo.isExternalAsec()
18869                && (!instantApp || Global.getInt(mContext.getContentResolver(),
18870                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18871
18872        if (performDexopt) {
18873            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18874            // Do not run PackageDexOptimizer through the local performDexOpt
18875            // method because `pkg` may not be in `mPackages` yet.
18876            //
18877            // Also, don't fail application installs if the dexopt step fails.
18878            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18879                    REASON_INSTALL,
18880                    DexoptOptions.DEXOPT_BOOT_COMPLETE);
18881            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18882                    null /* instructionSets */,
18883                    getOrCreateCompilerPackageStats(pkg),
18884                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18885                    dexoptOptions);
18886            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18887        }
18888
18889        // Notify BackgroundDexOptService that the package has been changed.
18890        // If this is an update of a package which used to fail to compile,
18891        // BackgroundDexOptService will remove it from its blacklist.
18892        // TODO: Layering violation
18893        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18894
18895        synchronized (mPackages) {
18896            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18897            if (ps != null) {
18898                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18899                ps.setUpdateAvailable(false /*updateAvailable*/);
18900            }
18901
18902            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18903            for (int i = 0; i < childCount; i++) {
18904                PackageParser.Package childPkg = pkg.childPackages.get(i);
18905                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18906                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18907                if (childPs != null) {
18908                    childRes.newUsers = childPs.queryInstalledUsers(
18909                            sUserManager.getUserIds(), true);
18910                }
18911            }
18912
18913            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18914                updateSequenceNumberLP(ps, res.newUsers);
18915                updateInstantAppInstallerLocked(pkgName);
18916            }
18917        }
18918    }
18919
18920    private void startIntentFilterVerifications(int userId, boolean replacing,
18921            PackageParser.Package pkg) {
18922        if (mIntentFilterVerifierComponent == null) {
18923            Slog.w(TAG, "No IntentFilter verification will not be done as "
18924                    + "there is no IntentFilterVerifier available!");
18925            return;
18926        }
18927
18928        final int verifierUid = getPackageUid(
18929                mIntentFilterVerifierComponent.getPackageName(),
18930                MATCH_DEBUG_TRIAGED_MISSING,
18931                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18932
18933        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18934        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18935        mHandler.sendMessage(msg);
18936
18937        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18938        for (int i = 0; i < childCount; i++) {
18939            PackageParser.Package childPkg = pkg.childPackages.get(i);
18940            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18941            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18942            mHandler.sendMessage(msg);
18943        }
18944    }
18945
18946    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18947            PackageParser.Package pkg) {
18948        int size = pkg.activities.size();
18949        if (size == 0) {
18950            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18951                    "No activity, so no need to verify any IntentFilter!");
18952            return;
18953        }
18954
18955        final boolean hasDomainURLs = hasDomainURLs(pkg);
18956        if (!hasDomainURLs) {
18957            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18958                    "No domain URLs, so no need to verify any IntentFilter!");
18959            return;
18960        }
18961
18962        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18963                + " if any IntentFilter from the " + size
18964                + " Activities needs verification ...");
18965
18966        int count = 0;
18967        final String packageName = pkg.packageName;
18968
18969        synchronized (mPackages) {
18970            // If this is a new install and we see that we've already run verification for this
18971            // package, we have nothing to do: it means the state was restored from backup.
18972            if (!replacing) {
18973                IntentFilterVerificationInfo ivi =
18974                        mSettings.getIntentFilterVerificationLPr(packageName);
18975                if (ivi != null) {
18976                    if (DEBUG_DOMAIN_VERIFICATION) {
18977                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18978                                + ivi.getStatusString());
18979                    }
18980                    return;
18981                }
18982            }
18983
18984            // If any filters need to be verified, then all need to be.
18985            boolean needToVerify = false;
18986            for (PackageParser.Activity a : pkg.activities) {
18987                for (ActivityIntentInfo filter : a.intents) {
18988                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18989                        if (DEBUG_DOMAIN_VERIFICATION) {
18990                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18991                        }
18992                        needToVerify = true;
18993                        break;
18994                    }
18995                }
18996            }
18997
18998            if (needToVerify) {
18999                final int verificationId = mIntentFilterVerificationToken++;
19000                for (PackageParser.Activity a : pkg.activities) {
19001                    for (ActivityIntentInfo filter : a.intents) {
19002                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
19003                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
19004                                    "Verification needed for IntentFilter:" + filter.toString());
19005                            mIntentFilterVerifier.addOneIntentFilterVerification(
19006                                    verifierUid, userId, verificationId, filter, packageName);
19007                            count++;
19008                        }
19009                    }
19010                }
19011            }
19012        }
19013
19014        if (count > 0) {
19015            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
19016                    + " IntentFilter verification" + (count > 1 ? "s" : "")
19017                    +  " for userId:" + userId);
19018            mIntentFilterVerifier.startVerifications(userId);
19019        } else {
19020            if (DEBUG_DOMAIN_VERIFICATION) {
19021                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
19022            }
19023        }
19024    }
19025
19026    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
19027        final ComponentName cn  = filter.activity.getComponentName();
19028        final String packageName = cn.getPackageName();
19029
19030        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
19031                packageName);
19032        if (ivi == null) {
19033            return true;
19034        }
19035        int status = ivi.getStatus();
19036        switch (status) {
19037            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
19038            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
19039                return true;
19040
19041            default:
19042                // Nothing to do
19043                return false;
19044        }
19045    }
19046
19047    private static boolean isMultiArch(ApplicationInfo info) {
19048        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
19049    }
19050
19051    private static boolean isExternal(PackageParser.Package pkg) {
19052        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
19053    }
19054
19055    private static boolean isExternal(PackageSetting ps) {
19056        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
19057    }
19058
19059    private static boolean isSystemApp(PackageParser.Package pkg) {
19060        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
19061    }
19062
19063    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
19064        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
19065    }
19066
19067    private static boolean hasDomainURLs(PackageParser.Package pkg) {
19068        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
19069    }
19070
19071    private static boolean isSystemApp(PackageSetting ps) {
19072        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
19073    }
19074
19075    private static boolean isUpdatedSystemApp(PackageSetting ps) {
19076        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
19077    }
19078
19079    private int packageFlagsToInstallFlags(PackageSetting ps) {
19080        int installFlags = 0;
19081        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
19082            // This existing package was an external ASEC install when we have
19083            // the external flag without a UUID
19084            installFlags |= PackageManager.INSTALL_EXTERNAL;
19085        }
19086        if (ps.isForwardLocked()) {
19087            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
19088        }
19089        return installFlags;
19090    }
19091
19092    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
19093        if (isExternal(pkg)) {
19094            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19095                return StorageManager.UUID_PRIMARY_PHYSICAL;
19096            } else {
19097                return pkg.volumeUuid;
19098            }
19099        } else {
19100            return StorageManager.UUID_PRIVATE_INTERNAL;
19101        }
19102    }
19103
19104    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
19105        if (isExternal(pkg)) {
19106            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19107                return mSettings.getExternalVersion();
19108            } else {
19109                return mSettings.findOrCreateVersion(pkg.volumeUuid);
19110            }
19111        } else {
19112            return mSettings.getInternalVersion();
19113        }
19114    }
19115
19116    private void deleteTempPackageFiles() {
19117        final FilenameFilter filter = new FilenameFilter() {
19118            public boolean accept(File dir, String name) {
19119                return name.startsWith("vmdl") && name.endsWith(".tmp");
19120            }
19121        };
19122        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
19123            file.delete();
19124        }
19125    }
19126
19127    @Override
19128    public void deletePackageAsUser(String packageName, int versionCode,
19129            IPackageDeleteObserver observer, int userId, int flags) {
19130        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
19131                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
19132    }
19133
19134    @Override
19135    public void deletePackageVersioned(VersionedPackage versionedPackage,
19136            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
19137        final int callingUid = Binder.getCallingUid();
19138        mContext.enforceCallingOrSelfPermission(
19139                android.Manifest.permission.DELETE_PACKAGES, null);
19140        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
19141        Preconditions.checkNotNull(versionedPackage);
19142        Preconditions.checkNotNull(observer);
19143        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
19144                PackageManager.VERSION_CODE_HIGHEST,
19145                Integer.MAX_VALUE, "versionCode must be >= -1");
19146
19147        final String packageName = versionedPackage.getPackageName();
19148        final int versionCode = versionedPackage.getVersionCode();
19149        final String internalPackageName;
19150        synchronized (mPackages) {
19151            // Normalize package name to handle renamed packages and static libs
19152            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
19153                    versionedPackage.getVersionCode());
19154        }
19155
19156        final int uid = Binder.getCallingUid();
19157        if (!isOrphaned(internalPackageName)
19158                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
19159            try {
19160                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
19161                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
19162                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
19163                observer.onUserActionRequired(intent);
19164            } catch (RemoteException re) {
19165            }
19166            return;
19167        }
19168        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
19169        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
19170        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
19171            mContext.enforceCallingOrSelfPermission(
19172                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
19173                    "deletePackage for user " + userId);
19174        }
19175
19176        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
19177            try {
19178                observer.onPackageDeleted(packageName,
19179                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
19180            } catch (RemoteException re) {
19181            }
19182            return;
19183        }
19184
19185        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
19186            try {
19187                observer.onPackageDeleted(packageName,
19188                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
19189            } catch (RemoteException re) {
19190            }
19191            return;
19192        }
19193
19194        if (DEBUG_REMOVE) {
19195            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
19196                    + " deleteAllUsers: " + deleteAllUsers + " version="
19197                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
19198                    ? "VERSION_CODE_HIGHEST" : versionCode));
19199        }
19200        // Queue up an async operation since the package deletion may take a little while.
19201        mHandler.post(new Runnable() {
19202            public void run() {
19203                mHandler.removeCallbacks(this);
19204                int returnCode;
19205                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
19206                boolean doDeletePackage = true;
19207                if (ps != null) {
19208                    final boolean targetIsInstantApp =
19209                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19210                    doDeletePackage = !targetIsInstantApp
19211                            || canViewInstantApps;
19212                }
19213                if (doDeletePackage) {
19214                    if (!deleteAllUsers) {
19215                        returnCode = deletePackageX(internalPackageName, versionCode,
19216                                userId, deleteFlags);
19217                    } else {
19218                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
19219                                internalPackageName, users);
19220                        // If nobody is blocking uninstall, proceed with delete for all users
19221                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
19222                            returnCode = deletePackageX(internalPackageName, versionCode,
19223                                    userId, deleteFlags);
19224                        } else {
19225                            // Otherwise uninstall individually for users with blockUninstalls=false
19226                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
19227                            for (int userId : users) {
19228                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
19229                                    returnCode = deletePackageX(internalPackageName, versionCode,
19230                                            userId, userFlags);
19231                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
19232                                        Slog.w(TAG, "Package delete failed for user " + userId
19233                                                + ", returnCode " + returnCode);
19234                                    }
19235                                }
19236                            }
19237                            // The app has only been marked uninstalled for certain users.
19238                            // We still need to report that delete was blocked
19239                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
19240                        }
19241                    }
19242                } else {
19243                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19244                }
19245                try {
19246                    observer.onPackageDeleted(packageName, returnCode, null);
19247                } catch (RemoteException e) {
19248                    Log.i(TAG, "Observer no longer exists.");
19249                } //end catch
19250            } //end run
19251        });
19252    }
19253
19254    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
19255        if (pkg.staticSharedLibName != null) {
19256            return pkg.manifestPackageName;
19257        }
19258        return pkg.packageName;
19259    }
19260
19261    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
19262        // Handle renamed packages
19263        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
19264        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
19265
19266        // Is this a static library?
19267        SparseArray<SharedLibraryEntry> versionedLib =
19268                mStaticLibsByDeclaringPackage.get(packageName);
19269        if (versionedLib == null || versionedLib.size() <= 0) {
19270            return packageName;
19271        }
19272
19273        // Figure out which lib versions the caller can see
19274        SparseIntArray versionsCallerCanSee = null;
19275        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19276        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19277                && callingAppId != Process.ROOT_UID) {
19278            versionsCallerCanSee = new SparseIntArray();
19279            String libName = versionedLib.valueAt(0).info.getName();
19280            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19281            if (uidPackages != null) {
19282                for (String uidPackage : uidPackages) {
19283                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19284                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19285                    if (libIdx >= 0) {
19286                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19287                        versionsCallerCanSee.append(libVersion, libVersion);
19288                    }
19289                }
19290            }
19291        }
19292
19293        // Caller can see nothing - done
19294        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19295            return packageName;
19296        }
19297
19298        // Find the version the caller can see and the app version code
19299        SharedLibraryEntry highestVersion = null;
19300        final int versionCount = versionedLib.size();
19301        for (int i = 0; i < versionCount; i++) {
19302            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19303            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19304                    libEntry.info.getVersion()) < 0) {
19305                continue;
19306            }
19307            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19308            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19309                if (libVersionCode == versionCode) {
19310                    return libEntry.apk;
19311                }
19312            } else if (highestVersion == null) {
19313                highestVersion = libEntry;
19314            } else if (libVersionCode  > highestVersion.info
19315                    .getDeclaringPackage().getVersionCode()) {
19316                highestVersion = libEntry;
19317            }
19318        }
19319
19320        if (highestVersion != null) {
19321            return highestVersion.apk;
19322        }
19323
19324        return packageName;
19325    }
19326
19327    boolean isCallerVerifier(int callingUid) {
19328        final int callingUserId = UserHandle.getUserId(callingUid);
19329        return mRequiredVerifierPackage != null &&
19330                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19331    }
19332
19333    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19334        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19335              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19336            return true;
19337        }
19338        final int callingUserId = UserHandle.getUserId(callingUid);
19339        // If the caller installed the pkgName, then allow it to silently uninstall.
19340        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19341            return true;
19342        }
19343
19344        // Allow package verifier to silently uninstall.
19345        if (mRequiredVerifierPackage != null &&
19346                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19347            return true;
19348        }
19349
19350        // Allow package uninstaller to silently uninstall.
19351        if (mRequiredUninstallerPackage != null &&
19352                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19353            return true;
19354        }
19355
19356        // Allow storage manager to silently uninstall.
19357        if (mStorageManagerPackage != null &&
19358                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19359            return true;
19360        }
19361
19362        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19363        // uninstall for device owner provisioning.
19364        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19365                == PERMISSION_GRANTED) {
19366            return true;
19367        }
19368
19369        return false;
19370    }
19371
19372    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19373        int[] result = EMPTY_INT_ARRAY;
19374        for (int userId : userIds) {
19375            if (getBlockUninstallForUser(packageName, userId)) {
19376                result = ArrayUtils.appendInt(result, userId);
19377            }
19378        }
19379        return result;
19380    }
19381
19382    @Override
19383    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19384        final int callingUid = Binder.getCallingUid();
19385        if (getInstantAppPackageName(callingUid) != null
19386                && !isCallerSameApp(packageName, callingUid)) {
19387            return false;
19388        }
19389        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19390    }
19391
19392    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19393        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19394                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19395        try {
19396            if (dpm != null) {
19397                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19398                        /* callingUserOnly =*/ false);
19399                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19400                        : deviceOwnerComponentName.getPackageName();
19401                // Does the package contains the device owner?
19402                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19403                // this check is probably not needed, since DO should be registered as a device
19404                // admin on some user too. (Original bug for this: b/17657954)
19405                if (packageName.equals(deviceOwnerPackageName)) {
19406                    return true;
19407                }
19408                // Does it contain a device admin for any user?
19409                int[] users;
19410                if (userId == UserHandle.USER_ALL) {
19411                    users = sUserManager.getUserIds();
19412                } else {
19413                    users = new int[]{userId};
19414                }
19415                for (int i = 0; i < users.length; ++i) {
19416                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19417                        return true;
19418                    }
19419                }
19420            }
19421        } catch (RemoteException e) {
19422        }
19423        return false;
19424    }
19425
19426    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19427        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19428    }
19429
19430    /**
19431     *  This method is an internal method that could be get invoked either
19432     *  to delete an installed package or to clean up a failed installation.
19433     *  After deleting an installed package, a broadcast is sent to notify any
19434     *  listeners that the package has been removed. For cleaning up a failed
19435     *  installation, the broadcast is not necessary since the package's
19436     *  installation wouldn't have sent the initial broadcast either
19437     *  The key steps in deleting a package are
19438     *  deleting the package information in internal structures like mPackages,
19439     *  deleting the packages base directories through installd
19440     *  updating mSettings to reflect current status
19441     *  persisting settings for later use
19442     *  sending a broadcast if necessary
19443     */
19444    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19445        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19446        final boolean res;
19447
19448        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19449                ? UserHandle.USER_ALL : userId;
19450
19451        if (isPackageDeviceAdmin(packageName, removeUser)) {
19452            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19453            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19454        }
19455
19456        PackageSetting uninstalledPs = null;
19457        PackageParser.Package pkg = null;
19458
19459        // for the uninstall-updates case and restricted profiles, remember the per-
19460        // user handle installed state
19461        int[] allUsers;
19462        synchronized (mPackages) {
19463            uninstalledPs = mSettings.mPackages.get(packageName);
19464            if (uninstalledPs == null) {
19465                Slog.w(TAG, "Not removing non-existent package " + packageName);
19466                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19467            }
19468
19469            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19470                    && uninstalledPs.versionCode != versionCode) {
19471                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19472                        + uninstalledPs.versionCode + " != " + versionCode);
19473                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19474            }
19475
19476            // Static shared libs can be declared by any package, so let us not
19477            // allow removing a package if it provides a lib others depend on.
19478            pkg = mPackages.get(packageName);
19479
19480            allUsers = sUserManager.getUserIds();
19481
19482            if (pkg != null && pkg.staticSharedLibName != null) {
19483                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19484                        pkg.staticSharedLibVersion);
19485                if (libEntry != null) {
19486                    for (int currUserId : allUsers) {
19487                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19488                            continue;
19489                        }
19490                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19491                                libEntry.info, 0, currUserId);
19492                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19493                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19494                                    + " hosting lib " + libEntry.info.getName() + " version "
19495                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19496                                    + " for user " + currUserId);
19497                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19498                        }
19499                    }
19500                }
19501            }
19502
19503            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19504        }
19505
19506        final int freezeUser;
19507        if (isUpdatedSystemApp(uninstalledPs)
19508                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19509            // We're downgrading a system app, which will apply to all users, so
19510            // freeze them all during the downgrade
19511            freezeUser = UserHandle.USER_ALL;
19512        } else {
19513            freezeUser = removeUser;
19514        }
19515
19516        synchronized (mInstallLock) {
19517            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19518            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19519                    deleteFlags, "deletePackageX")) {
19520                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19521                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19522            }
19523            synchronized (mPackages) {
19524                if (res) {
19525                    if (pkg != null) {
19526                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19527                    }
19528                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19529                    updateInstantAppInstallerLocked(packageName);
19530                }
19531            }
19532        }
19533
19534        if (res) {
19535            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19536            info.sendPackageRemovedBroadcasts(killApp);
19537            info.sendSystemPackageUpdatedBroadcasts();
19538            info.sendSystemPackageAppearedBroadcasts();
19539        }
19540        // Force a gc here.
19541        Runtime.getRuntime().gc();
19542        // Delete the resources here after sending the broadcast to let
19543        // other processes clean up before deleting resources.
19544        if (info.args != null) {
19545            synchronized (mInstallLock) {
19546                info.args.doPostDeleteLI(true);
19547            }
19548        }
19549
19550        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19551    }
19552
19553    static class PackageRemovedInfo {
19554        final PackageSender packageSender;
19555        String removedPackage;
19556        String installerPackageName;
19557        int uid = -1;
19558        int removedAppId = -1;
19559        int[] origUsers;
19560        int[] removedUsers = null;
19561        int[] broadcastUsers = null;
19562        SparseArray<Integer> installReasons;
19563        boolean isRemovedPackageSystemUpdate = false;
19564        boolean isUpdate;
19565        boolean dataRemoved;
19566        boolean removedForAllUsers;
19567        boolean isStaticSharedLib;
19568        // Clean up resources deleted packages.
19569        InstallArgs args = null;
19570        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19571        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19572
19573        PackageRemovedInfo(PackageSender packageSender) {
19574            this.packageSender = packageSender;
19575        }
19576
19577        void sendPackageRemovedBroadcasts(boolean killApp) {
19578            sendPackageRemovedBroadcastInternal(killApp);
19579            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19580            for (int i = 0; i < childCount; i++) {
19581                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19582                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19583            }
19584        }
19585
19586        void sendSystemPackageUpdatedBroadcasts() {
19587            if (isRemovedPackageSystemUpdate) {
19588                sendSystemPackageUpdatedBroadcastsInternal();
19589                final int childCount = (removedChildPackages != null)
19590                        ? removedChildPackages.size() : 0;
19591                for (int i = 0; i < childCount; i++) {
19592                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19593                    if (childInfo.isRemovedPackageSystemUpdate) {
19594                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19595                    }
19596                }
19597            }
19598        }
19599
19600        void sendSystemPackageAppearedBroadcasts() {
19601            final int packageCount = (appearedChildPackages != null)
19602                    ? appearedChildPackages.size() : 0;
19603            for (int i = 0; i < packageCount; i++) {
19604                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19605                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19606                    true /*sendBootCompleted*/, false /*startReceiver*/,
19607                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19608            }
19609        }
19610
19611        private void sendSystemPackageUpdatedBroadcastsInternal() {
19612            Bundle extras = new Bundle(2);
19613            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19614            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19615            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19616                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19617            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19618                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19619            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19620                null, null, 0, removedPackage, null, null);
19621            if (installerPackageName != null) {
19622                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19623                        removedPackage, extras, 0 /*flags*/,
19624                        installerPackageName, null, null);
19625                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19626                        removedPackage, extras, 0 /*flags*/,
19627                        installerPackageName, null, null);
19628            }
19629        }
19630
19631        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19632            // Don't send static shared library removal broadcasts as these
19633            // libs are visible only the the apps that depend on them an one
19634            // cannot remove the library if it has a dependency.
19635            if (isStaticSharedLib) {
19636                return;
19637            }
19638            Bundle extras = new Bundle(2);
19639            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19640            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19641            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19642            if (isUpdate || isRemovedPackageSystemUpdate) {
19643                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19644            }
19645            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19646            if (removedPackage != null) {
19647                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19648                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19649                if (installerPackageName != null) {
19650                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19651                            removedPackage, extras, 0 /*flags*/,
19652                            installerPackageName, null, broadcastUsers);
19653                }
19654                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19655                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19656                        removedPackage, extras,
19657                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19658                        null, null, broadcastUsers);
19659                }
19660            }
19661            if (removedAppId >= 0) {
19662                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19663                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19664                    null, null, broadcastUsers);
19665            }
19666        }
19667
19668        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19669            removedUsers = userIds;
19670            if (removedUsers == null) {
19671                broadcastUsers = null;
19672                return;
19673            }
19674
19675            broadcastUsers = EMPTY_INT_ARRAY;
19676            for (int i = userIds.length - 1; i >= 0; --i) {
19677                final int userId = userIds[i];
19678                if (deletedPackageSetting.getInstantApp(userId)) {
19679                    continue;
19680                }
19681                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19682            }
19683        }
19684    }
19685
19686    /*
19687     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19688     * flag is not set, the data directory is removed as well.
19689     * make sure this flag is set for partially installed apps. If not its meaningless to
19690     * delete a partially installed application.
19691     */
19692    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19693            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19694        String packageName = ps.name;
19695        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19696        // Retrieve object to delete permissions for shared user later on
19697        final PackageParser.Package deletedPkg;
19698        final PackageSetting deletedPs;
19699        // reader
19700        synchronized (mPackages) {
19701            deletedPkg = mPackages.get(packageName);
19702            deletedPs = mSettings.mPackages.get(packageName);
19703            if (outInfo != null) {
19704                outInfo.removedPackage = packageName;
19705                outInfo.installerPackageName = ps.installerPackageName;
19706                outInfo.isStaticSharedLib = deletedPkg != null
19707                        && deletedPkg.staticSharedLibName != null;
19708                outInfo.populateUsers(deletedPs == null ? null
19709                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19710            }
19711        }
19712
19713        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19714
19715        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19716            final PackageParser.Package resolvedPkg;
19717            if (deletedPkg != null) {
19718                resolvedPkg = deletedPkg;
19719            } else {
19720                // We don't have a parsed package when it lives on an ejected
19721                // adopted storage device, so fake something together
19722                resolvedPkg = new PackageParser.Package(ps.name);
19723                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19724            }
19725            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19726                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19727            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19728            if (outInfo != null) {
19729                outInfo.dataRemoved = true;
19730            }
19731            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19732        }
19733
19734        int removedAppId = -1;
19735
19736        // writer
19737        synchronized (mPackages) {
19738            boolean installedStateChanged = false;
19739            if (deletedPs != null) {
19740                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19741                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19742                    clearDefaultBrowserIfNeeded(packageName);
19743                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19744                    removedAppId = mSettings.removePackageLPw(packageName);
19745                    if (outInfo != null) {
19746                        outInfo.removedAppId = removedAppId;
19747                    }
19748                    updatePermissionsLPw(deletedPs.name, null, 0);
19749                    if (deletedPs.sharedUser != null) {
19750                        // Remove permissions associated with package. Since runtime
19751                        // permissions are per user we have to kill the removed package
19752                        // or packages running under the shared user of the removed
19753                        // package if revoking the permissions requested only by the removed
19754                        // package is successful and this causes a change in gids.
19755                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19756                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19757                                    userId);
19758                            if (userIdToKill == UserHandle.USER_ALL
19759                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19760                                // If gids changed for this user, kill all affected packages.
19761                                mHandler.post(new Runnable() {
19762                                    @Override
19763                                    public void run() {
19764                                        // This has to happen with no lock held.
19765                                        killApplication(deletedPs.name, deletedPs.appId,
19766                                                KILL_APP_REASON_GIDS_CHANGED);
19767                                    }
19768                                });
19769                                break;
19770                            }
19771                        }
19772                    }
19773                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19774                }
19775                // make sure to preserve per-user disabled state if this removal was just
19776                // a downgrade of a system app to the factory package
19777                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19778                    if (DEBUG_REMOVE) {
19779                        Slog.d(TAG, "Propagating install state across downgrade");
19780                    }
19781                    for (int userId : allUserHandles) {
19782                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19783                        if (DEBUG_REMOVE) {
19784                            Slog.d(TAG, "    user " + userId + " => " + installed);
19785                        }
19786                        if (installed != ps.getInstalled(userId)) {
19787                            installedStateChanged = true;
19788                        }
19789                        ps.setInstalled(installed, userId);
19790                    }
19791                }
19792            }
19793            // can downgrade to reader
19794            if (writeSettings) {
19795                // Save settings now
19796                mSettings.writeLPr();
19797            }
19798            if (installedStateChanged) {
19799                mSettings.writeKernelMappingLPr(ps);
19800            }
19801        }
19802        if (removedAppId != -1) {
19803            // A user ID was deleted here. Go through all users and remove it
19804            // from KeyStore.
19805            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19806        }
19807    }
19808
19809    static boolean locationIsPrivileged(File path) {
19810        try {
19811            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19812                    .getCanonicalPath();
19813            return path.getCanonicalPath().startsWith(privilegedAppDir);
19814        } catch (IOException e) {
19815            Slog.e(TAG, "Unable to access code path " + path);
19816        }
19817        return false;
19818    }
19819
19820    /*
19821     * Tries to delete system package.
19822     */
19823    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19824            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19825            boolean writeSettings) {
19826        if (deletedPs.parentPackageName != null) {
19827            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19828            return false;
19829        }
19830
19831        final boolean applyUserRestrictions
19832                = (allUserHandles != null) && (outInfo.origUsers != null);
19833        final PackageSetting disabledPs;
19834        // Confirm if the system package has been updated
19835        // An updated system app can be deleted. This will also have to restore
19836        // the system pkg from system partition
19837        // reader
19838        synchronized (mPackages) {
19839            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19840        }
19841
19842        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19843                + " disabledPs=" + disabledPs);
19844
19845        if (disabledPs == null) {
19846            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19847            return false;
19848        } else if (DEBUG_REMOVE) {
19849            Slog.d(TAG, "Deleting system pkg from data partition");
19850        }
19851
19852        if (DEBUG_REMOVE) {
19853            if (applyUserRestrictions) {
19854                Slog.d(TAG, "Remembering install states:");
19855                for (int userId : allUserHandles) {
19856                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19857                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19858                }
19859            }
19860        }
19861
19862        // Delete the updated package
19863        outInfo.isRemovedPackageSystemUpdate = true;
19864        if (outInfo.removedChildPackages != null) {
19865            final int childCount = (deletedPs.childPackageNames != null)
19866                    ? deletedPs.childPackageNames.size() : 0;
19867            for (int i = 0; i < childCount; i++) {
19868                String childPackageName = deletedPs.childPackageNames.get(i);
19869                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19870                        .contains(childPackageName)) {
19871                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19872                            childPackageName);
19873                    if (childInfo != null) {
19874                        childInfo.isRemovedPackageSystemUpdate = true;
19875                    }
19876                }
19877            }
19878        }
19879
19880        if (disabledPs.versionCode < deletedPs.versionCode) {
19881            // Delete data for downgrades
19882            flags &= ~PackageManager.DELETE_KEEP_DATA;
19883        } else {
19884            // Preserve data by setting flag
19885            flags |= PackageManager.DELETE_KEEP_DATA;
19886        }
19887
19888        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19889                outInfo, writeSettings, disabledPs.pkg);
19890        if (!ret) {
19891            return false;
19892        }
19893
19894        // writer
19895        synchronized (mPackages) {
19896            // NOTE: The system package always needs to be enabled; even if it's for
19897            // a compressed stub. If we don't, installing the system package fails
19898            // during scan [scanning checks the disabled packages]. We will reverse
19899            // this later, after we've "installed" the stub.
19900            // Reinstate the old system package
19901            enableSystemPackageLPw(disabledPs.pkg);
19902            // Remove any native libraries from the upgraded package.
19903            removeNativeBinariesLI(deletedPs);
19904        }
19905
19906        // Install the system package
19907        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19908        try {
19909            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
19910                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
19911        } catch (PackageManagerException e) {
19912            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19913                    + e.getMessage());
19914            return false;
19915        } finally {
19916            if (disabledPs.pkg.isStub) {
19917                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
19918            }
19919        }
19920        return true;
19921    }
19922
19923    /**
19924     * Installs a package that's already on the system partition.
19925     */
19926    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
19927            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
19928            @Nullable PermissionsState origPermissionState, boolean writeSettings)
19929                    throws PackageManagerException {
19930        int parseFlags = mDefParseFlags
19931                | PackageParser.PARSE_MUST_BE_APK
19932                | PackageParser.PARSE_IS_SYSTEM
19933                | PackageParser.PARSE_IS_SYSTEM_DIR;
19934        if (isPrivileged || locationIsPrivileged(codePath)) {
19935            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19936        }
19937
19938        final PackageParser.Package newPkg =
19939                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
19940
19941        try {
19942            // update shared libraries for the newly re-installed system package
19943            updateSharedLibrariesLPr(newPkg, null);
19944        } catch (PackageManagerException e) {
19945            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19946        }
19947
19948        prepareAppDataAfterInstallLIF(newPkg);
19949
19950        // writer
19951        synchronized (mPackages) {
19952            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19953
19954            // Propagate the permissions state as we do not want to drop on the floor
19955            // runtime permissions. The update permissions method below will take
19956            // care of removing obsolete permissions and grant install permissions.
19957            if (origPermissionState != null) {
19958                ps.getPermissionsState().copyFrom(origPermissionState);
19959            }
19960            updatePermissionsLPw(newPkg.packageName, newPkg,
19961                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19962
19963            final boolean applyUserRestrictions
19964                    = (allUserHandles != null) && (origUserHandles != null);
19965            if (applyUserRestrictions) {
19966                boolean installedStateChanged = false;
19967                if (DEBUG_REMOVE) {
19968                    Slog.d(TAG, "Propagating install state across reinstall");
19969                }
19970                for (int userId : allUserHandles) {
19971                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
19972                    if (DEBUG_REMOVE) {
19973                        Slog.d(TAG, "    user " + userId + " => " + installed);
19974                    }
19975                    if (installed != ps.getInstalled(userId)) {
19976                        installedStateChanged = true;
19977                    }
19978                    ps.setInstalled(installed, userId);
19979
19980                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19981                }
19982                // Regardless of writeSettings we need to ensure that this restriction
19983                // state propagation is persisted
19984                mSettings.writeAllUsersPackageRestrictionsLPr();
19985                if (installedStateChanged) {
19986                    mSettings.writeKernelMappingLPr(ps);
19987                }
19988            }
19989            // can downgrade to reader here
19990            if (writeSettings) {
19991                mSettings.writeLPr();
19992            }
19993        }
19994        return newPkg;
19995    }
19996
19997    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19998            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19999            PackageRemovedInfo outInfo, boolean writeSettings,
20000            PackageParser.Package replacingPackage) {
20001        synchronized (mPackages) {
20002            if (outInfo != null) {
20003                outInfo.uid = ps.appId;
20004            }
20005
20006            if (outInfo != null && outInfo.removedChildPackages != null) {
20007                final int childCount = (ps.childPackageNames != null)
20008                        ? ps.childPackageNames.size() : 0;
20009                for (int i = 0; i < childCount; i++) {
20010                    String childPackageName = ps.childPackageNames.get(i);
20011                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
20012                    if (childPs == null) {
20013                        return false;
20014                    }
20015                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
20016                            childPackageName);
20017                    if (childInfo != null) {
20018                        childInfo.uid = childPs.appId;
20019                    }
20020                }
20021            }
20022        }
20023
20024        // Delete package data from internal structures and also remove data if flag is set
20025        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
20026
20027        // Delete the child packages data
20028        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
20029        for (int i = 0; i < childCount; i++) {
20030            PackageSetting childPs;
20031            synchronized (mPackages) {
20032                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
20033            }
20034            if (childPs != null) {
20035                PackageRemovedInfo childOutInfo = (outInfo != null
20036                        && outInfo.removedChildPackages != null)
20037                        ? outInfo.removedChildPackages.get(childPs.name) : null;
20038                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
20039                        && (replacingPackage != null
20040                        && !replacingPackage.hasChildPackage(childPs.name))
20041                        ? flags & ~DELETE_KEEP_DATA : flags;
20042                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
20043                        deleteFlags, writeSettings);
20044            }
20045        }
20046
20047        // Delete application code and resources only for parent packages
20048        if (ps.parentPackageName == null) {
20049            if (deleteCodeAndResources && (outInfo != null)) {
20050                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
20051                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
20052                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
20053            }
20054        }
20055
20056        return true;
20057    }
20058
20059    @Override
20060    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
20061            int userId) {
20062        mContext.enforceCallingOrSelfPermission(
20063                android.Manifest.permission.DELETE_PACKAGES, null);
20064        synchronized (mPackages) {
20065            // Cannot block uninstall of static shared libs as they are
20066            // considered a part of the using app (emulating static linking).
20067            // Also static libs are installed always on internal storage.
20068            PackageParser.Package pkg = mPackages.get(packageName);
20069            if (pkg != null && pkg.staticSharedLibName != null) {
20070                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
20071                        + " providing static shared library: " + pkg.staticSharedLibName);
20072                return false;
20073            }
20074            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
20075            mSettings.writePackageRestrictionsLPr(userId);
20076        }
20077        return true;
20078    }
20079
20080    @Override
20081    public boolean getBlockUninstallForUser(String packageName, int userId) {
20082        synchronized (mPackages) {
20083            final PackageSetting ps = mSettings.mPackages.get(packageName);
20084            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
20085                return false;
20086            }
20087            return mSettings.getBlockUninstallLPr(userId, packageName);
20088        }
20089    }
20090
20091    @Override
20092    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
20093        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
20094        synchronized (mPackages) {
20095            PackageSetting ps = mSettings.mPackages.get(packageName);
20096            if (ps == null) {
20097                Log.w(TAG, "Package doesn't exist: " + packageName);
20098                return false;
20099            }
20100            if (systemUserApp) {
20101                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20102            } else {
20103                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20104            }
20105            mSettings.writeLPr();
20106        }
20107        return true;
20108    }
20109
20110    /*
20111     * This method handles package deletion in general
20112     */
20113    private boolean deletePackageLIF(String packageName, UserHandle user,
20114            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
20115            PackageRemovedInfo outInfo, boolean writeSettings,
20116            PackageParser.Package replacingPackage) {
20117        if (packageName == null) {
20118            Slog.w(TAG, "Attempt to delete null packageName.");
20119            return false;
20120        }
20121
20122        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
20123
20124        PackageSetting ps;
20125        synchronized (mPackages) {
20126            ps = mSettings.mPackages.get(packageName);
20127            if (ps == null) {
20128                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20129                return false;
20130            }
20131
20132            if (ps.parentPackageName != null && (!isSystemApp(ps)
20133                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
20134                if (DEBUG_REMOVE) {
20135                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
20136                            + ((user == null) ? UserHandle.USER_ALL : user));
20137                }
20138                final int removedUserId = (user != null) ? user.getIdentifier()
20139                        : UserHandle.USER_ALL;
20140                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
20141                    return false;
20142                }
20143                markPackageUninstalledForUserLPw(ps, user);
20144                scheduleWritePackageRestrictionsLocked(user);
20145                return true;
20146            }
20147        }
20148
20149        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
20150                && user.getIdentifier() != UserHandle.USER_ALL)) {
20151            // The caller is asking that the package only be deleted for a single
20152            // user.  To do this, we just mark its uninstalled state and delete
20153            // its data. If this is a system app, we only allow this to happen if
20154            // they have set the special DELETE_SYSTEM_APP which requests different
20155            // semantics than normal for uninstalling system apps.
20156            markPackageUninstalledForUserLPw(ps, user);
20157
20158            if (!isSystemApp(ps)) {
20159                // Do not uninstall the APK if an app should be cached
20160                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
20161                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
20162                    // Other user still have this package installed, so all
20163                    // we need to do is clear this user's data and save that
20164                    // it is uninstalled.
20165                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
20166                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20167                        return false;
20168                    }
20169                    scheduleWritePackageRestrictionsLocked(user);
20170                    return true;
20171                } else {
20172                    // We need to set it back to 'installed' so the uninstall
20173                    // broadcasts will be sent correctly.
20174                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
20175                    ps.setInstalled(true, user.getIdentifier());
20176                    mSettings.writeKernelMappingLPr(ps);
20177                }
20178            } else {
20179                // This is a system app, so we assume that the
20180                // other users still have this package installed, so all
20181                // we need to do is clear this user's data and save that
20182                // it is uninstalled.
20183                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
20184                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20185                    return false;
20186                }
20187                scheduleWritePackageRestrictionsLocked(user);
20188                return true;
20189            }
20190        }
20191
20192        // If we are deleting a composite package for all users, keep track
20193        // of result for each child.
20194        if (ps.childPackageNames != null && outInfo != null) {
20195            synchronized (mPackages) {
20196                final int childCount = ps.childPackageNames.size();
20197                outInfo.removedChildPackages = new ArrayMap<>(childCount);
20198                for (int i = 0; i < childCount; i++) {
20199                    String childPackageName = ps.childPackageNames.get(i);
20200                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
20201                    childInfo.removedPackage = childPackageName;
20202                    childInfo.installerPackageName = ps.installerPackageName;
20203                    outInfo.removedChildPackages.put(childPackageName, childInfo);
20204                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20205                    if (childPs != null) {
20206                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
20207                    }
20208                }
20209            }
20210        }
20211
20212        boolean ret = false;
20213        if (isSystemApp(ps)) {
20214            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
20215            // When an updated system application is deleted we delete the existing resources
20216            // as well and fall back to existing code in system partition
20217            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
20218        } else {
20219            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
20220            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
20221                    outInfo, writeSettings, replacingPackage);
20222        }
20223
20224        // Take a note whether we deleted the package for all users
20225        if (outInfo != null) {
20226            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
20227            if (outInfo.removedChildPackages != null) {
20228                synchronized (mPackages) {
20229                    final int childCount = outInfo.removedChildPackages.size();
20230                    for (int i = 0; i < childCount; i++) {
20231                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
20232                        if (childInfo != null) {
20233                            childInfo.removedForAllUsers = mPackages.get(
20234                                    childInfo.removedPackage) == null;
20235                        }
20236                    }
20237                }
20238            }
20239            // If we uninstalled an update to a system app there may be some
20240            // child packages that appeared as they are declared in the system
20241            // app but were not declared in the update.
20242            if (isSystemApp(ps)) {
20243                synchronized (mPackages) {
20244                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
20245                    final int childCount = (updatedPs.childPackageNames != null)
20246                            ? updatedPs.childPackageNames.size() : 0;
20247                    for (int i = 0; i < childCount; i++) {
20248                        String childPackageName = updatedPs.childPackageNames.get(i);
20249                        if (outInfo.removedChildPackages == null
20250                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
20251                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20252                            if (childPs == null) {
20253                                continue;
20254                            }
20255                            PackageInstalledInfo installRes = new PackageInstalledInfo();
20256                            installRes.name = childPackageName;
20257                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
20258                            installRes.pkg = mPackages.get(childPackageName);
20259                            installRes.uid = childPs.pkg.applicationInfo.uid;
20260                            if (outInfo.appearedChildPackages == null) {
20261                                outInfo.appearedChildPackages = new ArrayMap<>();
20262                            }
20263                            outInfo.appearedChildPackages.put(childPackageName, installRes);
20264                        }
20265                    }
20266                }
20267            }
20268        }
20269
20270        return ret;
20271    }
20272
20273    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
20274        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
20275                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
20276        for (int nextUserId : userIds) {
20277            if (DEBUG_REMOVE) {
20278                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
20279            }
20280            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
20281                    false /*installed*/,
20282                    true /*stopped*/,
20283                    true /*notLaunched*/,
20284                    false /*hidden*/,
20285                    false /*suspended*/,
20286                    false /*instantApp*/,
20287                    false /*virtualPreload*/,
20288                    null /*lastDisableAppCaller*/,
20289                    null /*enabledComponents*/,
20290                    null /*disabledComponents*/,
20291                    ps.readUserState(nextUserId).domainVerificationStatus,
20292                    0, PackageManager.INSTALL_REASON_UNKNOWN);
20293        }
20294        mSettings.writeKernelMappingLPr(ps);
20295    }
20296
20297    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
20298            PackageRemovedInfo outInfo) {
20299        final PackageParser.Package pkg;
20300        synchronized (mPackages) {
20301            pkg = mPackages.get(ps.name);
20302        }
20303
20304        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20305                : new int[] {userId};
20306        for (int nextUserId : userIds) {
20307            if (DEBUG_REMOVE) {
20308                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20309                        + nextUserId);
20310            }
20311
20312            destroyAppDataLIF(pkg, userId,
20313                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20314            destroyAppProfilesLIF(pkg, userId);
20315            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20316            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20317            schedulePackageCleaning(ps.name, nextUserId, false);
20318            synchronized (mPackages) {
20319                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20320                    scheduleWritePackageRestrictionsLocked(nextUserId);
20321                }
20322                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20323            }
20324        }
20325
20326        if (outInfo != null) {
20327            outInfo.removedPackage = ps.name;
20328            outInfo.installerPackageName = ps.installerPackageName;
20329            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20330            outInfo.removedAppId = ps.appId;
20331            outInfo.removedUsers = userIds;
20332            outInfo.broadcastUsers = userIds;
20333        }
20334
20335        return true;
20336    }
20337
20338    private final class ClearStorageConnection implements ServiceConnection {
20339        IMediaContainerService mContainerService;
20340
20341        @Override
20342        public void onServiceConnected(ComponentName name, IBinder service) {
20343            synchronized (this) {
20344                mContainerService = IMediaContainerService.Stub
20345                        .asInterface(Binder.allowBlocking(service));
20346                notifyAll();
20347            }
20348        }
20349
20350        @Override
20351        public void onServiceDisconnected(ComponentName name) {
20352        }
20353    }
20354
20355    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20356        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20357
20358        final boolean mounted;
20359        if (Environment.isExternalStorageEmulated()) {
20360            mounted = true;
20361        } else {
20362            final String status = Environment.getExternalStorageState();
20363
20364            mounted = status.equals(Environment.MEDIA_MOUNTED)
20365                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20366        }
20367
20368        if (!mounted) {
20369            return;
20370        }
20371
20372        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20373        int[] users;
20374        if (userId == UserHandle.USER_ALL) {
20375            users = sUserManager.getUserIds();
20376        } else {
20377            users = new int[] { userId };
20378        }
20379        final ClearStorageConnection conn = new ClearStorageConnection();
20380        if (mContext.bindServiceAsUser(
20381                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20382            try {
20383                for (int curUser : users) {
20384                    long timeout = SystemClock.uptimeMillis() + 5000;
20385                    synchronized (conn) {
20386                        long now;
20387                        while (conn.mContainerService == null &&
20388                                (now = SystemClock.uptimeMillis()) < timeout) {
20389                            try {
20390                                conn.wait(timeout - now);
20391                            } catch (InterruptedException e) {
20392                            }
20393                        }
20394                    }
20395                    if (conn.mContainerService == null) {
20396                        return;
20397                    }
20398
20399                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20400                    clearDirectory(conn.mContainerService,
20401                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20402                    if (allData) {
20403                        clearDirectory(conn.mContainerService,
20404                                userEnv.buildExternalStorageAppDataDirs(packageName));
20405                        clearDirectory(conn.mContainerService,
20406                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20407                    }
20408                }
20409            } finally {
20410                mContext.unbindService(conn);
20411            }
20412        }
20413    }
20414
20415    @Override
20416    public void clearApplicationProfileData(String packageName) {
20417        enforceSystemOrRoot("Only the system can clear all profile data");
20418
20419        final PackageParser.Package pkg;
20420        synchronized (mPackages) {
20421            pkg = mPackages.get(packageName);
20422        }
20423
20424        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20425            synchronized (mInstallLock) {
20426                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20427            }
20428        }
20429    }
20430
20431    @Override
20432    public void clearApplicationUserData(final String packageName,
20433            final IPackageDataObserver observer, final int userId) {
20434        mContext.enforceCallingOrSelfPermission(
20435                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20436
20437        final int callingUid = Binder.getCallingUid();
20438        enforceCrossUserPermission(callingUid, userId,
20439                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20440
20441        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20442        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
20443        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20444            throw new SecurityException("Cannot clear data for a protected package: "
20445                    + packageName);
20446        }
20447        // Queue up an async operation since the package deletion may take a little while.
20448        mHandler.post(new Runnable() {
20449            public void run() {
20450                mHandler.removeCallbacks(this);
20451                final boolean succeeded;
20452                if (!filterApp) {
20453                    try (PackageFreezer freezer = freezePackage(packageName,
20454                            "clearApplicationUserData")) {
20455                        synchronized (mInstallLock) {
20456                            succeeded = clearApplicationUserDataLIF(packageName, userId);
20457                        }
20458                        clearExternalStorageDataSync(packageName, userId, true);
20459                        synchronized (mPackages) {
20460                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20461                                    packageName, userId);
20462                        }
20463                    }
20464                    if (succeeded) {
20465                        // invoke DeviceStorageMonitor's update method to clear any notifications
20466                        DeviceStorageMonitorInternal dsm = LocalServices
20467                                .getService(DeviceStorageMonitorInternal.class);
20468                        if (dsm != null) {
20469                            dsm.checkMemory();
20470                        }
20471                    }
20472                } else {
20473                    succeeded = false;
20474                }
20475                if (observer != null) {
20476                    try {
20477                        observer.onRemoveCompleted(packageName, succeeded);
20478                    } catch (RemoteException e) {
20479                        Log.i(TAG, "Observer no longer exists.");
20480                    }
20481                } //end if observer
20482            } //end run
20483        });
20484    }
20485
20486    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20487        if (packageName == null) {
20488            Slog.w(TAG, "Attempt to delete null packageName.");
20489            return false;
20490        }
20491
20492        // Try finding details about the requested package
20493        PackageParser.Package pkg;
20494        synchronized (mPackages) {
20495            pkg = mPackages.get(packageName);
20496            if (pkg == null) {
20497                final PackageSetting ps = mSettings.mPackages.get(packageName);
20498                if (ps != null) {
20499                    pkg = ps.pkg;
20500                }
20501            }
20502
20503            if (pkg == null) {
20504                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20505                return false;
20506            }
20507
20508            PackageSetting ps = (PackageSetting) pkg.mExtras;
20509            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20510        }
20511
20512        clearAppDataLIF(pkg, userId,
20513                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20514
20515        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20516        removeKeystoreDataIfNeeded(userId, appId);
20517
20518        UserManagerInternal umInternal = getUserManagerInternal();
20519        final int flags;
20520        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20521            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20522        } else if (umInternal.isUserRunning(userId)) {
20523            flags = StorageManager.FLAG_STORAGE_DE;
20524        } else {
20525            flags = 0;
20526        }
20527        prepareAppDataContentsLIF(pkg, userId, flags);
20528
20529        return true;
20530    }
20531
20532    /**
20533     * Reverts user permission state changes (permissions and flags) in
20534     * all packages for a given user.
20535     *
20536     * @param userId The device user for which to do a reset.
20537     */
20538    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20539        final int packageCount = mPackages.size();
20540        for (int i = 0; i < packageCount; i++) {
20541            PackageParser.Package pkg = mPackages.valueAt(i);
20542            PackageSetting ps = (PackageSetting) pkg.mExtras;
20543            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20544        }
20545    }
20546
20547    private void resetNetworkPolicies(int userId) {
20548        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20549    }
20550
20551    /**
20552     * Reverts user permission state changes (permissions and flags).
20553     *
20554     * @param ps The package for which to reset.
20555     * @param userId The device user for which to do a reset.
20556     */
20557    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20558            final PackageSetting ps, final int userId) {
20559        if (ps.pkg == null) {
20560            return;
20561        }
20562
20563        // These are flags that can change base on user actions.
20564        final int userSettableMask = FLAG_PERMISSION_USER_SET
20565                | FLAG_PERMISSION_USER_FIXED
20566                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20567                | FLAG_PERMISSION_REVIEW_REQUIRED;
20568
20569        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20570                | FLAG_PERMISSION_POLICY_FIXED;
20571
20572        boolean writeInstallPermissions = false;
20573        boolean writeRuntimePermissions = false;
20574
20575        final int permissionCount = ps.pkg.requestedPermissions.size();
20576        for (int i = 0; i < permissionCount; i++) {
20577            String permission = ps.pkg.requestedPermissions.get(i);
20578
20579            BasePermission bp = mSettings.mPermissions.get(permission);
20580            if (bp == null) {
20581                continue;
20582            }
20583
20584            // If shared user we just reset the state to which only this app contributed.
20585            if (ps.sharedUser != null) {
20586                boolean used = false;
20587                final int packageCount = ps.sharedUser.packages.size();
20588                for (int j = 0; j < packageCount; j++) {
20589                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20590                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20591                            && pkg.pkg.requestedPermissions.contains(permission)) {
20592                        used = true;
20593                        break;
20594                    }
20595                }
20596                if (used) {
20597                    continue;
20598                }
20599            }
20600
20601            PermissionsState permissionsState = ps.getPermissionsState();
20602
20603            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20604
20605            // Always clear the user settable flags.
20606            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20607                    bp.name) != null;
20608            // If permission review is enabled and this is a legacy app, mark the
20609            // permission as requiring a review as this is the initial state.
20610            int flags = 0;
20611            if (mPermissionReviewRequired
20612                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20613                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20614            }
20615            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20616                if (hasInstallState) {
20617                    writeInstallPermissions = true;
20618                } else {
20619                    writeRuntimePermissions = true;
20620                }
20621            }
20622
20623            // Below is only runtime permission handling.
20624            if (!bp.isRuntime()) {
20625                continue;
20626            }
20627
20628            // Never clobber system or policy.
20629            if ((oldFlags & policyOrSystemFlags) != 0) {
20630                continue;
20631            }
20632
20633            // If this permission was granted by default, make sure it is.
20634            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20635                if (permissionsState.grantRuntimePermission(bp, userId)
20636                        != PERMISSION_OPERATION_FAILURE) {
20637                    writeRuntimePermissions = true;
20638                }
20639            // If permission review is enabled the permissions for a legacy apps
20640            // are represented as constantly granted runtime ones, so don't revoke.
20641            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20642                // Otherwise, reset the permission.
20643                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20644                switch (revokeResult) {
20645                    case PERMISSION_OPERATION_SUCCESS:
20646                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20647                        writeRuntimePermissions = true;
20648                        final int appId = ps.appId;
20649                        mHandler.post(new Runnable() {
20650                            @Override
20651                            public void run() {
20652                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20653                            }
20654                        });
20655                    } break;
20656                }
20657            }
20658        }
20659
20660        // Synchronously write as we are taking permissions away.
20661        if (writeRuntimePermissions) {
20662            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20663        }
20664
20665        // Synchronously write as we are taking permissions away.
20666        if (writeInstallPermissions) {
20667            mSettings.writeLPr();
20668        }
20669    }
20670
20671    /**
20672     * Remove entries from the keystore daemon. Will only remove it if the
20673     * {@code appId} is valid.
20674     */
20675    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20676        if (appId < 0) {
20677            return;
20678        }
20679
20680        final KeyStore keyStore = KeyStore.getInstance();
20681        if (keyStore != null) {
20682            if (userId == UserHandle.USER_ALL) {
20683                for (final int individual : sUserManager.getUserIds()) {
20684                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20685                }
20686            } else {
20687                keyStore.clearUid(UserHandle.getUid(userId, appId));
20688            }
20689        } else {
20690            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20691        }
20692    }
20693
20694    @Override
20695    public void deleteApplicationCacheFiles(final String packageName,
20696            final IPackageDataObserver observer) {
20697        final int userId = UserHandle.getCallingUserId();
20698        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20699    }
20700
20701    @Override
20702    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20703            final IPackageDataObserver observer) {
20704        final int callingUid = Binder.getCallingUid();
20705        mContext.enforceCallingOrSelfPermission(
20706                android.Manifest.permission.DELETE_CACHE_FILES, null);
20707        enforceCrossUserPermission(callingUid, userId,
20708                /* requireFullPermission= */ true, /* checkShell= */ false,
20709                "delete application cache files");
20710        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20711                android.Manifest.permission.ACCESS_INSTANT_APPS);
20712
20713        final PackageParser.Package pkg;
20714        synchronized (mPackages) {
20715            pkg = mPackages.get(packageName);
20716        }
20717
20718        // Queue up an async operation since the package deletion may take a little while.
20719        mHandler.post(new Runnable() {
20720            public void run() {
20721                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20722                boolean doClearData = true;
20723                if (ps != null) {
20724                    final boolean targetIsInstantApp =
20725                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20726                    doClearData = !targetIsInstantApp
20727                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20728                }
20729                if (doClearData) {
20730                    synchronized (mInstallLock) {
20731                        final int flags = StorageManager.FLAG_STORAGE_DE
20732                                | StorageManager.FLAG_STORAGE_CE;
20733                        // We're only clearing cache files, so we don't care if the
20734                        // app is unfrozen and still able to run
20735                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20736                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20737                    }
20738                    clearExternalStorageDataSync(packageName, userId, false);
20739                }
20740                if (observer != null) {
20741                    try {
20742                        observer.onRemoveCompleted(packageName, true);
20743                    } catch (RemoteException e) {
20744                        Log.i(TAG, "Observer no longer exists.");
20745                    }
20746                }
20747            }
20748        });
20749    }
20750
20751    @Override
20752    public void getPackageSizeInfo(final String packageName, int userHandle,
20753            final IPackageStatsObserver observer) {
20754        throw new UnsupportedOperationException(
20755                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20756    }
20757
20758    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20759        final PackageSetting ps;
20760        synchronized (mPackages) {
20761            ps = mSettings.mPackages.get(packageName);
20762            if (ps == null) {
20763                Slog.w(TAG, "Failed to find settings for " + packageName);
20764                return false;
20765            }
20766        }
20767
20768        final String[] packageNames = { packageName };
20769        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20770        final String[] codePaths = { ps.codePathString };
20771
20772        try {
20773            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20774                    ps.appId, ceDataInodes, codePaths, stats);
20775
20776            // For now, ignore code size of packages on system partition
20777            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20778                stats.codeSize = 0;
20779            }
20780
20781            // External clients expect these to be tracked separately
20782            stats.dataSize -= stats.cacheSize;
20783
20784        } catch (InstallerException e) {
20785            Slog.w(TAG, String.valueOf(e));
20786            return false;
20787        }
20788
20789        return true;
20790    }
20791
20792    private int getUidTargetSdkVersionLockedLPr(int uid) {
20793        Object obj = mSettings.getUserIdLPr(uid);
20794        if (obj instanceof SharedUserSetting) {
20795            final SharedUserSetting sus = (SharedUserSetting) obj;
20796            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20797            final Iterator<PackageSetting> it = sus.packages.iterator();
20798            while (it.hasNext()) {
20799                final PackageSetting ps = it.next();
20800                if (ps.pkg != null) {
20801                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20802                    if (v < vers) vers = v;
20803                }
20804            }
20805            return vers;
20806        } else if (obj instanceof PackageSetting) {
20807            final PackageSetting ps = (PackageSetting) obj;
20808            if (ps.pkg != null) {
20809                return ps.pkg.applicationInfo.targetSdkVersion;
20810            }
20811        }
20812        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20813    }
20814
20815    @Override
20816    public void addPreferredActivity(IntentFilter filter, int match,
20817            ComponentName[] set, ComponentName activity, int userId) {
20818        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20819                "Adding preferred");
20820    }
20821
20822    private void addPreferredActivityInternal(IntentFilter filter, int match,
20823            ComponentName[] set, ComponentName activity, boolean always, int userId,
20824            String opname) {
20825        // writer
20826        int callingUid = Binder.getCallingUid();
20827        enforceCrossUserPermission(callingUid, userId,
20828                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20829        if (filter.countActions() == 0) {
20830            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20831            return;
20832        }
20833        synchronized (mPackages) {
20834            if (mContext.checkCallingOrSelfPermission(
20835                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20836                    != PackageManager.PERMISSION_GRANTED) {
20837                if (getUidTargetSdkVersionLockedLPr(callingUid)
20838                        < Build.VERSION_CODES.FROYO) {
20839                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20840                            + callingUid);
20841                    return;
20842                }
20843                mContext.enforceCallingOrSelfPermission(
20844                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20845            }
20846
20847            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20848            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20849                    + userId + ":");
20850            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20851            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20852            scheduleWritePackageRestrictionsLocked(userId);
20853            postPreferredActivityChangedBroadcast(userId);
20854        }
20855    }
20856
20857    private void postPreferredActivityChangedBroadcast(int userId) {
20858        mHandler.post(() -> {
20859            final IActivityManager am = ActivityManager.getService();
20860            if (am == null) {
20861                return;
20862            }
20863
20864            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20865            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20866            try {
20867                am.broadcastIntent(null, intent, null, null,
20868                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20869                        null, false, false, userId);
20870            } catch (RemoteException e) {
20871            }
20872        });
20873    }
20874
20875    @Override
20876    public void replacePreferredActivity(IntentFilter filter, int match,
20877            ComponentName[] set, ComponentName activity, int userId) {
20878        if (filter.countActions() != 1) {
20879            throw new IllegalArgumentException(
20880                    "replacePreferredActivity expects filter to have only 1 action.");
20881        }
20882        if (filter.countDataAuthorities() != 0
20883                || filter.countDataPaths() != 0
20884                || filter.countDataSchemes() > 1
20885                || filter.countDataTypes() != 0) {
20886            throw new IllegalArgumentException(
20887                    "replacePreferredActivity expects filter to have no data authorities, " +
20888                    "paths, or types; and at most one scheme.");
20889        }
20890
20891        final int callingUid = Binder.getCallingUid();
20892        enforceCrossUserPermission(callingUid, userId,
20893                true /* requireFullPermission */, false /* checkShell */,
20894                "replace preferred activity");
20895        synchronized (mPackages) {
20896            if (mContext.checkCallingOrSelfPermission(
20897                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20898                    != PackageManager.PERMISSION_GRANTED) {
20899                if (getUidTargetSdkVersionLockedLPr(callingUid)
20900                        < Build.VERSION_CODES.FROYO) {
20901                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20902                            + Binder.getCallingUid());
20903                    return;
20904                }
20905                mContext.enforceCallingOrSelfPermission(
20906                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20907            }
20908
20909            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20910            if (pir != null) {
20911                // Get all of the existing entries that exactly match this filter.
20912                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20913                if (existing != null && existing.size() == 1) {
20914                    PreferredActivity cur = existing.get(0);
20915                    if (DEBUG_PREFERRED) {
20916                        Slog.i(TAG, "Checking replace of preferred:");
20917                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20918                        if (!cur.mPref.mAlways) {
20919                            Slog.i(TAG, "  -- CUR; not mAlways!");
20920                        } else {
20921                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20922                            Slog.i(TAG, "  -- CUR: mSet="
20923                                    + Arrays.toString(cur.mPref.mSetComponents));
20924                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20925                            Slog.i(TAG, "  -- NEW: mMatch="
20926                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20927                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20928                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20929                        }
20930                    }
20931                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20932                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20933                            && cur.mPref.sameSet(set)) {
20934                        // Setting the preferred activity to what it happens to be already
20935                        if (DEBUG_PREFERRED) {
20936                            Slog.i(TAG, "Replacing with same preferred activity "
20937                                    + cur.mPref.mShortComponent + " for user "
20938                                    + userId + ":");
20939                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20940                        }
20941                        return;
20942                    }
20943                }
20944
20945                if (existing != null) {
20946                    if (DEBUG_PREFERRED) {
20947                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20948                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20949                    }
20950                    for (int i = 0; i < existing.size(); i++) {
20951                        PreferredActivity pa = existing.get(i);
20952                        if (DEBUG_PREFERRED) {
20953                            Slog.i(TAG, "Removing existing preferred activity "
20954                                    + pa.mPref.mComponent + ":");
20955                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20956                        }
20957                        pir.removeFilter(pa);
20958                    }
20959                }
20960            }
20961            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20962                    "Replacing preferred");
20963        }
20964    }
20965
20966    @Override
20967    public void clearPackagePreferredActivities(String packageName) {
20968        final int callingUid = Binder.getCallingUid();
20969        if (getInstantAppPackageName(callingUid) != null) {
20970            return;
20971        }
20972        // writer
20973        synchronized (mPackages) {
20974            PackageParser.Package pkg = mPackages.get(packageName);
20975            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20976                if (mContext.checkCallingOrSelfPermission(
20977                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20978                        != PackageManager.PERMISSION_GRANTED) {
20979                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20980                            < Build.VERSION_CODES.FROYO) {
20981                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20982                                + callingUid);
20983                        return;
20984                    }
20985                    mContext.enforceCallingOrSelfPermission(
20986                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20987                }
20988            }
20989            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20990            if (ps != null
20991                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20992                return;
20993            }
20994            int user = UserHandle.getCallingUserId();
20995            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20996                scheduleWritePackageRestrictionsLocked(user);
20997            }
20998        }
20999    }
21000
21001    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
21002    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
21003        ArrayList<PreferredActivity> removed = null;
21004        boolean changed = false;
21005        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21006            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
21007            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21008            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
21009                continue;
21010            }
21011            Iterator<PreferredActivity> it = pir.filterIterator();
21012            while (it.hasNext()) {
21013                PreferredActivity pa = it.next();
21014                // Mark entry for removal only if it matches the package name
21015                // and the entry is of type "always".
21016                if (packageName == null ||
21017                        (pa.mPref.mComponent.getPackageName().equals(packageName)
21018                                && pa.mPref.mAlways)) {
21019                    if (removed == null) {
21020                        removed = new ArrayList<PreferredActivity>();
21021                    }
21022                    removed.add(pa);
21023                }
21024            }
21025            if (removed != null) {
21026                for (int j=0; j<removed.size(); j++) {
21027                    PreferredActivity pa = removed.get(j);
21028                    pir.removeFilter(pa);
21029                }
21030                changed = true;
21031            }
21032        }
21033        if (changed) {
21034            postPreferredActivityChangedBroadcast(userId);
21035        }
21036        return changed;
21037    }
21038
21039    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
21040    private void clearIntentFilterVerificationsLPw(int userId) {
21041        final int packageCount = mPackages.size();
21042        for (int i = 0; i < packageCount; i++) {
21043            PackageParser.Package pkg = mPackages.valueAt(i);
21044            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
21045        }
21046    }
21047
21048    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
21049    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
21050        if (userId == UserHandle.USER_ALL) {
21051            if (mSettings.removeIntentFilterVerificationLPw(packageName,
21052                    sUserManager.getUserIds())) {
21053                for (int oneUserId : sUserManager.getUserIds()) {
21054                    scheduleWritePackageRestrictionsLocked(oneUserId);
21055                }
21056            }
21057        } else {
21058            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
21059                scheduleWritePackageRestrictionsLocked(userId);
21060            }
21061        }
21062    }
21063
21064    /** Clears state for all users, and touches intent filter verification policy */
21065    void clearDefaultBrowserIfNeeded(String packageName) {
21066        for (int oneUserId : sUserManager.getUserIds()) {
21067            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
21068        }
21069    }
21070
21071    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
21072        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
21073        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
21074            if (packageName.equals(defaultBrowserPackageName)) {
21075                setDefaultBrowserPackageName(null, userId);
21076            }
21077        }
21078    }
21079
21080    @Override
21081    public void resetApplicationPreferences(int userId) {
21082        mContext.enforceCallingOrSelfPermission(
21083                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
21084        final long identity = Binder.clearCallingIdentity();
21085        // writer
21086        try {
21087            synchronized (mPackages) {
21088                clearPackagePreferredActivitiesLPw(null, userId);
21089                mSettings.applyDefaultPreferredAppsLPw(this, userId);
21090                // TODO: We have to reset the default SMS and Phone. This requires
21091                // significant refactoring to keep all default apps in the package
21092                // manager (cleaner but more work) or have the services provide
21093                // callbacks to the package manager to request a default app reset.
21094                applyFactoryDefaultBrowserLPw(userId);
21095                clearIntentFilterVerificationsLPw(userId);
21096                primeDomainVerificationsLPw(userId);
21097                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
21098                scheduleWritePackageRestrictionsLocked(userId);
21099            }
21100            resetNetworkPolicies(userId);
21101        } finally {
21102            Binder.restoreCallingIdentity(identity);
21103        }
21104    }
21105
21106    @Override
21107    public int getPreferredActivities(List<IntentFilter> outFilters,
21108            List<ComponentName> outActivities, String packageName) {
21109        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21110            return 0;
21111        }
21112        int num = 0;
21113        final int userId = UserHandle.getCallingUserId();
21114        // reader
21115        synchronized (mPackages) {
21116            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
21117            if (pir != null) {
21118                final Iterator<PreferredActivity> it = pir.filterIterator();
21119                while (it.hasNext()) {
21120                    final PreferredActivity pa = it.next();
21121                    if (packageName == null
21122                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
21123                                    && pa.mPref.mAlways)) {
21124                        if (outFilters != null) {
21125                            outFilters.add(new IntentFilter(pa));
21126                        }
21127                        if (outActivities != null) {
21128                            outActivities.add(pa.mPref.mComponent);
21129                        }
21130                    }
21131                }
21132            }
21133        }
21134
21135        return num;
21136    }
21137
21138    @Override
21139    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
21140            int userId) {
21141        int callingUid = Binder.getCallingUid();
21142        if (callingUid != Process.SYSTEM_UID) {
21143            throw new SecurityException(
21144                    "addPersistentPreferredActivity can only be run by the system");
21145        }
21146        if (filter.countActions() == 0) {
21147            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
21148            return;
21149        }
21150        synchronized (mPackages) {
21151            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
21152                    ":");
21153            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
21154            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
21155                    new PersistentPreferredActivity(filter, activity));
21156            scheduleWritePackageRestrictionsLocked(userId);
21157            postPreferredActivityChangedBroadcast(userId);
21158        }
21159    }
21160
21161    @Override
21162    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
21163        int callingUid = Binder.getCallingUid();
21164        if (callingUid != Process.SYSTEM_UID) {
21165            throw new SecurityException(
21166                    "clearPackagePersistentPreferredActivities can only be run by the system");
21167        }
21168        ArrayList<PersistentPreferredActivity> removed = null;
21169        boolean changed = false;
21170        synchronized (mPackages) {
21171            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
21172                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
21173                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
21174                        .valueAt(i);
21175                if (userId != thisUserId) {
21176                    continue;
21177                }
21178                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
21179                while (it.hasNext()) {
21180                    PersistentPreferredActivity ppa = it.next();
21181                    // Mark entry for removal only if it matches the package name.
21182                    if (ppa.mComponent.getPackageName().equals(packageName)) {
21183                        if (removed == null) {
21184                            removed = new ArrayList<PersistentPreferredActivity>();
21185                        }
21186                        removed.add(ppa);
21187                    }
21188                }
21189                if (removed != null) {
21190                    for (int j=0; j<removed.size(); j++) {
21191                        PersistentPreferredActivity ppa = removed.get(j);
21192                        ppir.removeFilter(ppa);
21193                    }
21194                    changed = true;
21195                }
21196            }
21197
21198            if (changed) {
21199                scheduleWritePackageRestrictionsLocked(userId);
21200                postPreferredActivityChangedBroadcast(userId);
21201            }
21202        }
21203    }
21204
21205    /**
21206     * Common machinery for picking apart a restored XML blob and passing
21207     * it to a caller-supplied functor to be applied to the running system.
21208     */
21209    private void restoreFromXml(XmlPullParser parser, int userId,
21210            String expectedStartTag, BlobXmlRestorer functor)
21211            throws IOException, XmlPullParserException {
21212        int type;
21213        while ((type = parser.next()) != XmlPullParser.START_TAG
21214                && type != XmlPullParser.END_DOCUMENT) {
21215        }
21216        if (type != XmlPullParser.START_TAG) {
21217            // oops didn't find a start tag?!
21218            if (DEBUG_BACKUP) {
21219                Slog.e(TAG, "Didn't find start tag during restore");
21220            }
21221            return;
21222        }
21223Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
21224        // this is supposed to be TAG_PREFERRED_BACKUP
21225        if (!expectedStartTag.equals(parser.getName())) {
21226            if (DEBUG_BACKUP) {
21227                Slog.e(TAG, "Found unexpected tag " + parser.getName());
21228            }
21229            return;
21230        }
21231
21232        // skip interfering stuff, then we're aligned with the backing implementation
21233        while ((type = parser.next()) == XmlPullParser.TEXT) { }
21234Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
21235        functor.apply(parser, userId);
21236    }
21237
21238    private interface BlobXmlRestorer {
21239        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
21240    }
21241
21242    /**
21243     * Non-Binder method, support for the backup/restore mechanism: write the
21244     * full set of preferred activities in its canonical XML format.  Returns the
21245     * XML output as a byte array, or null if there is none.
21246     */
21247    @Override
21248    public byte[] getPreferredActivityBackup(int userId) {
21249        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21250            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
21251        }
21252
21253        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21254        try {
21255            final XmlSerializer serializer = new FastXmlSerializer();
21256            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21257            serializer.startDocument(null, true);
21258            serializer.startTag(null, TAG_PREFERRED_BACKUP);
21259
21260            synchronized (mPackages) {
21261                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
21262            }
21263
21264            serializer.endTag(null, TAG_PREFERRED_BACKUP);
21265            serializer.endDocument();
21266            serializer.flush();
21267        } catch (Exception e) {
21268            if (DEBUG_BACKUP) {
21269                Slog.e(TAG, "Unable to write preferred activities for backup", e);
21270            }
21271            return null;
21272        }
21273
21274        return dataStream.toByteArray();
21275    }
21276
21277    @Override
21278    public void restorePreferredActivities(byte[] backup, int userId) {
21279        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21280            throw new SecurityException("Only the system may call restorePreferredActivities()");
21281        }
21282
21283        try {
21284            final XmlPullParser parser = Xml.newPullParser();
21285            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21286            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
21287                    new BlobXmlRestorer() {
21288                        @Override
21289                        public void apply(XmlPullParser parser, int userId)
21290                                throws XmlPullParserException, IOException {
21291                            synchronized (mPackages) {
21292                                mSettings.readPreferredActivitiesLPw(parser, userId);
21293                            }
21294                        }
21295                    } );
21296        } catch (Exception e) {
21297            if (DEBUG_BACKUP) {
21298                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21299            }
21300        }
21301    }
21302
21303    /**
21304     * Non-Binder method, support for the backup/restore mechanism: write the
21305     * default browser (etc) settings in its canonical XML format.  Returns the default
21306     * browser XML representation as a byte array, or null if there is none.
21307     */
21308    @Override
21309    public byte[] getDefaultAppsBackup(int userId) {
21310        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21311            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21312        }
21313
21314        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21315        try {
21316            final XmlSerializer serializer = new FastXmlSerializer();
21317            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21318            serializer.startDocument(null, true);
21319            serializer.startTag(null, TAG_DEFAULT_APPS);
21320
21321            synchronized (mPackages) {
21322                mSettings.writeDefaultAppsLPr(serializer, userId);
21323            }
21324
21325            serializer.endTag(null, TAG_DEFAULT_APPS);
21326            serializer.endDocument();
21327            serializer.flush();
21328        } catch (Exception e) {
21329            if (DEBUG_BACKUP) {
21330                Slog.e(TAG, "Unable to write default apps for backup", e);
21331            }
21332            return null;
21333        }
21334
21335        return dataStream.toByteArray();
21336    }
21337
21338    @Override
21339    public void restoreDefaultApps(byte[] backup, int userId) {
21340        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21341            throw new SecurityException("Only the system may call restoreDefaultApps()");
21342        }
21343
21344        try {
21345            final XmlPullParser parser = Xml.newPullParser();
21346            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21347            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21348                    new BlobXmlRestorer() {
21349                        @Override
21350                        public void apply(XmlPullParser parser, int userId)
21351                                throws XmlPullParserException, IOException {
21352                            synchronized (mPackages) {
21353                                mSettings.readDefaultAppsLPw(parser, userId);
21354                            }
21355                        }
21356                    } );
21357        } catch (Exception e) {
21358            if (DEBUG_BACKUP) {
21359                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21360            }
21361        }
21362    }
21363
21364    @Override
21365    public byte[] getIntentFilterVerificationBackup(int userId) {
21366        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21367            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21368        }
21369
21370        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21371        try {
21372            final XmlSerializer serializer = new FastXmlSerializer();
21373            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21374            serializer.startDocument(null, true);
21375            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21376
21377            synchronized (mPackages) {
21378                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21379            }
21380
21381            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21382            serializer.endDocument();
21383            serializer.flush();
21384        } catch (Exception e) {
21385            if (DEBUG_BACKUP) {
21386                Slog.e(TAG, "Unable to write default apps for backup", e);
21387            }
21388            return null;
21389        }
21390
21391        return dataStream.toByteArray();
21392    }
21393
21394    @Override
21395    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21396        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21397            throw new SecurityException("Only the system may call restorePreferredActivities()");
21398        }
21399
21400        try {
21401            final XmlPullParser parser = Xml.newPullParser();
21402            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21403            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21404                    new BlobXmlRestorer() {
21405                        @Override
21406                        public void apply(XmlPullParser parser, int userId)
21407                                throws XmlPullParserException, IOException {
21408                            synchronized (mPackages) {
21409                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21410                                mSettings.writeLPr();
21411                            }
21412                        }
21413                    } );
21414        } catch (Exception e) {
21415            if (DEBUG_BACKUP) {
21416                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21417            }
21418        }
21419    }
21420
21421    @Override
21422    public byte[] getPermissionGrantBackup(int userId) {
21423        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21424            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21425        }
21426
21427        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21428        try {
21429            final XmlSerializer serializer = new FastXmlSerializer();
21430            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21431            serializer.startDocument(null, true);
21432            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21433
21434            synchronized (mPackages) {
21435                serializeRuntimePermissionGrantsLPr(serializer, userId);
21436            }
21437
21438            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21439            serializer.endDocument();
21440            serializer.flush();
21441        } catch (Exception e) {
21442            if (DEBUG_BACKUP) {
21443                Slog.e(TAG, "Unable to write default apps for backup", e);
21444            }
21445            return null;
21446        }
21447
21448        return dataStream.toByteArray();
21449    }
21450
21451    @Override
21452    public void restorePermissionGrants(byte[] backup, int userId) {
21453        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21454            throw new SecurityException("Only the system may call restorePermissionGrants()");
21455        }
21456
21457        try {
21458            final XmlPullParser parser = Xml.newPullParser();
21459            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21460            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21461                    new BlobXmlRestorer() {
21462                        @Override
21463                        public void apply(XmlPullParser parser, int userId)
21464                                throws XmlPullParserException, IOException {
21465                            synchronized (mPackages) {
21466                                processRestoredPermissionGrantsLPr(parser, userId);
21467                            }
21468                        }
21469                    } );
21470        } catch (Exception e) {
21471            if (DEBUG_BACKUP) {
21472                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21473            }
21474        }
21475    }
21476
21477    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21478            throws IOException {
21479        serializer.startTag(null, TAG_ALL_GRANTS);
21480
21481        final int N = mSettings.mPackages.size();
21482        for (int i = 0; i < N; i++) {
21483            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21484            boolean pkgGrantsKnown = false;
21485
21486            PermissionsState packagePerms = ps.getPermissionsState();
21487
21488            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21489                final int grantFlags = state.getFlags();
21490                // only look at grants that are not system/policy fixed
21491                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21492                    final boolean isGranted = state.isGranted();
21493                    // And only back up the user-twiddled state bits
21494                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21495                        final String packageName = mSettings.mPackages.keyAt(i);
21496                        if (!pkgGrantsKnown) {
21497                            serializer.startTag(null, TAG_GRANT);
21498                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21499                            pkgGrantsKnown = true;
21500                        }
21501
21502                        final boolean userSet =
21503                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21504                        final boolean userFixed =
21505                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21506                        final boolean revoke =
21507                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21508
21509                        serializer.startTag(null, TAG_PERMISSION);
21510                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21511                        if (isGranted) {
21512                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21513                        }
21514                        if (userSet) {
21515                            serializer.attribute(null, ATTR_USER_SET, "true");
21516                        }
21517                        if (userFixed) {
21518                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21519                        }
21520                        if (revoke) {
21521                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21522                        }
21523                        serializer.endTag(null, TAG_PERMISSION);
21524                    }
21525                }
21526            }
21527
21528            if (pkgGrantsKnown) {
21529                serializer.endTag(null, TAG_GRANT);
21530            }
21531        }
21532
21533        serializer.endTag(null, TAG_ALL_GRANTS);
21534    }
21535
21536    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21537            throws XmlPullParserException, IOException {
21538        String pkgName = null;
21539        int outerDepth = parser.getDepth();
21540        int type;
21541        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21542                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21543            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21544                continue;
21545            }
21546
21547            final String tagName = parser.getName();
21548            if (tagName.equals(TAG_GRANT)) {
21549                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21550                if (DEBUG_BACKUP) {
21551                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21552                }
21553            } else if (tagName.equals(TAG_PERMISSION)) {
21554
21555                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21556                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21557
21558                int newFlagSet = 0;
21559                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21560                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21561                }
21562                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21563                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21564                }
21565                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21566                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21567                }
21568                if (DEBUG_BACKUP) {
21569                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21570                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21571                }
21572                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21573                if (ps != null) {
21574                    // Already installed so we apply the grant immediately
21575                    if (DEBUG_BACKUP) {
21576                        Slog.v(TAG, "        + already installed; applying");
21577                    }
21578                    PermissionsState perms = ps.getPermissionsState();
21579                    BasePermission bp = mSettings.mPermissions.get(permName);
21580                    if (bp != null) {
21581                        if (isGranted) {
21582                            perms.grantRuntimePermission(bp, userId);
21583                        }
21584                        if (newFlagSet != 0) {
21585                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21586                        }
21587                    }
21588                } else {
21589                    // Need to wait for post-restore install to apply the grant
21590                    if (DEBUG_BACKUP) {
21591                        Slog.v(TAG, "        - not yet installed; saving for later");
21592                    }
21593                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21594                            isGranted, newFlagSet, userId);
21595                }
21596            } else {
21597                PackageManagerService.reportSettingsProblem(Log.WARN,
21598                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21599                XmlUtils.skipCurrentTag(parser);
21600            }
21601        }
21602
21603        scheduleWriteSettingsLocked();
21604        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21605    }
21606
21607    @Override
21608    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21609            int sourceUserId, int targetUserId, int flags) {
21610        mContext.enforceCallingOrSelfPermission(
21611                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21612        int callingUid = Binder.getCallingUid();
21613        enforceOwnerRights(ownerPackage, callingUid);
21614        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21615        if (intentFilter.countActions() == 0) {
21616            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21617            return;
21618        }
21619        synchronized (mPackages) {
21620            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21621                    ownerPackage, targetUserId, flags);
21622            CrossProfileIntentResolver resolver =
21623                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21624            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21625            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21626            if (existing != null) {
21627                int size = existing.size();
21628                for (int i = 0; i < size; i++) {
21629                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21630                        return;
21631                    }
21632                }
21633            }
21634            resolver.addFilter(newFilter);
21635            scheduleWritePackageRestrictionsLocked(sourceUserId);
21636        }
21637    }
21638
21639    @Override
21640    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21641        mContext.enforceCallingOrSelfPermission(
21642                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21643        final int callingUid = Binder.getCallingUid();
21644        enforceOwnerRights(ownerPackage, callingUid);
21645        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21646        synchronized (mPackages) {
21647            CrossProfileIntentResolver resolver =
21648                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21649            ArraySet<CrossProfileIntentFilter> set =
21650                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21651            for (CrossProfileIntentFilter filter : set) {
21652                if (filter.getOwnerPackage().equals(ownerPackage)) {
21653                    resolver.removeFilter(filter);
21654                }
21655            }
21656            scheduleWritePackageRestrictionsLocked(sourceUserId);
21657        }
21658    }
21659
21660    // Enforcing that callingUid is owning pkg on userId
21661    private void enforceOwnerRights(String pkg, int callingUid) {
21662        // The system owns everything.
21663        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21664            return;
21665        }
21666        final int callingUserId = UserHandle.getUserId(callingUid);
21667        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21668        if (pi == null) {
21669            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21670                    + callingUserId);
21671        }
21672        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21673            throw new SecurityException("Calling uid " + callingUid
21674                    + " does not own package " + pkg);
21675        }
21676    }
21677
21678    @Override
21679    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21680        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21681            return null;
21682        }
21683        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21684    }
21685
21686    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21687        UserManagerService ums = UserManagerService.getInstance();
21688        if (ums != null) {
21689            final UserInfo parent = ums.getProfileParent(userId);
21690            final int launcherUid = (parent != null) ? parent.id : userId;
21691            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21692            if (launcherComponent != null) {
21693                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21694                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21695                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21696                        .setPackage(launcherComponent.getPackageName());
21697                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21698            }
21699        }
21700    }
21701
21702    /**
21703     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21704     * then reports the most likely home activity or null if there are more than one.
21705     */
21706    private ComponentName getDefaultHomeActivity(int userId) {
21707        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21708        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21709        if (cn != null) {
21710            return cn;
21711        }
21712
21713        // Find the launcher with the highest priority and return that component if there are no
21714        // other home activity with the same priority.
21715        int lastPriority = Integer.MIN_VALUE;
21716        ComponentName lastComponent = null;
21717        final int size = allHomeCandidates.size();
21718        for (int i = 0; i < size; i++) {
21719            final ResolveInfo ri = allHomeCandidates.get(i);
21720            if (ri.priority > lastPriority) {
21721                lastComponent = ri.activityInfo.getComponentName();
21722                lastPriority = ri.priority;
21723            } else if (ri.priority == lastPriority) {
21724                // Two components found with same priority.
21725                lastComponent = null;
21726            }
21727        }
21728        return lastComponent;
21729    }
21730
21731    private Intent getHomeIntent() {
21732        Intent intent = new Intent(Intent.ACTION_MAIN);
21733        intent.addCategory(Intent.CATEGORY_HOME);
21734        intent.addCategory(Intent.CATEGORY_DEFAULT);
21735        return intent;
21736    }
21737
21738    private IntentFilter getHomeFilter() {
21739        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21740        filter.addCategory(Intent.CATEGORY_HOME);
21741        filter.addCategory(Intent.CATEGORY_DEFAULT);
21742        return filter;
21743    }
21744
21745    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21746            int userId) {
21747        Intent intent  = getHomeIntent();
21748        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21749                PackageManager.GET_META_DATA, userId);
21750        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21751                true, false, false, userId);
21752
21753        allHomeCandidates.clear();
21754        if (list != null) {
21755            for (ResolveInfo ri : list) {
21756                allHomeCandidates.add(ri);
21757            }
21758        }
21759        return (preferred == null || preferred.activityInfo == null)
21760                ? null
21761                : new ComponentName(preferred.activityInfo.packageName,
21762                        preferred.activityInfo.name);
21763    }
21764
21765    @Override
21766    public void setHomeActivity(ComponentName comp, int userId) {
21767        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21768            return;
21769        }
21770        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21771        getHomeActivitiesAsUser(homeActivities, userId);
21772
21773        boolean found = false;
21774
21775        final int size = homeActivities.size();
21776        final ComponentName[] set = new ComponentName[size];
21777        for (int i = 0; i < size; i++) {
21778            final ResolveInfo candidate = homeActivities.get(i);
21779            final ActivityInfo info = candidate.activityInfo;
21780            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21781            set[i] = activityName;
21782            if (!found && activityName.equals(comp)) {
21783                found = true;
21784            }
21785        }
21786        if (!found) {
21787            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21788                    + userId);
21789        }
21790        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21791                set, comp, userId);
21792    }
21793
21794    private @Nullable String getSetupWizardPackageName() {
21795        final Intent intent = new Intent(Intent.ACTION_MAIN);
21796        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21797
21798        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21799                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21800                        | MATCH_DISABLED_COMPONENTS,
21801                UserHandle.myUserId());
21802        if (matches.size() == 1) {
21803            return matches.get(0).getComponentInfo().packageName;
21804        } else {
21805            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21806                    + ": matches=" + matches);
21807            return null;
21808        }
21809    }
21810
21811    private @Nullable String getStorageManagerPackageName() {
21812        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21813
21814        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21815                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21816                        | MATCH_DISABLED_COMPONENTS,
21817                UserHandle.myUserId());
21818        if (matches.size() == 1) {
21819            return matches.get(0).getComponentInfo().packageName;
21820        } else {
21821            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21822                    + matches.size() + ": matches=" + matches);
21823            return null;
21824        }
21825    }
21826
21827    @Override
21828    public void setApplicationEnabledSetting(String appPackageName,
21829            int newState, int flags, int userId, String callingPackage) {
21830        if (!sUserManager.exists(userId)) return;
21831        if (callingPackage == null) {
21832            callingPackage = Integer.toString(Binder.getCallingUid());
21833        }
21834        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21835    }
21836
21837    @Override
21838    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21839        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21840        synchronized (mPackages) {
21841            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21842            if (pkgSetting != null) {
21843                pkgSetting.setUpdateAvailable(updateAvailable);
21844            }
21845        }
21846    }
21847
21848    @Override
21849    public void setComponentEnabledSetting(ComponentName componentName,
21850            int newState, int flags, int userId) {
21851        if (!sUserManager.exists(userId)) return;
21852        setEnabledSetting(componentName.getPackageName(),
21853                componentName.getClassName(), newState, flags, userId, null);
21854    }
21855
21856    private void setEnabledSetting(final String packageName, String className, int newState,
21857            final int flags, int userId, String callingPackage) {
21858        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21859              || newState == COMPONENT_ENABLED_STATE_ENABLED
21860              || newState == COMPONENT_ENABLED_STATE_DISABLED
21861              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21862              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21863            throw new IllegalArgumentException("Invalid new component state: "
21864                    + newState);
21865        }
21866        PackageSetting pkgSetting;
21867        final int callingUid = Binder.getCallingUid();
21868        final int permission;
21869        if (callingUid == Process.SYSTEM_UID) {
21870            permission = PackageManager.PERMISSION_GRANTED;
21871        } else {
21872            permission = mContext.checkCallingOrSelfPermission(
21873                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21874        }
21875        enforceCrossUserPermission(callingUid, userId,
21876                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21877        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21878        boolean sendNow = false;
21879        boolean isApp = (className == null);
21880        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21881        String componentName = isApp ? packageName : className;
21882        int packageUid = -1;
21883        ArrayList<String> components;
21884
21885        // reader
21886        synchronized (mPackages) {
21887            pkgSetting = mSettings.mPackages.get(packageName);
21888            if (pkgSetting == null) {
21889                if (!isCallerInstantApp) {
21890                    if (className == null) {
21891                        throw new IllegalArgumentException("Unknown package: " + packageName);
21892                    }
21893                    throw new IllegalArgumentException(
21894                            "Unknown component: " + packageName + "/" + className);
21895                } else {
21896                    // throw SecurityException to prevent leaking package information
21897                    throw new SecurityException(
21898                            "Attempt to change component state; "
21899                            + "pid=" + Binder.getCallingPid()
21900                            + ", uid=" + callingUid
21901                            + (className == null
21902                                    ? ", package=" + packageName
21903                                    : ", component=" + packageName + "/" + className));
21904                }
21905            }
21906        }
21907
21908        // Limit who can change which apps
21909        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21910            // Don't allow apps that don't have permission to modify other apps
21911            if (!allowedByPermission
21912                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21913                throw new SecurityException(
21914                        "Attempt to change component state; "
21915                        + "pid=" + Binder.getCallingPid()
21916                        + ", uid=" + callingUid
21917                        + (className == null
21918                                ? ", package=" + packageName
21919                                : ", component=" + packageName + "/" + className));
21920            }
21921            // Don't allow changing protected packages.
21922            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21923                throw new SecurityException("Cannot disable a protected package: " + packageName);
21924            }
21925        }
21926
21927        synchronized (mPackages) {
21928            if (callingUid == Process.SHELL_UID
21929                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21930                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21931                // unless it is a test package.
21932                int oldState = pkgSetting.getEnabled(userId);
21933                if (className == null
21934                        &&
21935                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21936                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21937                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21938                        &&
21939                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21940                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
21941                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21942                    // ok
21943                } else {
21944                    throw new SecurityException(
21945                            "Shell cannot change component state for " + packageName + "/"
21946                                    + className + " to " + newState);
21947                }
21948            }
21949        }
21950        if (className == null) {
21951            // We're dealing with an application/package level state change
21952            synchronized (mPackages) {
21953                if (pkgSetting.getEnabled(userId) == newState) {
21954                    // Nothing to do
21955                    return;
21956                }
21957            }
21958            // If we're enabling a system stub, there's a little more work to do.
21959            // Prior to enabling the package, we need to decompress the APK(s) to the
21960            // data partition and then replace the version on the system partition.
21961            final PackageParser.Package deletedPkg = pkgSetting.pkg;
21962            final boolean isSystemStub = deletedPkg.isStub
21963                    && deletedPkg.isSystemApp();
21964            if (isSystemStub
21965                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21966                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
21967                final File codePath = decompressPackage(deletedPkg);
21968                if (codePath == null) {
21969                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
21970                    return;
21971                }
21972                // TODO remove direct parsing of the package object during internal cleanup
21973                // of scan package
21974                // We need to call parse directly here for no other reason than we need
21975                // the new package in order to disable the old one [we use the information
21976                // for some internal optimization to optionally create a new package setting
21977                // object on replace]. However, we can't get the package from the scan
21978                // because the scan modifies live structures and we need to remove the
21979                // old [system] package from the system before a scan can be attempted.
21980                // Once scan is indempotent we can remove this parse and use the package
21981                // object we scanned, prior to adding it to package settings.
21982                final PackageParser pp = new PackageParser();
21983                pp.setSeparateProcesses(mSeparateProcesses);
21984                pp.setDisplayMetrics(mMetrics);
21985                pp.setCallback(mPackageParserCallback);
21986                final PackageParser.Package tmpPkg;
21987                try {
21988                    final int parseFlags = mDefParseFlags
21989                            | PackageParser.PARSE_MUST_BE_APK
21990                            | PackageParser.PARSE_IS_SYSTEM
21991                            | PackageParser.PARSE_IS_SYSTEM_DIR;
21992                    tmpPkg = pp.parsePackage(codePath, parseFlags);
21993                } catch (PackageParserException e) {
21994                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
21995                    return;
21996                }
21997                synchronized (mInstallLock) {
21998                    // Disable the stub and remove any package entries
21999                    removePackageLI(deletedPkg, true);
22000                    synchronized (mPackages) {
22001                        disableSystemPackageLPw(deletedPkg, tmpPkg);
22002                    }
22003                    final PackageParser.Package newPkg;
22004                    try (PackageFreezer freezer =
22005                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
22006                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
22007                                | PackageParser.PARSE_ENFORCE_CODE;
22008                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
22009                                0 /*currentTime*/, null /*user*/);
22010                        prepareAppDataAfterInstallLIF(newPkg);
22011                        synchronized (mPackages) {
22012                            try {
22013                                updateSharedLibrariesLPr(newPkg, null);
22014                            } catch (PackageManagerException e) {
22015                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
22016                            }
22017                            updatePermissionsLPw(newPkg.packageName, newPkg,
22018                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
22019                            mSettings.writeLPr();
22020                        }
22021                    } catch (PackageManagerException e) {
22022                        // Whoops! Something went wrong; try to roll back to the stub
22023                        Slog.w(TAG, "Failed to install compressed system package:"
22024                                + pkgSetting.name, e);
22025                        // Remove the failed install
22026                        removeCodePathLI(codePath);
22027
22028                        // Install the system package
22029                        try (PackageFreezer freezer =
22030                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
22031                            synchronized (mPackages) {
22032                                // NOTE: The system package always needs to be enabled; even
22033                                // if it's for a compressed stub. If we don't, installing the
22034                                // system package fails during scan [scanning checks the disabled
22035                                // packages]. We will reverse this later, after we've "installed"
22036                                // the stub.
22037                                // This leaves us in a fragile state; the stub should never be
22038                                // enabled, so, cross your fingers and hope nothing goes wrong
22039                                // until we can disable the package later.
22040                                enableSystemPackageLPw(deletedPkg);
22041                            }
22042                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
22043                                    false /*isPrivileged*/, null /*allUserHandles*/,
22044                                    null /*origUserHandles*/, null /*origPermissionsState*/,
22045                                    true /*writeSettings*/);
22046                        } catch (PackageManagerException pme) {
22047                            Slog.w(TAG, "Failed to restore system package:"
22048                                    + deletedPkg.packageName, pme);
22049                        } finally {
22050                            synchronized (mPackages) {
22051                                mSettings.disableSystemPackageLPw(
22052                                        deletedPkg.packageName, true /*replaced*/);
22053                                mSettings.writeLPr();
22054                            }
22055                        }
22056                        return;
22057                    }
22058                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
22059                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22060                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
22061                    mDexManager.notifyPackageUpdated(newPkg.packageName,
22062                            newPkg.baseCodePath, newPkg.splitCodePaths);
22063                }
22064            }
22065            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
22066                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
22067                // Don't care about who enables an app.
22068                callingPackage = null;
22069            }
22070            synchronized (mPackages) {
22071                pkgSetting.setEnabled(newState, userId, callingPackage);
22072            }
22073        } else {
22074            synchronized (mPackages) {
22075                // We're dealing with a component level state change
22076                // First, verify that this is a valid class name.
22077                PackageParser.Package pkg = pkgSetting.pkg;
22078                if (pkg == null || !pkg.hasComponentClassName(className)) {
22079                    if (pkg != null &&
22080                            pkg.applicationInfo.targetSdkVersion >=
22081                                    Build.VERSION_CODES.JELLY_BEAN) {
22082                        throw new IllegalArgumentException("Component class " + className
22083                                + " does not exist in " + packageName);
22084                    } else {
22085                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
22086                                + className + " does not exist in " + packageName);
22087                    }
22088                }
22089                switch (newState) {
22090                    case COMPONENT_ENABLED_STATE_ENABLED:
22091                        if (!pkgSetting.enableComponentLPw(className, userId)) {
22092                            return;
22093                        }
22094                        break;
22095                    case COMPONENT_ENABLED_STATE_DISABLED:
22096                        if (!pkgSetting.disableComponentLPw(className, userId)) {
22097                            return;
22098                        }
22099                        break;
22100                    case COMPONENT_ENABLED_STATE_DEFAULT:
22101                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
22102                            return;
22103                        }
22104                        break;
22105                    default:
22106                        Slog.e(TAG, "Invalid new component state: " + newState);
22107                        return;
22108                }
22109            }
22110        }
22111        synchronized (mPackages) {
22112            scheduleWritePackageRestrictionsLocked(userId);
22113            updateSequenceNumberLP(pkgSetting, new int[] { userId });
22114            final long callingId = Binder.clearCallingIdentity();
22115            try {
22116                updateInstantAppInstallerLocked(packageName);
22117            } finally {
22118                Binder.restoreCallingIdentity(callingId);
22119            }
22120            components = mPendingBroadcasts.get(userId, packageName);
22121            final boolean newPackage = components == null;
22122            if (newPackage) {
22123                components = new ArrayList<String>();
22124            }
22125            if (!components.contains(componentName)) {
22126                components.add(componentName);
22127            }
22128            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
22129                sendNow = true;
22130                // Purge entry from pending broadcast list if another one exists already
22131                // since we are sending one right away.
22132                mPendingBroadcasts.remove(userId, packageName);
22133            } else {
22134                if (newPackage) {
22135                    mPendingBroadcasts.put(userId, packageName, components);
22136                }
22137                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
22138                    // Schedule a message
22139                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
22140                }
22141            }
22142        }
22143
22144        long callingId = Binder.clearCallingIdentity();
22145        try {
22146            if (sendNow) {
22147                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
22148                sendPackageChangedBroadcast(packageName,
22149                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
22150            }
22151        } finally {
22152            Binder.restoreCallingIdentity(callingId);
22153        }
22154    }
22155
22156    @Override
22157    public void flushPackageRestrictionsAsUser(int userId) {
22158        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22159            return;
22160        }
22161        if (!sUserManager.exists(userId)) {
22162            return;
22163        }
22164        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
22165                false /* checkShell */, "flushPackageRestrictions");
22166        synchronized (mPackages) {
22167            mSettings.writePackageRestrictionsLPr(userId);
22168            mDirtyUsers.remove(userId);
22169            if (mDirtyUsers.isEmpty()) {
22170                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
22171            }
22172        }
22173    }
22174
22175    private void sendPackageChangedBroadcast(String packageName,
22176            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
22177        if (DEBUG_INSTALL)
22178            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
22179                    + componentNames);
22180        Bundle extras = new Bundle(4);
22181        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
22182        String nameList[] = new String[componentNames.size()];
22183        componentNames.toArray(nameList);
22184        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
22185        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
22186        extras.putInt(Intent.EXTRA_UID, packageUid);
22187        // If this is not reporting a change of the overall package, then only send it
22188        // to registered receivers.  We don't want to launch a swath of apps for every
22189        // little component state change.
22190        final int flags = !componentNames.contains(packageName)
22191                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
22192        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
22193                new int[] {UserHandle.getUserId(packageUid)});
22194    }
22195
22196    @Override
22197    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
22198        if (!sUserManager.exists(userId)) return;
22199        final int callingUid = Binder.getCallingUid();
22200        if (getInstantAppPackageName(callingUid) != null) {
22201            return;
22202        }
22203        final int permission = mContext.checkCallingOrSelfPermission(
22204                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
22205        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
22206        enforceCrossUserPermission(callingUid, userId,
22207                true /* requireFullPermission */, true /* checkShell */, "stop package");
22208        // writer
22209        synchronized (mPackages) {
22210            final PackageSetting ps = mSettings.mPackages.get(packageName);
22211            if (!filterAppAccessLPr(ps, callingUid, userId)
22212                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
22213                            allowedByPermission, callingUid, userId)) {
22214                scheduleWritePackageRestrictionsLocked(userId);
22215            }
22216        }
22217    }
22218
22219    @Override
22220    public String getInstallerPackageName(String packageName) {
22221        final int callingUid = Binder.getCallingUid();
22222        if (getInstantAppPackageName(callingUid) != null) {
22223            return null;
22224        }
22225        // reader
22226        synchronized (mPackages) {
22227            final PackageSetting ps = mSettings.mPackages.get(packageName);
22228            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
22229                return null;
22230            }
22231            return mSettings.getInstallerPackageNameLPr(packageName);
22232        }
22233    }
22234
22235    public boolean isOrphaned(String packageName) {
22236        // reader
22237        synchronized (mPackages) {
22238            return mSettings.isOrphaned(packageName);
22239        }
22240    }
22241
22242    @Override
22243    public int getApplicationEnabledSetting(String packageName, int userId) {
22244        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22245        int callingUid = Binder.getCallingUid();
22246        enforceCrossUserPermission(callingUid, userId,
22247                false /* requireFullPermission */, false /* checkShell */, "get enabled");
22248        // reader
22249        synchronized (mPackages) {
22250            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
22251                return COMPONENT_ENABLED_STATE_DISABLED;
22252            }
22253            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
22254        }
22255    }
22256
22257    @Override
22258    public int getComponentEnabledSetting(ComponentName component, int userId) {
22259        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22260        int callingUid = Binder.getCallingUid();
22261        enforceCrossUserPermission(callingUid, userId,
22262                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
22263        synchronized (mPackages) {
22264            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
22265                    component, TYPE_UNKNOWN, userId)) {
22266                return COMPONENT_ENABLED_STATE_DISABLED;
22267            }
22268            return mSettings.getComponentEnabledSettingLPr(component, userId);
22269        }
22270    }
22271
22272    @Override
22273    public void enterSafeMode() {
22274        enforceSystemOrRoot("Only the system can request entering safe mode");
22275
22276        if (!mSystemReady) {
22277            mSafeMode = true;
22278        }
22279    }
22280
22281    @Override
22282    public void systemReady() {
22283        enforceSystemOrRoot("Only the system can claim the system is ready");
22284
22285        mSystemReady = true;
22286        final ContentResolver resolver = mContext.getContentResolver();
22287        ContentObserver co = new ContentObserver(mHandler) {
22288            @Override
22289            public void onChange(boolean selfChange) {
22290                mEphemeralAppsDisabled =
22291                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
22292                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
22293            }
22294        };
22295        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22296                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
22297                false, co, UserHandle.USER_SYSTEM);
22298        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22299                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
22300        co.onChange(true);
22301
22302        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
22303        // disabled after already being started.
22304        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
22305                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
22306
22307        // Read the compatibilty setting when the system is ready.
22308        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
22309                mContext.getContentResolver(),
22310                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
22311        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
22312        if (DEBUG_SETTINGS) {
22313            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
22314        }
22315
22316        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
22317
22318        synchronized (mPackages) {
22319            // Verify that all of the preferred activity components actually
22320            // exist.  It is possible for applications to be updated and at
22321            // that point remove a previously declared activity component that
22322            // had been set as a preferred activity.  We try to clean this up
22323            // the next time we encounter that preferred activity, but it is
22324            // possible for the user flow to never be able to return to that
22325            // situation so here we do a sanity check to make sure we haven't
22326            // left any junk around.
22327            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
22328            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22329                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22330                removed.clear();
22331                for (PreferredActivity pa : pir.filterSet()) {
22332                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
22333                        removed.add(pa);
22334                    }
22335                }
22336                if (removed.size() > 0) {
22337                    for (int r=0; r<removed.size(); r++) {
22338                        PreferredActivity pa = removed.get(r);
22339                        Slog.w(TAG, "Removing dangling preferred activity: "
22340                                + pa.mPref.mComponent);
22341                        pir.removeFilter(pa);
22342                    }
22343                    mSettings.writePackageRestrictionsLPr(
22344                            mSettings.mPreferredActivities.keyAt(i));
22345                }
22346            }
22347
22348            for (int userId : UserManagerService.getInstance().getUserIds()) {
22349                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
22350                    grantPermissionsUserIds = ArrayUtils.appendInt(
22351                            grantPermissionsUserIds, userId);
22352                }
22353            }
22354        }
22355        sUserManager.systemReady();
22356
22357        // If we upgraded grant all default permissions before kicking off.
22358        for (int userId : grantPermissionsUserIds) {
22359            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22360        }
22361
22362        // If we did not grant default permissions, we preload from this the
22363        // default permission exceptions lazily to ensure we don't hit the
22364        // disk on a new user creation.
22365        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
22366            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
22367        }
22368
22369        // Kick off any messages waiting for system ready
22370        if (mPostSystemReadyMessages != null) {
22371            for (Message msg : mPostSystemReadyMessages) {
22372                msg.sendToTarget();
22373            }
22374            mPostSystemReadyMessages = null;
22375        }
22376
22377        // Watch for external volumes that come and go over time
22378        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22379        storage.registerListener(mStorageListener);
22380
22381        mInstallerService.systemReady();
22382        mPackageDexOptimizer.systemReady();
22383
22384        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22385                StorageManagerInternal.class);
22386        StorageManagerInternal.addExternalStoragePolicy(
22387                new StorageManagerInternal.ExternalStorageMountPolicy() {
22388            @Override
22389            public int getMountMode(int uid, String packageName) {
22390                if (Process.isIsolated(uid)) {
22391                    return Zygote.MOUNT_EXTERNAL_NONE;
22392                }
22393                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22394                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22395                }
22396                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22397                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22398                }
22399                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22400                    return Zygote.MOUNT_EXTERNAL_READ;
22401                }
22402                return Zygote.MOUNT_EXTERNAL_WRITE;
22403            }
22404
22405            @Override
22406            public boolean hasExternalStorage(int uid, String packageName) {
22407                return true;
22408            }
22409        });
22410
22411        // Now that we're mostly running, clean up stale users and apps
22412        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22413        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22414
22415        if (mPrivappPermissionsViolations != null) {
22416            Slog.wtf(TAG,"Signature|privileged permissions not in "
22417                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22418            mPrivappPermissionsViolations = null;
22419        }
22420    }
22421
22422    public void waitForAppDataPrepared() {
22423        if (mPrepareAppDataFuture == null) {
22424            return;
22425        }
22426        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22427        mPrepareAppDataFuture = null;
22428    }
22429
22430    @Override
22431    public boolean isSafeMode() {
22432        // allow instant applications
22433        return mSafeMode;
22434    }
22435
22436    @Override
22437    public boolean hasSystemUidErrors() {
22438        // allow instant applications
22439        return mHasSystemUidErrors;
22440    }
22441
22442    static String arrayToString(int[] array) {
22443        StringBuffer buf = new StringBuffer(128);
22444        buf.append('[');
22445        if (array != null) {
22446            for (int i=0; i<array.length; i++) {
22447                if (i > 0) buf.append(", ");
22448                buf.append(array[i]);
22449            }
22450        }
22451        buf.append(']');
22452        return buf.toString();
22453    }
22454
22455    static class DumpState {
22456        public static final int DUMP_LIBS = 1 << 0;
22457        public static final int DUMP_FEATURES = 1 << 1;
22458        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22459        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22460        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22461        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22462        public static final int DUMP_PERMISSIONS = 1 << 6;
22463        public static final int DUMP_PACKAGES = 1 << 7;
22464        public static final int DUMP_SHARED_USERS = 1 << 8;
22465        public static final int DUMP_MESSAGES = 1 << 9;
22466        public static final int DUMP_PROVIDERS = 1 << 10;
22467        public static final int DUMP_VERIFIERS = 1 << 11;
22468        public static final int DUMP_PREFERRED = 1 << 12;
22469        public static final int DUMP_PREFERRED_XML = 1 << 13;
22470        public static final int DUMP_KEYSETS = 1 << 14;
22471        public static final int DUMP_VERSION = 1 << 15;
22472        public static final int DUMP_INSTALLS = 1 << 16;
22473        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22474        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22475        public static final int DUMP_FROZEN = 1 << 19;
22476        public static final int DUMP_DEXOPT = 1 << 20;
22477        public static final int DUMP_COMPILER_STATS = 1 << 21;
22478        public static final int DUMP_CHANGES = 1 << 22;
22479        public static final int DUMP_VOLUMES = 1 << 23;
22480
22481        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22482
22483        private int mTypes;
22484
22485        private int mOptions;
22486
22487        private boolean mTitlePrinted;
22488
22489        private SharedUserSetting mSharedUser;
22490
22491        public boolean isDumping(int type) {
22492            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22493                return true;
22494            }
22495
22496            return (mTypes & type) != 0;
22497        }
22498
22499        public void setDump(int type) {
22500            mTypes |= type;
22501        }
22502
22503        public boolean isOptionEnabled(int option) {
22504            return (mOptions & option) != 0;
22505        }
22506
22507        public void setOptionEnabled(int option) {
22508            mOptions |= option;
22509        }
22510
22511        public boolean onTitlePrinted() {
22512            final boolean printed = mTitlePrinted;
22513            mTitlePrinted = true;
22514            return printed;
22515        }
22516
22517        public boolean getTitlePrinted() {
22518            return mTitlePrinted;
22519        }
22520
22521        public void setTitlePrinted(boolean enabled) {
22522            mTitlePrinted = enabled;
22523        }
22524
22525        public SharedUserSetting getSharedUser() {
22526            return mSharedUser;
22527        }
22528
22529        public void setSharedUser(SharedUserSetting user) {
22530            mSharedUser = user;
22531        }
22532    }
22533
22534    @Override
22535    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22536            FileDescriptor err, String[] args, ShellCallback callback,
22537            ResultReceiver resultReceiver) {
22538        (new PackageManagerShellCommand(this)).exec(
22539                this, in, out, err, args, callback, resultReceiver);
22540    }
22541
22542    @Override
22543    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22544        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22545
22546        DumpState dumpState = new DumpState();
22547        boolean fullPreferred = false;
22548        boolean checkin = false;
22549
22550        String packageName = null;
22551        ArraySet<String> permissionNames = null;
22552
22553        int opti = 0;
22554        while (opti < args.length) {
22555            String opt = args[opti];
22556            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22557                break;
22558            }
22559            opti++;
22560
22561            if ("-a".equals(opt)) {
22562                // Right now we only know how to print all.
22563            } else if ("-h".equals(opt)) {
22564                pw.println("Package manager dump options:");
22565                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22566                pw.println("    --checkin: dump for a checkin");
22567                pw.println("    -f: print details of intent filters");
22568                pw.println("    -h: print this help");
22569                pw.println("  cmd may be one of:");
22570                pw.println("    l[ibraries]: list known shared libraries");
22571                pw.println("    f[eatures]: list device features");
22572                pw.println("    k[eysets]: print known keysets");
22573                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22574                pw.println("    perm[issions]: dump permissions");
22575                pw.println("    permission [name ...]: dump declaration and use of given permission");
22576                pw.println("    pref[erred]: print preferred package settings");
22577                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22578                pw.println("    prov[iders]: dump content providers");
22579                pw.println("    p[ackages]: dump installed packages");
22580                pw.println("    s[hared-users]: dump shared user IDs");
22581                pw.println("    m[essages]: print collected runtime messages");
22582                pw.println("    v[erifiers]: print package verifier info");
22583                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22584                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22585                pw.println("    version: print database version info");
22586                pw.println("    write: write current settings now");
22587                pw.println("    installs: details about install sessions");
22588                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22589                pw.println("    dexopt: dump dexopt state");
22590                pw.println("    compiler-stats: dump compiler statistics");
22591                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22592                pw.println("    <package.name>: info about given package");
22593                return;
22594            } else if ("--checkin".equals(opt)) {
22595                checkin = true;
22596            } else if ("-f".equals(opt)) {
22597                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22598            } else if ("--proto".equals(opt)) {
22599                dumpProto(fd);
22600                return;
22601            } else {
22602                pw.println("Unknown argument: " + opt + "; use -h for help");
22603            }
22604        }
22605
22606        // Is the caller requesting to dump a particular piece of data?
22607        if (opti < args.length) {
22608            String cmd = args[opti];
22609            opti++;
22610            // Is this a package name?
22611            if ("android".equals(cmd) || cmd.contains(".")) {
22612                packageName = cmd;
22613                // When dumping a single package, we always dump all of its
22614                // filter information since the amount of data will be reasonable.
22615                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22616            } else if ("check-permission".equals(cmd)) {
22617                if (opti >= args.length) {
22618                    pw.println("Error: check-permission missing permission argument");
22619                    return;
22620                }
22621                String perm = args[opti];
22622                opti++;
22623                if (opti >= args.length) {
22624                    pw.println("Error: check-permission missing package argument");
22625                    return;
22626                }
22627
22628                String pkg = args[opti];
22629                opti++;
22630                int user = UserHandle.getUserId(Binder.getCallingUid());
22631                if (opti < args.length) {
22632                    try {
22633                        user = Integer.parseInt(args[opti]);
22634                    } catch (NumberFormatException e) {
22635                        pw.println("Error: check-permission user argument is not a number: "
22636                                + args[opti]);
22637                        return;
22638                    }
22639                }
22640
22641                // Normalize package name to handle renamed packages and static libs
22642                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22643
22644                pw.println(checkPermission(perm, pkg, user));
22645                return;
22646            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22647                dumpState.setDump(DumpState.DUMP_LIBS);
22648            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22649                dumpState.setDump(DumpState.DUMP_FEATURES);
22650            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22651                if (opti >= args.length) {
22652                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22653                            | DumpState.DUMP_SERVICE_RESOLVERS
22654                            | DumpState.DUMP_RECEIVER_RESOLVERS
22655                            | DumpState.DUMP_CONTENT_RESOLVERS);
22656                } else {
22657                    while (opti < args.length) {
22658                        String name = args[opti];
22659                        if ("a".equals(name) || "activity".equals(name)) {
22660                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22661                        } else if ("s".equals(name) || "service".equals(name)) {
22662                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22663                        } else if ("r".equals(name) || "receiver".equals(name)) {
22664                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22665                        } else if ("c".equals(name) || "content".equals(name)) {
22666                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22667                        } else {
22668                            pw.println("Error: unknown resolver table type: " + name);
22669                            return;
22670                        }
22671                        opti++;
22672                    }
22673                }
22674            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22675                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22676            } else if ("permission".equals(cmd)) {
22677                if (opti >= args.length) {
22678                    pw.println("Error: permission requires permission name");
22679                    return;
22680                }
22681                permissionNames = new ArraySet<>();
22682                while (opti < args.length) {
22683                    permissionNames.add(args[opti]);
22684                    opti++;
22685                }
22686                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22687                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22688            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22689                dumpState.setDump(DumpState.DUMP_PREFERRED);
22690            } else if ("preferred-xml".equals(cmd)) {
22691                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22692                if (opti < args.length && "--full".equals(args[opti])) {
22693                    fullPreferred = true;
22694                    opti++;
22695                }
22696            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22697                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22698            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22699                dumpState.setDump(DumpState.DUMP_PACKAGES);
22700            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22701                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22702            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22703                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22704            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22705                dumpState.setDump(DumpState.DUMP_MESSAGES);
22706            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22707                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22708            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22709                    || "intent-filter-verifiers".equals(cmd)) {
22710                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22711            } else if ("version".equals(cmd)) {
22712                dumpState.setDump(DumpState.DUMP_VERSION);
22713            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22714                dumpState.setDump(DumpState.DUMP_KEYSETS);
22715            } else if ("installs".equals(cmd)) {
22716                dumpState.setDump(DumpState.DUMP_INSTALLS);
22717            } else if ("frozen".equals(cmd)) {
22718                dumpState.setDump(DumpState.DUMP_FROZEN);
22719            } else if ("volumes".equals(cmd)) {
22720                dumpState.setDump(DumpState.DUMP_VOLUMES);
22721            } else if ("dexopt".equals(cmd)) {
22722                dumpState.setDump(DumpState.DUMP_DEXOPT);
22723            } else if ("compiler-stats".equals(cmd)) {
22724                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22725            } else if ("changes".equals(cmd)) {
22726                dumpState.setDump(DumpState.DUMP_CHANGES);
22727            } else if ("write".equals(cmd)) {
22728                synchronized (mPackages) {
22729                    mSettings.writeLPr();
22730                    pw.println("Settings written.");
22731                    return;
22732                }
22733            }
22734        }
22735
22736        if (checkin) {
22737            pw.println("vers,1");
22738        }
22739
22740        // reader
22741        synchronized (mPackages) {
22742            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22743                if (!checkin) {
22744                    if (dumpState.onTitlePrinted())
22745                        pw.println();
22746                    pw.println("Database versions:");
22747                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22748                }
22749            }
22750
22751            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22752                if (!checkin) {
22753                    if (dumpState.onTitlePrinted())
22754                        pw.println();
22755                    pw.println("Verifiers:");
22756                    pw.print("  Required: ");
22757                    pw.print(mRequiredVerifierPackage);
22758                    pw.print(" (uid=");
22759                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22760                            UserHandle.USER_SYSTEM));
22761                    pw.println(")");
22762                } else if (mRequiredVerifierPackage != null) {
22763                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22764                    pw.print(",");
22765                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22766                            UserHandle.USER_SYSTEM));
22767                }
22768            }
22769
22770            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22771                    packageName == null) {
22772                if (mIntentFilterVerifierComponent != null) {
22773                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22774                    if (!checkin) {
22775                        if (dumpState.onTitlePrinted())
22776                            pw.println();
22777                        pw.println("Intent Filter Verifier:");
22778                        pw.print("  Using: ");
22779                        pw.print(verifierPackageName);
22780                        pw.print(" (uid=");
22781                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22782                                UserHandle.USER_SYSTEM));
22783                        pw.println(")");
22784                    } else if (verifierPackageName != null) {
22785                        pw.print("ifv,"); pw.print(verifierPackageName);
22786                        pw.print(",");
22787                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22788                                UserHandle.USER_SYSTEM));
22789                    }
22790                } else {
22791                    pw.println();
22792                    pw.println("No Intent Filter Verifier available!");
22793                }
22794            }
22795
22796            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22797                boolean printedHeader = false;
22798                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22799                while (it.hasNext()) {
22800                    String libName = it.next();
22801                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22802                    if (versionedLib == null) {
22803                        continue;
22804                    }
22805                    final int versionCount = versionedLib.size();
22806                    for (int i = 0; i < versionCount; i++) {
22807                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22808                        if (!checkin) {
22809                            if (!printedHeader) {
22810                                if (dumpState.onTitlePrinted())
22811                                    pw.println();
22812                                pw.println("Libraries:");
22813                                printedHeader = true;
22814                            }
22815                            pw.print("  ");
22816                        } else {
22817                            pw.print("lib,");
22818                        }
22819                        pw.print(libEntry.info.getName());
22820                        if (libEntry.info.isStatic()) {
22821                            pw.print(" version=" + libEntry.info.getVersion());
22822                        }
22823                        if (!checkin) {
22824                            pw.print(" -> ");
22825                        }
22826                        if (libEntry.path != null) {
22827                            pw.print(" (jar) ");
22828                            pw.print(libEntry.path);
22829                        } else {
22830                            pw.print(" (apk) ");
22831                            pw.print(libEntry.apk);
22832                        }
22833                        pw.println();
22834                    }
22835                }
22836            }
22837
22838            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22839                if (dumpState.onTitlePrinted())
22840                    pw.println();
22841                if (!checkin) {
22842                    pw.println("Features:");
22843                }
22844
22845                synchronized (mAvailableFeatures) {
22846                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22847                        if (checkin) {
22848                            pw.print("feat,");
22849                            pw.print(feat.name);
22850                            pw.print(",");
22851                            pw.println(feat.version);
22852                        } else {
22853                            pw.print("  ");
22854                            pw.print(feat.name);
22855                            if (feat.version > 0) {
22856                                pw.print(" version=");
22857                                pw.print(feat.version);
22858                            }
22859                            pw.println();
22860                        }
22861                    }
22862                }
22863            }
22864
22865            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22866                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22867                        : "Activity Resolver Table:", "  ", packageName,
22868                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22869                    dumpState.setTitlePrinted(true);
22870                }
22871            }
22872            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22873                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22874                        : "Receiver Resolver Table:", "  ", packageName,
22875                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22876                    dumpState.setTitlePrinted(true);
22877                }
22878            }
22879            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22880                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22881                        : "Service Resolver Table:", "  ", packageName,
22882                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22883                    dumpState.setTitlePrinted(true);
22884                }
22885            }
22886            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22887                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22888                        : "Provider Resolver Table:", "  ", packageName,
22889                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22890                    dumpState.setTitlePrinted(true);
22891                }
22892            }
22893
22894            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22895                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22896                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22897                    int user = mSettings.mPreferredActivities.keyAt(i);
22898                    if (pir.dump(pw,
22899                            dumpState.getTitlePrinted()
22900                                ? "\nPreferred Activities User " + user + ":"
22901                                : "Preferred Activities User " + user + ":", "  ",
22902                            packageName, true, false)) {
22903                        dumpState.setTitlePrinted(true);
22904                    }
22905                }
22906            }
22907
22908            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22909                pw.flush();
22910                FileOutputStream fout = new FileOutputStream(fd);
22911                BufferedOutputStream str = new BufferedOutputStream(fout);
22912                XmlSerializer serializer = new FastXmlSerializer();
22913                try {
22914                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22915                    serializer.startDocument(null, true);
22916                    serializer.setFeature(
22917                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22918                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22919                    serializer.endDocument();
22920                    serializer.flush();
22921                } catch (IllegalArgumentException e) {
22922                    pw.println("Failed writing: " + e);
22923                } catch (IllegalStateException e) {
22924                    pw.println("Failed writing: " + e);
22925                } catch (IOException e) {
22926                    pw.println("Failed writing: " + e);
22927                }
22928            }
22929
22930            if (!checkin
22931                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22932                    && packageName == null) {
22933                pw.println();
22934                int count = mSettings.mPackages.size();
22935                if (count == 0) {
22936                    pw.println("No applications!");
22937                    pw.println();
22938                } else {
22939                    final String prefix = "  ";
22940                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22941                    if (allPackageSettings.size() == 0) {
22942                        pw.println("No domain preferred apps!");
22943                        pw.println();
22944                    } else {
22945                        pw.println("App verification status:");
22946                        pw.println();
22947                        count = 0;
22948                        for (PackageSetting ps : allPackageSettings) {
22949                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22950                            if (ivi == null || ivi.getPackageName() == null) continue;
22951                            pw.println(prefix + "Package: " + ivi.getPackageName());
22952                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22953                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22954                            pw.println();
22955                            count++;
22956                        }
22957                        if (count == 0) {
22958                            pw.println(prefix + "No app verification established.");
22959                            pw.println();
22960                        }
22961                        for (int userId : sUserManager.getUserIds()) {
22962                            pw.println("App linkages for user " + userId + ":");
22963                            pw.println();
22964                            count = 0;
22965                            for (PackageSetting ps : allPackageSettings) {
22966                                final long status = ps.getDomainVerificationStatusForUser(userId);
22967                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22968                                        && !DEBUG_DOMAIN_VERIFICATION) {
22969                                    continue;
22970                                }
22971                                pw.println(prefix + "Package: " + ps.name);
22972                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22973                                String statusStr = IntentFilterVerificationInfo.
22974                                        getStatusStringFromValue(status);
22975                                pw.println(prefix + "Status:  " + statusStr);
22976                                pw.println();
22977                                count++;
22978                            }
22979                            if (count == 0) {
22980                                pw.println(prefix + "No configured app linkages.");
22981                                pw.println();
22982                            }
22983                        }
22984                    }
22985                }
22986            }
22987
22988            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22989                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22990                if (packageName == null && permissionNames == null) {
22991                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22992                        if (iperm == 0) {
22993                            if (dumpState.onTitlePrinted())
22994                                pw.println();
22995                            pw.println("AppOp Permissions:");
22996                        }
22997                        pw.print("  AppOp Permission ");
22998                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22999                        pw.println(":");
23000                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
23001                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
23002                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
23003                        }
23004                    }
23005                }
23006            }
23007
23008            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
23009                boolean printedSomething = false;
23010                for (PackageParser.Provider p : mProviders.mProviders.values()) {
23011                    if (packageName != null && !packageName.equals(p.info.packageName)) {
23012                        continue;
23013                    }
23014                    if (!printedSomething) {
23015                        if (dumpState.onTitlePrinted())
23016                            pw.println();
23017                        pw.println("Registered ContentProviders:");
23018                        printedSomething = true;
23019                    }
23020                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
23021                    pw.print("    "); pw.println(p.toString());
23022                }
23023                printedSomething = false;
23024                for (Map.Entry<String, PackageParser.Provider> entry :
23025                        mProvidersByAuthority.entrySet()) {
23026                    PackageParser.Provider p = entry.getValue();
23027                    if (packageName != null && !packageName.equals(p.info.packageName)) {
23028                        continue;
23029                    }
23030                    if (!printedSomething) {
23031                        if (dumpState.onTitlePrinted())
23032                            pw.println();
23033                        pw.println("ContentProvider Authorities:");
23034                        printedSomething = true;
23035                    }
23036                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
23037                    pw.print("    "); pw.println(p.toString());
23038                    if (p.info != null && p.info.applicationInfo != null) {
23039                        final String appInfo = p.info.applicationInfo.toString();
23040                        pw.print("      applicationInfo="); pw.println(appInfo);
23041                    }
23042                }
23043            }
23044
23045            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
23046                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
23047            }
23048
23049            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
23050                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
23051            }
23052
23053            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
23054                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
23055            }
23056
23057            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
23058                if (dumpState.onTitlePrinted()) pw.println();
23059                pw.println("Package Changes:");
23060                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
23061                final int K = mChangedPackages.size();
23062                for (int i = 0; i < K; i++) {
23063                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
23064                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
23065                    final int N = changes.size();
23066                    if (N == 0) {
23067                        pw.print("    "); pw.println("No packages changed");
23068                    } else {
23069                        for (int j = 0; j < N; j++) {
23070                            final String pkgName = changes.valueAt(j);
23071                            final int sequenceNumber = changes.keyAt(j);
23072                            pw.print("    ");
23073                            pw.print("seq=");
23074                            pw.print(sequenceNumber);
23075                            pw.print(", package=");
23076                            pw.println(pkgName);
23077                        }
23078                    }
23079                }
23080            }
23081
23082            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
23083                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
23084            }
23085
23086            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
23087                // XXX should handle packageName != null by dumping only install data that
23088                // the given package is involved with.
23089                if (dumpState.onTitlePrinted()) pw.println();
23090
23091                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23092                ipw.println();
23093                ipw.println("Frozen packages:");
23094                ipw.increaseIndent();
23095                if (mFrozenPackages.size() == 0) {
23096                    ipw.println("(none)");
23097                } else {
23098                    for (int i = 0; i < mFrozenPackages.size(); i++) {
23099                        ipw.println(mFrozenPackages.valueAt(i));
23100                    }
23101                }
23102                ipw.decreaseIndent();
23103            }
23104
23105            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
23106                if (dumpState.onTitlePrinted()) pw.println();
23107
23108                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23109                ipw.println();
23110                ipw.println("Loaded volumes:");
23111                ipw.increaseIndent();
23112                if (mLoadedVolumes.size() == 0) {
23113                    ipw.println("(none)");
23114                } else {
23115                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
23116                        ipw.println(mLoadedVolumes.valueAt(i));
23117                    }
23118                }
23119                ipw.decreaseIndent();
23120            }
23121
23122            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
23123                if (dumpState.onTitlePrinted()) pw.println();
23124                dumpDexoptStateLPr(pw, packageName);
23125            }
23126
23127            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
23128                if (dumpState.onTitlePrinted()) pw.println();
23129                dumpCompilerStatsLPr(pw, packageName);
23130            }
23131
23132            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
23133                if (dumpState.onTitlePrinted()) pw.println();
23134                mSettings.dumpReadMessagesLPr(pw, dumpState);
23135
23136                pw.println();
23137                pw.println("Package warning messages:");
23138                BufferedReader in = null;
23139                String line = null;
23140                try {
23141                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23142                    while ((line = in.readLine()) != null) {
23143                        if (line.contains("ignored: updated version")) continue;
23144                        pw.println(line);
23145                    }
23146                } catch (IOException ignored) {
23147                } finally {
23148                    IoUtils.closeQuietly(in);
23149                }
23150            }
23151
23152            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
23153                BufferedReader in = null;
23154                String line = null;
23155                try {
23156                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23157                    while ((line = in.readLine()) != null) {
23158                        if (line.contains("ignored: updated version")) continue;
23159                        pw.print("msg,");
23160                        pw.println(line);
23161                    }
23162                } catch (IOException ignored) {
23163                } finally {
23164                    IoUtils.closeQuietly(in);
23165                }
23166            }
23167        }
23168
23169        // PackageInstaller should be called outside of mPackages lock
23170        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
23171            // XXX should handle packageName != null by dumping only install data that
23172            // the given package is involved with.
23173            if (dumpState.onTitlePrinted()) pw.println();
23174            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
23175        }
23176    }
23177
23178    private void dumpProto(FileDescriptor fd) {
23179        final ProtoOutputStream proto = new ProtoOutputStream(fd);
23180
23181        synchronized (mPackages) {
23182            final long requiredVerifierPackageToken =
23183                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
23184            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
23185            proto.write(
23186                    PackageServiceDumpProto.PackageShortProto.UID,
23187                    getPackageUid(
23188                            mRequiredVerifierPackage,
23189                            MATCH_DEBUG_TRIAGED_MISSING,
23190                            UserHandle.USER_SYSTEM));
23191            proto.end(requiredVerifierPackageToken);
23192
23193            if (mIntentFilterVerifierComponent != null) {
23194                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
23195                final long verifierPackageToken =
23196                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
23197                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
23198                proto.write(
23199                        PackageServiceDumpProto.PackageShortProto.UID,
23200                        getPackageUid(
23201                                verifierPackageName,
23202                                MATCH_DEBUG_TRIAGED_MISSING,
23203                                UserHandle.USER_SYSTEM));
23204                proto.end(verifierPackageToken);
23205            }
23206
23207            dumpSharedLibrariesProto(proto);
23208            dumpFeaturesProto(proto);
23209            mSettings.dumpPackagesProto(proto);
23210            mSettings.dumpSharedUsersProto(proto);
23211            dumpMessagesProto(proto);
23212        }
23213        proto.flush();
23214    }
23215
23216    private void dumpMessagesProto(ProtoOutputStream proto) {
23217        BufferedReader in = null;
23218        String line = null;
23219        try {
23220            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23221            while ((line = in.readLine()) != null) {
23222                if (line.contains("ignored: updated version")) continue;
23223                proto.write(PackageServiceDumpProto.MESSAGES, line);
23224            }
23225        } catch (IOException ignored) {
23226        } finally {
23227            IoUtils.closeQuietly(in);
23228        }
23229    }
23230
23231    private void dumpFeaturesProto(ProtoOutputStream proto) {
23232        synchronized (mAvailableFeatures) {
23233            final int count = mAvailableFeatures.size();
23234            for (int i = 0; i < count; i++) {
23235                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
23236                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
23237                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
23238                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
23239                proto.end(featureToken);
23240            }
23241        }
23242    }
23243
23244    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
23245        final int count = mSharedLibraries.size();
23246        for (int i = 0; i < count; i++) {
23247            final String libName = mSharedLibraries.keyAt(i);
23248            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
23249            if (versionedLib == null) {
23250                continue;
23251            }
23252            final int versionCount = versionedLib.size();
23253            for (int j = 0; j < versionCount; j++) {
23254                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
23255                final long sharedLibraryToken =
23256                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
23257                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
23258                final boolean isJar = (libEntry.path != null);
23259                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
23260                if (isJar) {
23261                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
23262                } else {
23263                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
23264                }
23265                proto.end(sharedLibraryToken);
23266            }
23267        }
23268    }
23269
23270    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
23271        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23272        ipw.println();
23273        ipw.println("Dexopt state:");
23274        ipw.increaseIndent();
23275        Collection<PackageParser.Package> packages = null;
23276        if (packageName != null) {
23277            PackageParser.Package targetPackage = mPackages.get(packageName);
23278            if (targetPackage != null) {
23279                packages = Collections.singletonList(targetPackage);
23280            } else {
23281                ipw.println("Unable to find package: " + packageName);
23282                return;
23283            }
23284        } else {
23285            packages = mPackages.values();
23286        }
23287
23288        for (PackageParser.Package pkg : packages) {
23289            ipw.println("[" + pkg.packageName + "]");
23290            ipw.increaseIndent();
23291            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
23292                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
23293            ipw.decreaseIndent();
23294        }
23295    }
23296
23297    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
23298        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23299        ipw.println();
23300        ipw.println("Compiler stats:");
23301        ipw.increaseIndent();
23302        Collection<PackageParser.Package> packages = null;
23303        if (packageName != null) {
23304            PackageParser.Package targetPackage = mPackages.get(packageName);
23305            if (targetPackage != null) {
23306                packages = Collections.singletonList(targetPackage);
23307            } else {
23308                ipw.println("Unable to find package: " + packageName);
23309                return;
23310            }
23311        } else {
23312            packages = mPackages.values();
23313        }
23314
23315        for (PackageParser.Package pkg : packages) {
23316            ipw.println("[" + pkg.packageName + "]");
23317            ipw.increaseIndent();
23318
23319            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
23320            if (stats == null) {
23321                ipw.println("(No recorded stats)");
23322            } else {
23323                stats.dump(ipw);
23324            }
23325            ipw.decreaseIndent();
23326        }
23327    }
23328
23329    private String dumpDomainString(String packageName) {
23330        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
23331                .getList();
23332        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
23333
23334        ArraySet<String> result = new ArraySet<>();
23335        if (iviList.size() > 0) {
23336            for (IntentFilterVerificationInfo ivi : iviList) {
23337                for (String host : ivi.getDomains()) {
23338                    result.add(host);
23339                }
23340            }
23341        }
23342        if (filters != null && filters.size() > 0) {
23343            for (IntentFilter filter : filters) {
23344                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
23345                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
23346                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
23347                    result.addAll(filter.getHostsList());
23348                }
23349            }
23350        }
23351
23352        StringBuilder sb = new StringBuilder(result.size() * 16);
23353        for (String domain : result) {
23354            if (sb.length() > 0) sb.append(" ");
23355            sb.append(domain);
23356        }
23357        return sb.toString();
23358    }
23359
23360    // ------- apps on sdcard specific code -------
23361    static final boolean DEBUG_SD_INSTALL = false;
23362
23363    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
23364
23365    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
23366
23367    private boolean mMediaMounted = false;
23368
23369    static String getEncryptKey() {
23370        try {
23371            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
23372                    SD_ENCRYPTION_KEYSTORE_NAME);
23373            if (sdEncKey == null) {
23374                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23375                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23376                if (sdEncKey == null) {
23377                    Slog.e(TAG, "Failed to create encryption keys");
23378                    return null;
23379                }
23380            }
23381            return sdEncKey;
23382        } catch (NoSuchAlgorithmException nsae) {
23383            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23384            return null;
23385        } catch (IOException ioe) {
23386            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23387            return null;
23388        }
23389    }
23390
23391    /*
23392     * Update media status on PackageManager.
23393     */
23394    @Override
23395    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
23396        enforceSystemOrRoot("Media status can only be updated by the system");
23397        // reader; this apparently protects mMediaMounted, but should probably
23398        // be a different lock in that case.
23399        synchronized (mPackages) {
23400            Log.i(TAG, "Updating external media status from "
23401                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
23402                    + (mediaStatus ? "mounted" : "unmounted"));
23403            if (DEBUG_SD_INSTALL)
23404                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
23405                        + ", mMediaMounted=" + mMediaMounted);
23406            if (mediaStatus == mMediaMounted) {
23407                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
23408                        : 0, -1);
23409                mHandler.sendMessage(msg);
23410                return;
23411            }
23412            mMediaMounted = mediaStatus;
23413        }
23414        // Queue up an async operation since the package installation may take a
23415        // little while.
23416        mHandler.post(new Runnable() {
23417            public void run() {
23418                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23419            }
23420        });
23421    }
23422
23423    /**
23424     * Called by StorageManagerService when the initial ASECs to scan are available.
23425     * Should block until all the ASEC containers are finished being scanned.
23426     */
23427    public void scanAvailableAsecs() {
23428        updateExternalMediaStatusInner(true, false, false);
23429    }
23430
23431    /*
23432     * Collect information of applications on external media, map them against
23433     * existing containers and update information based on current mount status.
23434     * Please note that we always have to report status if reportStatus has been
23435     * set to true especially when unloading packages.
23436     */
23437    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23438            boolean externalStorage) {
23439        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23440        int[] uidArr = EmptyArray.INT;
23441
23442        final String[] list = PackageHelper.getSecureContainerList();
23443        if (ArrayUtils.isEmpty(list)) {
23444            Log.i(TAG, "No secure containers found");
23445        } else {
23446            // Process list of secure containers and categorize them
23447            // as active or stale based on their package internal state.
23448
23449            // reader
23450            synchronized (mPackages) {
23451                for (String cid : list) {
23452                    // Leave stages untouched for now; installer service owns them
23453                    if (PackageInstallerService.isStageName(cid)) continue;
23454
23455                    if (DEBUG_SD_INSTALL)
23456                        Log.i(TAG, "Processing container " + cid);
23457                    String pkgName = getAsecPackageName(cid);
23458                    if (pkgName == null) {
23459                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23460                        continue;
23461                    }
23462                    if (DEBUG_SD_INSTALL)
23463                        Log.i(TAG, "Looking for pkg : " + pkgName);
23464
23465                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23466                    if (ps == null) {
23467                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23468                        continue;
23469                    }
23470
23471                    /*
23472                     * Skip packages that are not external if we're unmounting
23473                     * external storage.
23474                     */
23475                    if (externalStorage && !isMounted && !isExternal(ps)) {
23476                        continue;
23477                    }
23478
23479                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23480                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23481                    // The package status is changed only if the code path
23482                    // matches between settings and the container id.
23483                    if (ps.codePathString != null
23484                            && ps.codePathString.startsWith(args.getCodePath())) {
23485                        if (DEBUG_SD_INSTALL) {
23486                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23487                                    + " at code path: " + ps.codePathString);
23488                        }
23489
23490                        // We do have a valid package installed on sdcard
23491                        processCids.put(args, ps.codePathString);
23492                        final int uid = ps.appId;
23493                        if (uid != -1) {
23494                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23495                        }
23496                    } else {
23497                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23498                                + ps.codePathString);
23499                    }
23500                }
23501            }
23502
23503            Arrays.sort(uidArr);
23504        }
23505
23506        // Process packages with valid entries.
23507        if (isMounted) {
23508            if (DEBUG_SD_INSTALL)
23509                Log.i(TAG, "Loading packages");
23510            loadMediaPackages(processCids, uidArr, externalStorage);
23511            startCleaningPackages();
23512            mInstallerService.onSecureContainersAvailable();
23513        } else {
23514            if (DEBUG_SD_INSTALL)
23515                Log.i(TAG, "Unloading packages");
23516            unloadMediaPackages(processCids, uidArr, reportStatus);
23517        }
23518    }
23519
23520    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23521            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23522        final int size = infos.size();
23523        final String[] packageNames = new String[size];
23524        final int[] packageUids = new int[size];
23525        for (int i = 0; i < size; i++) {
23526            final ApplicationInfo info = infos.get(i);
23527            packageNames[i] = info.packageName;
23528            packageUids[i] = info.uid;
23529        }
23530        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23531                finishedReceiver);
23532    }
23533
23534    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23535            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23536        sendResourcesChangedBroadcast(mediaStatus, replacing,
23537                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23538    }
23539
23540    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23541            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23542        int size = pkgList.length;
23543        if (size > 0) {
23544            // Send broadcasts here
23545            Bundle extras = new Bundle();
23546            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23547            if (uidArr != null) {
23548                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23549            }
23550            if (replacing) {
23551                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23552            }
23553            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23554                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23555            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23556        }
23557    }
23558
23559   /*
23560     * Look at potentially valid container ids from processCids If package
23561     * information doesn't match the one on record or package scanning fails,
23562     * the cid is added to list of removeCids. We currently don't delete stale
23563     * containers.
23564     */
23565    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23566            boolean externalStorage) {
23567        ArrayList<String> pkgList = new ArrayList<String>();
23568        Set<AsecInstallArgs> keys = processCids.keySet();
23569
23570        for (AsecInstallArgs args : keys) {
23571            String codePath = processCids.get(args);
23572            if (DEBUG_SD_INSTALL)
23573                Log.i(TAG, "Loading container : " + args.cid);
23574            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23575            try {
23576                // Make sure there are no container errors first.
23577                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23578                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23579                            + " when installing from sdcard");
23580                    continue;
23581                }
23582                // Check code path here.
23583                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23584                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23585                            + " does not match one in settings " + codePath);
23586                    continue;
23587                }
23588                // Parse package
23589                int parseFlags = mDefParseFlags;
23590                if (args.isExternalAsec()) {
23591                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23592                }
23593                if (args.isFwdLocked()) {
23594                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23595                }
23596
23597                synchronized (mInstallLock) {
23598                    PackageParser.Package pkg = null;
23599                    try {
23600                        // Sadly we don't know the package name yet to freeze it
23601                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23602                                SCAN_IGNORE_FROZEN, 0, null);
23603                    } catch (PackageManagerException e) {
23604                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23605                    }
23606                    // Scan the package
23607                    if (pkg != null) {
23608                        /*
23609                         * TODO why is the lock being held? doPostInstall is
23610                         * called in other places without the lock. This needs
23611                         * to be straightened out.
23612                         */
23613                        // writer
23614                        synchronized (mPackages) {
23615                            retCode = PackageManager.INSTALL_SUCCEEDED;
23616                            pkgList.add(pkg.packageName);
23617                            // Post process args
23618                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23619                                    pkg.applicationInfo.uid);
23620                        }
23621                    } else {
23622                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23623                    }
23624                }
23625
23626            } finally {
23627                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23628                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23629                }
23630            }
23631        }
23632        // writer
23633        synchronized (mPackages) {
23634            // If the platform SDK has changed since the last time we booted,
23635            // we need to re-grant app permission to catch any new ones that
23636            // appear. This is really a hack, and means that apps can in some
23637            // cases get permissions that the user didn't initially explicitly
23638            // allow... it would be nice to have some better way to handle
23639            // this situation.
23640            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23641                    : mSettings.getInternalVersion();
23642            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23643                    : StorageManager.UUID_PRIVATE_INTERNAL;
23644
23645            int updateFlags = UPDATE_PERMISSIONS_ALL;
23646            if (ver.sdkVersion != mSdkVersion) {
23647                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23648                        + mSdkVersion + "; regranting permissions for external");
23649                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23650            }
23651            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23652
23653            // Yay, everything is now upgraded
23654            ver.forceCurrent();
23655
23656            // can downgrade to reader
23657            // Persist settings
23658            mSettings.writeLPr();
23659        }
23660        // Send a broadcast to let everyone know we are done processing
23661        if (pkgList.size() > 0) {
23662            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23663        }
23664    }
23665
23666   /*
23667     * Utility method to unload a list of specified containers
23668     */
23669    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23670        // Just unmount all valid containers.
23671        for (AsecInstallArgs arg : cidArgs) {
23672            synchronized (mInstallLock) {
23673                arg.doPostDeleteLI(false);
23674           }
23675       }
23676   }
23677
23678    /*
23679     * Unload packages mounted on external media. This involves deleting package
23680     * data from internal structures, sending broadcasts about disabled packages,
23681     * gc'ing to free up references, unmounting all secure containers
23682     * corresponding to packages on external media, and posting a
23683     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23684     * that we always have to post this message if status has been requested no
23685     * matter what.
23686     */
23687    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23688            final boolean reportStatus) {
23689        if (DEBUG_SD_INSTALL)
23690            Log.i(TAG, "unloading media packages");
23691        ArrayList<String> pkgList = new ArrayList<String>();
23692        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23693        final Set<AsecInstallArgs> keys = processCids.keySet();
23694        for (AsecInstallArgs args : keys) {
23695            String pkgName = args.getPackageName();
23696            if (DEBUG_SD_INSTALL)
23697                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23698            // Delete package internally
23699            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23700            synchronized (mInstallLock) {
23701                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23702                final boolean res;
23703                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23704                        "unloadMediaPackages")) {
23705                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23706                            null);
23707                }
23708                if (res) {
23709                    pkgList.add(pkgName);
23710                } else {
23711                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23712                    failedList.add(args);
23713                }
23714            }
23715        }
23716
23717        // reader
23718        synchronized (mPackages) {
23719            // We didn't update the settings after removing each package;
23720            // write them now for all packages.
23721            mSettings.writeLPr();
23722        }
23723
23724        // We have to absolutely send UPDATED_MEDIA_STATUS only
23725        // after confirming that all the receivers processed the ordered
23726        // broadcast when packages get disabled, force a gc to clean things up.
23727        // and unload all the containers.
23728        if (pkgList.size() > 0) {
23729            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23730                    new IIntentReceiver.Stub() {
23731                public void performReceive(Intent intent, int resultCode, String data,
23732                        Bundle extras, boolean ordered, boolean sticky,
23733                        int sendingUser) throws RemoteException {
23734                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23735                            reportStatus ? 1 : 0, 1, keys);
23736                    mHandler.sendMessage(msg);
23737                }
23738            });
23739        } else {
23740            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23741                    keys);
23742            mHandler.sendMessage(msg);
23743        }
23744    }
23745
23746    private void loadPrivatePackages(final VolumeInfo vol) {
23747        mHandler.post(new Runnable() {
23748            @Override
23749            public void run() {
23750                loadPrivatePackagesInner(vol);
23751            }
23752        });
23753    }
23754
23755    private void loadPrivatePackagesInner(VolumeInfo vol) {
23756        final String volumeUuid = vol.fsUuid;
23757        if (TextUtils.isEmpty(volumeUuid)) {
23758            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23759            return;
23760        }
23761
23762        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23763        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23764        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23765
23766        final VersionInfo ver;
23767        final List<PackageSetting> packages;
23768        synchronized (mPackages) {
23769            ver = mSettings.findOrCreateVersion(volumeUuid);
23770            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23771        }
23772
23773        for (PackageSetting ps : packages) {
23774            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23775            synchronized (mInstallLock) {
23776                final PackageParser.Package pkg;
23777                try {
23778                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23779                    loaded.add(pkg.applicationInfo);
23780
23781                } catch (PackageManagerException e) {
23782                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23783                }
23784
23785                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23786                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23787                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23788                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23789                }
23790            }
23791        }
23792
23793        // Reconcile app data for all started/unlocked users
23794        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23795        final UserManager um = mContext.getSystemService(UserManager.class);
23796        UserManagerInternal umInternal = getUserManagerInternal();
23797        for (UserInfo user : um.getUsers()) {
23798            final int flags;
23799            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23800                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23801            } else if (umInternal.isUserRunning(user.id)) {
23802                flags = StorageManager.FLAG_STORAGE_DE;
23803            } else {
23804                continue;
23805            }
23806
23807            try {
23808                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23809                synchronized (mInstallLock) {
23810                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23811                }
23812            } catch (IllegalStateException e) {
23813                // Device was probably ejected, and we'll process that event momentarily
23814                Slog.w(TAG, "Failed to prepare storage: " + e);
23815            }
23816        }
23817
23818        synchronized (mPackages) {
23819            int updateFlags = UPDATE_PERMISSIONS_ALL;
23820            if (ver.sdkVersion != mSdkVersion) {
23821                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23822                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23823                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23824            }
23825            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23826
23827            // Yay, everything is now upgraded
23828            ver.forceCurrent();
23829
23830            mSettings.writeLPr();
23831        }
23832
23833        for (PackageFreezer freezer : freezers) {
23834            freezer.close();
23835        }
23836
23837        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23838        sendResourcesChangedBroadcast(true, false, loaded, null);
23839        mLoadedVolumes.add(vol.getId());
23840    }
23841
23842    private void unloadPrivatePackages(final VolumeInfo vol) {
23843        mHandler.post(new Runnable() {
23844            @Override
23845            public void run() {
23846                unloadPrivatePackagesInner(vol);
23847            }
23848        });
23849    }
23850
23851    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23852        final String volumeUuid = vol.fsUuid;
23853        if (TextUtils.isEmpty(volumeUuid)) {
23854            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23855            return;
23856        }
23857
23858        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23859        synchronized (mInstallLock) {
23860        synchronized (mPackages) {
23861            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23862            for (PackageSetting ps : packages) {
23863                if (ps.pkg == null) continue;
23864
23865                final ApplicationInfo info = ps.pkg.applicationInfo;
23866                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23867                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23868
23869                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23870                        "unloadPrivatePackagesInner")) {
23871                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23872                            false, null)) {
23873                        unloaded.add(info);
23874                    } else {
23875                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23876                    }
23877                }
23878
23879                // Try very hard to release any references to this package
23880                // so we don't risk the system server being killed due to
23881                // open FDs
23882                AttributeCache.instance().removePackage(ps.name);
23883            }
23884
23885            mSettings.writeLPr();
23886        }
23887        }
23888
23889        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23890        sendResourcesChangedBroadcast(false, false, unloaded, null);
23891        mLoadedVolumes.remove(vol.getId());
23892
23893        // Try very hard to release any references to this path so we don't risk
23894        // the system server being killed due to open FDs
23895        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23896
23897        for (int i = 0; i < 3; i++) {
23898            System.gc();
23899            System.runFinalization();
23900        }
23901    }
23902
23903    private void assertPackageKnown(String volumeUuid, String packageName)
23904            throws PackageManagerException {
23905        synchronized (mPackages) {
23906            // Normalize package name to handle renamed packages
23907            packageName = normalizePackageNameLPr(packageName);
23908
23909            final PackageSetting ps = mSettings.mPackages.get(packageName);
23910            if (ps == null) {
23911                throw new PackageManagerException("Package " + packageName + " is unknown");
23912            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23913                throw new PackageManagerException(
23914                        "Package " + packageName + " found on unknown volume " + volumeUuid
23915                                + "; expected volume " + ps.volumeUuid);
23916            }
23917        }
23918    }
23919
23920    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23921            throws PackageManagerException {
23922        synchronized (mPackages) {
23923            // Normalize package name to handle renamed packages
23924            packageName = normalizePackageNameLPr(packageName);
23925
23926            final PackageSetting ps = mSettings.mPackages.get(packageName);
23927            if (ps == null) {
23928                throw new PackageManagerException("Package " + packageName + " is unknown");
23929            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23930                throw new PackageManagerException(
23931                        "Package " + packageName + " found on unknown volume " + volumeUuid
23932                                + "; expected volume " + ps.volumeUuid);
23933            } else if (!ps.getInstalled(userId)) {
23934                throw new PackageManagerException(
23935                        "Package " + packageName + " not installed for user " + userId);
23936            }
23937        }
23938    }
23939
23940    private List<String> collectAbsoluteCodePaths() {
23941        synchronized (mPackages) {
23942            List<String> codePaths = new ArrayList<>();
23943            final int packageCount = mSettings.mPackages.size();
23944            for (int i = 0; i < packageCount; i++) {
23945                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23946                codePaths.add(ps.codePath.getAbsolutePath());
23947            }
23948            return codePaths;
23949        }
23950    }
23951
23952    /**
23953     * Examine all apps present on given mounted volume, and destroy apps that
23954     * aren't expected, either due to uninstallation or reinstallation on
23955     * another volume.
23956     */
23957    private void reconcileApps(String volumeUuid) {
23958        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23959        List<File> filesToDelete = null;
23960
23961        final File[] files = FileUtils.listFilesOrEmpty(
23962                Environment.getDataAppDirectory(volumeUuid));
23963        for (File file : files) {
23964            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23965                    && !PackageInstallerService.isStageName(file.getName());
23966            if (!isPackage) {
23967                // Ignore entries which are not packages
23968                continue;
23969            }
23970
23971            String absolutePath = file.getAbsolutePath();
23972
23973            boolean pathValid = false;
23974            final int absoluteCodePathCount = absoluteCodePaths.size();
23975            for (int i = 0; i < absoluteCodePathCount; i++) {
23976                String absoluteCodePath = absoluteCodePaths.get(i);
23977                if (absolutePath.startsWith(absoluteCodePath)) {
23978                    pathValid = true;
23979                    break;
23980                }
23981            }
23982
23983            if (!pathValid) {
23984                if (filesToDelete == null) {
23985                    filesToDelete = new ArrayList<>();
23986                }
23987                filesToDelete.add(file);
23988            }
23989        }
23990
23991        if (filesToDelete != null) {
23992            final int fileToDeleteCount = filesToDelete.size();
23993            for (int i = 0; i < fileToDeleteCount; i++) {
23994                File fileToDelete = filesToDelete.get(i);
23995                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23996                synchronized (mInstallLock) {
23997                    removeCodePathLI(fileToDelete);
23998                }
23999            }
24000        }
24001    }
24002
24003    /**
24004     * Reconcile all app data for the given user.
24005     * <p>
24006     * Verifies that directories exist and that ownership and labeling is
24007     * correct for all installed apps on all mounted volumes.
24008     */
24009    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
24010        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24011        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
24012            final String volumeUuid = vol.getFsUuid();
24013            synchronized (mInstallLock) {
24014                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
24015            }
24016        }
24017    }
24018
24019    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
24020            boolean migrateAppData) {
24021        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
24022    }
24023
24024    /**
24025     * Reconcile all app data on given mounted volume.
24026     * <p>
24027     * Destroys app data that isn't expected, either due to uninstallation or
24028     * reinstallation on another volume.
24029     * <p>
24030     * Verifies that directories exist and that ownership and labeling is
24031     * correct for all installed apps.
24032     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
24033     */
24034    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
24035            boolean migrateAppData, boolean onlyCoreApps) {
24036        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
24037                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
24038        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
24039
24040        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
24041        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
24042
24043        // First look for stale data that doesn't belong, and check if things
24044        // have changed since we did our last restorecon
24045        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24046            if (StorageManager.isFileEncryptedNativeOrEmulated()
24047                    && !StorageManager.isUserKeyUnlocked(userId)) {
24048                throw new RuntimeException(
24049                        "Yikes, someone asked us to reconcile CE storage while " + userId
24050                                + " was still locked; this would have caused massive data loss!");
24051            }
24052
24053            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
24054            for (File file : files) {
24055                final String packageName = file.getName();
24056                try {
24057                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
24058                } catch (PackageManagerException e) {
24059                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
24060                    try {
24061                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
24062                                StorageManager.FLAG_STORAGE_CE, 0);
24063                    } catch (InstallerException e2) {
24064                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
24065                    }
24066                }
24067            }
24068        }
24069        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
24070            final File[] files = FileUtils.listFilesOrEmpty(deDir);
24071            for (File file : files) {
24072                final String packageName = file.getName();
24073                try {
24074                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
24075                } catch (PackageManagerException e) {
24076                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
24077                    try {
24078                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
24079                                StorageManager.FLAG_STORAGE_DE, 0);
24080                    } catch (InstallerException e2) {
24081                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
24082                    }
24083                }
24084            }
24085        }
24086
24087        // Ensure that data directories are ready to roll for all packages
24088        // installed for this volume and user
24089        final List<PackageSetting> packages;
24090        synchronized (mPackages) {
24091            packages = mSettings.getVolumePackagesLPr(volumeUuid);
24092        }
24093        int preparedCount = 0;
24094        for (PackageSetting ps : packages) {
24095            final String packageName = ps.name;
24096            if (ps.pkg == null) {
24097                Slog.w(TAG, "Odd, missing scanned package " + packageName);
24098                // TODO: might be due to legacy ASEC apps; we should circle back
24099                // and reconcile again once they're scanned
24100                continue;
24101            }
24102            // Skip non-core apps if requested
24103            if (onlyCoreApps && !ps.pkg.coreApp) {
24104                result.add(packageName);
24105                continue;
24106            }
24107
24108            if (ps.getInstalled(userId)) {
24109                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
24110                preparedCount++;
24111            }
24112        }
24113
24114        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
24115        return result;
24116    }
24117
24118    /**
24119     * Prepare app data for the given app just after it was installed or
24120     * upgraded. This method carefully only touches users that it's installed
24121     * for, and it forces a restorecon to handle any seinfo changes.
24122     * <p>
24123     * Verifies that directories exist and that ownership and labeling is
24124     * correct for all installed apps. If there is an ownership mismatch, it
24125     * will try recovering system apps by wiping data; third-party app data is
24126     * left intact.
24127     * <p>
24128     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
24129     */
24130    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
24131        final PackageSetting ps;
24132        synchronized (mPackages) {
24133            ps = mSettings.mPackages.get(pkg.packageName);
24134            mSettings.writeKernelMappingLPr(ps);
24135        }
24136
24137        final UserManager um = mContext.getSystemService(UserManager.class);
24138        UserManagerInternal umInternal = getUserManagerInternal();
24139        for (UserInfo user : um.getUsers()) {
24140            final int flags;
24141            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
24142                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
24143            } else if (umInternal.isUserRunning(user.id)) {
24144                flags = StorageManager.FLAG_STORAGE_DE;
24145            } else {
24146                continue;
24147            }
24148
24149            if (ps.getInstalled(user.id)) {
24150                // TODO: when user data is locked, mark that we're still dirty
24151                prepareAppDataLIF(pkg, user.id, flags);
24152            }
24153        }
24154    }
24155
24156    /**
24157     * Prepare app data for the given app.
24158     * <p>
24159     * Verifies that directories exist and that ownership and labeling is
24160     * correct for all installed apps. If there is an ownership mismatch, this
24161     * will try recovering system apps by wiping data; third-party app data is
24162     * left intact.
24163     */
24164    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
24165        if (pkg == null) {
24166            Slog.wtf(TAG, "Package was null!", new Throwable());
24167            return;
24168        }
24169        prepareAppDataLeafLIF(pkg, userId, flags);
24170        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24171        for (int i = 0; i < childCount; i++) {
24172            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
24173        }
24174    }
24175
24176    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
24177            boolean maybeMigrateAppData) {
24178        prepareAppDataLIF(pkg, userId, flags);
24179
24180        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
24181            // We may have just shuffled around app data directories, so
24182            // prepare them one more time
24183            prepareAppDataLIF(pkg, userId, flags);
24184        }
24185    }
24186
24187    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24188        if (DEBUG_APP_DATA) {
24189            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
24190                    + Integer.toHexString(flags));
24191        }
24192
24193        final String volumeUuid = pkg.volumeUuid;
24194        final String packageName = pkg.packageName;
24195        final ApplicationInfo app = pkg.applicationInfo;
24196        final int appId = UserHandle.getAppId(app.uid);
24197
24198        Preconditions.checkNotNull(app.seInfo);
24199
24200        long ceDataInode = -1;
24201        try {
24202            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24203                    appId, app.seInfo, app.targetSdkVersion);
24204        } catch (InstallerException e) {
24205            if (app.isSystemApp()) {
24206                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
24207                        + ", but trying to recover: " + e);
24208                destroyAppDataLeafLIF(pkg, userId, flags);
24209                try {
24210                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24211                            appId, app.seInfo, app.targetSdkVersion);
24212                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
24213                } catch (InstallerException e2) {
24214                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
24215                }
24216            } else {
24217                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
24218            }
24219        }
24220
24221        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
24222            // TODO: mark this structure as dirty so we persist it!
24223            synchronized (mPackages) {
24224                final PackageSetting ps = mSettings.mPackages.get(packageName);
24225                if (ps != null) {
24226                    ps.setCeDataInode(ceDataInode, userId);
24227                }
24228            }
24229        }
24230
24231        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24232    }
24233
24234    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
24235        if (pkg == null) {
24236            Slog.wtf(TAG, "Package was null!", new Throwable());
24237            return;
24238        }
24239        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24240        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24241        for (int i = 0; i < childCount; i++) {
24242            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
24243        }
24244    }
24245
24246    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24247        final String volumeUuid = pkg.volumeUuid;
24248        final String packageName = pkg.packageName;
24249        final ApplicationInfo app = pkg.applicationInfo;
24250
24251        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24252            // Create a native library symlink only if we have native libraries
24253            // and if the native libraries are 32 bit libraries. We do not provide
24254            // this symlink for 64 bit libraries.
24255            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
24256                final String nativeLibPath = app.nativeLibraryDir;
24257                try {
24258                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
24259                            nativeLibPath, userId);
24260                } catch (InstallerException e) {
24261                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
24262                }
24263            }
24264        }
24265    }
24266
24267    /**
24268     * For system apps on non-FBE devices, this method migrates any existing
24269     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
24270     * requested by the app.
24271     */
24272    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
24273        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
24274                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
24275            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
24276                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
24277            try {
24278                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
24279                        storageTarget);
24280            } catch (InstallerException e) {
24281                logCriticalInfo(Log.WARN,
24282                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
24283            }
24284            return true;
24285        } else {
24286            return false;
24287        }
24288    }
24289
24290    public PackageFreezer freezePackage(String packageName, String killReason) {
24291        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
24292    }
24293
24294    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
24295        return new PackageFreezer(packageName, userId, killReason);
24296    }
24297
24298    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
24299            String killReason) {
24300        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
24301    }
24302
24303    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
24304            String killReason) {
24305        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
24306            return new PackageFreezer();
24307        } else {
24308            return freezePackage(packageName, userId, killReason);
24309        }
24310    }
24311
24312    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
24313            String killReason) {
24314        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
24315    }
24316
24317    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
24318            String killReason) {
24319        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
24320            return new PackageFreezer();
24321        } else {
24322            return freezePackage(packageName, userId, killReason);
24323        }
24324    }
24325
24326    /**
24327     * Class that freezes and kills the given package upon creation, and
24328     * unfreezes it upon closing. This is typically used when doing surgery on
24329     * app code/data to prevent the app from running while you're working.
24330     */
24331    private class PackageFreezer implements AutoCloseable {
24332        private final String mPackageName;
24333        private final PackageFreezer[] mChildren;
24334
24335        private final boolean mWeFroze;
24336
24337        private final AtomicBoolean mClosed = new AtomicBoolean();
24338        private final CloseGuard mCloseGuard = CloseGuard.get();
24339
24340        /**
24341         * Create and return a stub freezer that doesn't actually do anything,
24342         * typically used when someone requested
24343         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
24344         * {@link PackageManager#DELETE_DONT_KILL_APP}.
24345         */
24346        public PackageFreezer() {
24347            mPackageName = null;
24348            mChildren = null;
24349            mWeFroze = false;
24350            mCloseGuard.open("close");
24351        }
24352
24353        public PackageFreezer(String packageName, int userId, String killReason) {
24354            synchronized (mPackages) {
24355                mPackageName = packageName;
24356                mWeFroze = mFrozenPackages.add(mPackageName);
24357
24358                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
24359                if (ps != null) {
24360                    killApplication(ps.name, ps.appId, userId, killReason);
24361                }
24362
24363                final PackageParser.Package p = mPackages.get(packageName);
24364                if (p != null && p.childPackages != null) {
24365                    final int N = p.childPackages.size();
24366                    mChildren = new PackageFreezer[N];
24367                    for (int i = 0; i < N; i++) {
24368                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
24369                                userId, killReason);
24370                    }
24371                } else {
24372                    mChildren = null;
24373                }
24374            }
24375            mCloseGuard.open("close");
24376        }
24377
24378        @Override
24379        protected void finalize() throws Throwable {
24380            try {
24381                if (mCloseGuard != null) {
24382                    mCloseGuard.warnIfOpen();
24383                }
24384
24385                close();
24386            } finally {
24387                super.finalize();
24388            }
24389        }
24390
24391        @Override
24392        public void close() {
24393            mCloseGuard.close();
24394            if (mClosed.compareAndSet(false, true)) {
24395                synchronized (mPackages) {
24396                    if (mWeFroze) {
24397                        mFrozenPackages.remove(mPackageName);
24398                    }
24399
24400                    if (mChildren != null) {
24401                        for (PackageFreezer freezer : mChildren) {
24402                            freezer.close();
24403                        }
24404                    }
24405                }
24406            }
24407        }
24408    }
24409
24410    /**
24411     * Verify that given package is currently frozen.
24412     */
24413    private void checkPackageFrozen(String packageName) {
24414        synchronized (mPackages) {
24415            if (!mFrozenPackages.contains(packageName)) {
24416                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24417            }
24418        }
24419    }
24420
24421    @Override
24422    public int movePackage(final String packageName, final String volumeUuid) {
24423        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24424
24425        final int callingUid = Binder.getCallingUid();
24426        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24427        final int moveId = mNextMoveId.getAndIncrement();
24428        mHandler.post(new Runnable() {
24429            @Override
24430            public void run() {
24431                try {
24432                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24433                } catch (PackageManagerException e) {
24434                    Slog.w(TAG, "Failed to move " + packageName, e);
24435                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24436                }
24437            }
24438        });
24439        return moveId;
24440    }
24441
24442    private void movePackageInternal(final String packageName, final String volumeUuid,
24443            final int moveId, final int callingUid, UserHandle user)
24444                    throws PackageManagerException {
24445        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24446        final PackageManager pm = mContext.getPackageManager();
24447
24448        final boolean currentAsec;
24449        final String currentVolumeUuid;
24450        final File codeFile;
24451        final String installerPackageName;
24452        final String packageAbiOverride;
24453        final int appId;
24454        final String seinfo;
24455        final String label;
24456        final int targetSdkVersion;
24457        final PackageFreezer freezer;
24458        final int[] installedUserIds;
24459
24460        // reader
24461        synchronized (mPackages) {
24462            final PackageParser.Package pkg = mPackages.get(packageName);
24463            final PackageSetting ps = mSettings.mPackages.get(packageName);
24464            if (pkg == null
24465                    || ps == null
24466                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24467                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24468            }
24469            if (pkg.applicationInfo.isSystemApp()) {
24470                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24471                        "Cannot move system application");
24472            }
24473
24474            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24475            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24476                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24477            if (isInternalStorage && !allow3rdPartyOnInternal) {
24478                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24479                        "3rd party apps are not allowed on internal storage");
24480            }
24481
24482            if (pkg.applicationInfo.isExternalAsec()) {
24483                currentAsec = true;
24484                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24485            } else if (pkg.applicationInfo.isForwardLocked()) {
24486                currentAsec = true;
24487                currentVolumeUuid = "forward_locked";
24488            } else {
24489                currentAsec = false;
24490                currentVolumeUuid = ps.volumeUuid;
24491
24492                final File probe = new File(pkg.codePath);
24493                final File probeOat = new File(probe, "oat");
24494                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24495                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24496                            "Move only supported for modern cluster style installs");
24497                }
24498            }
24499
24500            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24501                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24502                        "Package already moved to " + volumeUuid);
24503            }
24504            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24505                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24506                        "Device admin cannot be moved");
24507            }
24508
24509            if (mFrozenPackages.contains(packageName)) {
24510                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24511                        "Failed to move already frozen package");
24512            }
24513
24514            codeFile = new File(pkg.codePath);
24515            installerPackageName = ps.installerPackageName;
24516            packageAbiOverride = ps.cpuAbiOverrideString;
24517            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24518            seinfo = pkg.applicationInfo.seInfo;
24519            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24520            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24521            freezer = freezePackage(packageName, "movePackageInternal");
24522            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24523        }
24524
24525        final Bundle extras = new Bundle();
24526        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24527        extras.putString(Intent.EXTRA_TITLE, label);
24528        mMoveCallbacks.notifyCreated(moveId, extras);
24529
24530        int installFlags;
24531        final boolean moveCompleteApp;
24532        final File measurePath;
24533
24534        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24535            installFlags = INSTALL_INTERNAL;
24536            moveCompleteApp = !currentAsec;
24537            measurePath = Environment.getDataAppDirectory(volumeUuid);
24538        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24539            installFlags = INSTALL_EXTERNAL;
24540            moveCompleteApp = false;
24541            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24542        } else {
24543            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24544            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24545                    || !volume.isMountedWritable()) {
24546                freezer.close();
24547                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24548                        "Move location not mounted private volume");
24549            }
24550
24551            Preconditions.checkState(!currentAsec);
24552
24553            installFlags = INSTALL_INTERNAL;
24554            moveCompleteApp = true;
24555            measurePath = Environment.getDataAppDirectory(volumeUuid);
24556        }
24557
24558        // If we're moving app data around, we need all the users unlocked
24559        if (moveCompleteApp) {
24560            for (int userId : installedUserIds) {
24561                if (StorageManager.isFileEncryptedNativeOrEmulated()
24562                        && !StorageManager.isUserKeyUnlocked(userId)) {
24563                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24564                            "User " + userId + " must be unlocked");
24565                }
24566            }
24567        }
24568
24569        final PackageStats stats = new PackageStats(null, -1);
24570        synchronized (mInstaller) {
24571            for (int userId : installedUserIds) {
24572                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24573                    freezer.close();
24574                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24575                            "Failed to measure package size");
24576                }
24577            }
24578        }
24579
24580        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24581                + stats.dataSize);
24582
24583        final long startFreeBytes = measurePath.getUsableSpace();
24584        final long sizeBytes;
24585        if (moveCompleteApp) {
24586            sizeBytes = stats.codeSize + stats.dataSize;
24587        } else {
24588            sizeBytes = stats.codeSize;
24589        }
24590
24591        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24592            freezer.close();
24593            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24594                    "Not enough free space to move");
24595        }
24596
24597        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24598
24599        final CountDownLatch installedLatch = new CountDownLatch(1);
24600        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24601            @Override
24602            public void onUserActionRequired(Intent intent) throws RemoteException {
24603                throw new IllegalStateException();
24604            }
24605
24606            @Override
24607            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24608                    Bundle extras) throws RemoteException {
24609                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24610                        + PackageManager.installStatusToString(returnCode, msg));
24611
24612                installedLatch.countDown();
24613                freezer.close();
24614
24615                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24616                switch (status) {
24617                    case PackageInstaller.STATUS_SUCCESS:
24618                        mMoveCallbacks.notifyStatusChanged(moveId,
24619                                PackageManager.MOVE_SUCCEEDED);
24620                        break;
24621                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24622                        mMoveCallbacks.notifyStatusChanged(moveId,
24623                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24624                        break;
24625                    default:
24626                        mMoveCallbacks.notifyStatusChanged(moveId,
24627                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24628                        break;
24629                }
24630            }
24631        };
24632
24633        final MoveInfo move;
24634        if (moveCompleteApp) {
24635            // Kick off a thread to report progress estimates
24636            new Thread() {
24637                @Override
24638                public void run() {
24639                    while (true) {
24640                        try {
24641                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24642                                break;
24643                            }
24644                        } catch (InterruptedException ignored) {
24645                        }
24646
24647                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24648                        final int progress = 10 + (int) MathUtils.constrain(
24649                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24650                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24651                    }
24652                }
24653            }.start();
24654
24655            final String dataAppName = codeFile.getName();
24656            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24657                    dataAppName, appId, seinfo, targetSdkVersion);
24658        } else {
24659            move = null;
24660        }
24661
24662        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24663
24664        final Message msg = mHandler.obtainMessage(INIT_COPY);
24665        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24666        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24667                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24668                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24669                PackageManager.INSTALL_REASON_UNKNOWN);
24670        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24671        msg.obj = params;
24672
24673        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24674                System.identityHashCode(msg.obj));
24675        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24676                System.identityHashCode(msg.obj));
24677
24678        mHandler.sendMessage(msg);
24679    }
24680
24681    @Override
24682    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24683        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24684
24685        final int realMoveId = mNextMoveId.getAndIncrement();
24686        final Bundle extras = new Bundle();
24687        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24688        mMoveCallbacks.notifyCreated(realMoveId, extras);
24689
24690        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24691            @Override
24692            public void onCreated(int moveId, Bundle extras) {
24693                // Ignored
24694            }
24695
24696            @Override
24697            public void onStatusChanged(int moveId, int status, long estMillis) {
24698                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24699            }
24700        };
24701
24702        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24703        storage.setPrimaryStorageUuid(volumeUuid, callback);
24704        return realMoveId;
24705    }
24706
24707    @Override
24708    public int getMoveStatus(int moveId) {
24709        mContext.enforceCallingOrSelfPermission(
24710                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24711        return mMoveCallbacks.mLastStatus.get(moveId);
24712    }
24713
24714    @Override
24715    public void registerMoveCallback(IPackageMoveObserver callback) {
24716        mContext.enforceCallingOrSelfPermission(
24717                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24718        mMoveCallbacks.register(callback);
24719    }
24720
24721    @Override
24722    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24723        mContext.enforceCallingOrSelfPermission(
24724                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24725        mMoveCallbacks.unregister(callback);
24726    }
24727
24728    @Override
24729    public boolean setInstallLocation(int loc) {
24730        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24731                null);
24732        if (getInstallLocation() == loc) {
24733            return true;
24734        }
24735        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24736                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24737            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24738                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24739            return true;
24740        }
24741        return false;
24742   }
24743
24744    @Override
24745    public int getInstallLocation() {
24746        // allow instant app access
24747        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24748                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24749                PackageHelper.APP_INSTALL_AUTO);
24750    }
24751
24752    /** Called by UserManagerService */
24753    void cleanUpUser(UserManagerService userManager, int userHandle) {
24754        synchronized (mPackages) {
24755            mDirtyUsers.remove(userHandle);
24756            mUserNeedsBadging.delete(userHandle);
24757            mSettings.removeUserLPw(userHandle);
24758            mPendingBroadcasts.remove(userHandle);
24759            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24760            removeUnusedPackagesLPw(userManager, userHandle);
24761        }
24762    }
24763
24764    /**
24765     * We're removing userHandle and would like to remove any downloaded packages
24766     * that are no longer in use by any other user.
24767     * @param userHandle the user being removed
24768     */
24769    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24770        final boolean DEBUG_CLEAN_APKS = false;
24771        int [] users = userManager.getUserIds();
24772        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24773        while (psit.hasNext()) {
24774            PackageSetting ps = psit.next();
24775            if (ps.pkg == null) {
24776                continue;
24777            }
24778            final String packageName = ps.pkg.packageName;
24779            // Skip over if system app
24780            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24781                continue;
24782            }
24783            if (DEBUG_CLEAN_APKS) {
24784                Slog.i(TAG, "Checking package " + packageName);
24785            }
24786            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24787            if (keep) {
24788                if (DEBUG_CLEAN_APKS) {
24789                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24790                }
24791            } else {
24792                for (int i = 0; i < users.length; i++) {
24793                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24794                        keep = true;
24795                        if (DEBUG_CLEAN_APKS) {
24796                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24797                                    + users[i]);
24798                        }
24799                        break;
24800                    }
24801                }
24802            }
24803            if (!keep) {
24804                if (DEBUG_CLEAN_APKS) {
24805                    Slog.i(TAG, "  Removing package " + packageName);
24806                }
24807                mHandler.post(new Runnable() {
24808                    public void run() {
24809                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24810                                userHandle, 0);
24811                    } //end run
24812                });
24813            }
24814        }
24815    }
24816
24817    /** Called by UserManagerService */
24818    void createNewUser(int userId, String[] disallowedPackages) {
24819        synchronized (mInstallLock) {
24820            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24821        }
24822        synchronized (mPackages) {
24823            scheduleWritePackageRestrictionsLocked(userId);
24824            scheduleWritePackageListLocked(userId);
24825            applyFactoryDefaultBrowserLPw(userId);
24826            primeDomainVerificationsLPw(userId);
24827        }
24828    }
24829
24830    void onNewUserCreated(final int userId) {
24831        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24832        // If permission review for legacy apps is required, we represent
24833        // dagerous permissions for such apps as always granted runtime
24834        // permissions to keep per user flag state whether review is needed.
24835        // Hence, if a new user is added we have to propagate dangerous
24836        // permission grants for these legacy apps.
24837        if (mPermissionReviewRequired) {
24838            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24839                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24840        }
24841    }
24842
24843    @Override
24844    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24845        mContext.enforceCallingOrSelfPermission(
24846                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24847                "Only package verification agents can read the verifier device identity");
24848
24849        synchronized (mPackages) {
24850            return mSettings.getVerifierDeviceIdentityLPw();
24851        }
24852    }
24853
24854    @Override
24855    public void setPermissionEnforced(String permission, boolean enforced) {
24856        // TODO: Now that we no longer change GID for storage, this should to away.
24857        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24858                "setPermissionEnforced");
24859        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24860            synchronized (mPackages) {
24861                if (mSettings.mReadExternalStorageEnforced == null
24862                        || mSettings.mReadExternalStorageEnforced != enforced) {
24863                    mSettings.mReadExternalStorageEnforced = enforced;
24864                    mSettings.writeLPr();
24865                }
24866            }
24867            // kill any non-foreground processes so we restart them and
24868            // grant/revoke the GID.
24869            final IActivityManager am = ActivityManager.getService();
24870            if (am != null) {
24871                final long token = Binder.clearCallingIdentity();
24872                try {
24873                    am.killProcessesBelowForeground("setPermissionEnforcement");
24874                } catch (RemoteException e) {
24875                } finally {
24876                    Binder.restoreCallingIdentity(token);
24877                }
24878            }
24879        } else {
24880            throw new IllegalArgumentException("No selective enforcement for " + permission);
24881        }
24882    }
24883
24884    @Override
24885    @Deprecated
24886    public boolean isPermissionEnforced(String permission) {
24887        // allow instant applications
24888        return true;
24889    }
24890
24891    @Override
24892    public boolean isStorageLow() {
24893        // allow instant applications
24894        final long token = Binder.clearCallingIdentity();
24895        try {
24896            final DeviceStorageMonitorInternal
24897                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24898            if (dsm != null) {
24899                return dsm.isMemoryLow();
24900            } else {
24901                return false;
24902            }
24903        } finally {
24904            Binder.restoreCallingIdentity(token);
24905        }
24906    }
24907
24908    @Override
24909    public IPackageInstaller getPackageInstaller() {
24910        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24911            return null;
24912        }
24913        return mInstallerService;
24914    }
24915
24916    @Override
24917    public IArtManager getArtManager() {
24918        return mArtManagerService;
24919    }
24920
24921    private boolean userNeedsBadging(int userId) {
24922        int index = mUserNeedsBadging.indexOfKey(userId);
24923        if (index < 0) {
24924            final UserInfo userInfo;
24925            final long token = Binder.clearCallingIdentity();
24926            try {
24927                userInfo = sUserManager.getUserInfo(userId);
24928            } finally {
24929                Binder.restoreCallingIdentity(token);
24930            }
24931            final boolean b;
24932            if (userInfo != null && userInfo.isManagedProfile()) {
24933                b = true;
24934            } else {
24935                b = false;
24936            }
24937            mUserNeedsBadging.put(userId, b);
24938            return b;
24939        }
24940        return mUserNeedsBadging.valueAt(index);
24941    }
24942
24943    @Override
24944    public KeySet getKeySetByAlias(String packageName, String alias) {
24945        if (packageName == null || alias == null) {
24946            return null;
24947        }
24948        synchronized(mPackages) {
24949            final PackageParser.Package pkg = mPackages.get(packageName);
24950            if (pkg == null) {
24951                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24952                throw new IllegalArgumentException("Unknown package: " + packageName);
24953            }
24954            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24955            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24956                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24957                throw new IllegalArgumentException("Unknown package: " + packageName);
24958            }
24959            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24960            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24961        }
24962    }
24963
24964    @Override
24965    public KeySet getSigningKeySet(String packageName) {
24966        if (packageName == null) {
24967            return null;
24968        }
24969        synchronized(mPackages) {
24970            final int callingUid = Binder.getCallingUid();
24971            final int callingUserId = UserHandle.getUserId(callingUid);
24972            final PackageParser.Package pkg = mPackages.get(packageName);
24973            if (pkg == null) {
24974                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24975                throw new IllegalArgumentException("Unknown package: " + packageName);
24976            }
24977            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24978            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24979                // filter and pretend the package doesn't exist
24980                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24981                        + ", uid:" + callingUid);
24982                throw new IllegalArgumentException("Unknown package: " + packageName);
24983            }
24984            if (pkg.applicationInfo.uid != callingUid
24985                    && Process.SYSTEM_UID != callingUid) {
24986                throw new SecurityException("May not access signing KeySet of other apps.");
24987            }
24988            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24989            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24990        }
24991    }
24992
24993    @Override
24994    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24995        final int callingUid = Binder.getCallingUid();
24996        if (getInstantAppPackageName(callingUid) != null) {
24997            return false;
24998        }
24999        if (packageName == null || ks == null) {
25000            return false;
25001        }
25002        synchronized(mPackages) {
25003            final PackageParser.Package pkg = mPackages.get(packageName);
25004            if (pkg == null
25005                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
25006                            UserHandle.getUserId(callingUid))) {
25007                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
25008                throw new IllegalArgumentException("Unknown package: " + packageName);
25009            }
25010            IBinder ksh = ks.getToken();
25011            if (ksh instanceof KeySetHandle) {
25012                KeySetManagerService ksms = mSettings.mKeySetManagerService;
25013                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
25014            }
25015            return false;
25016        }
25017    }
25018
25019    @Override
25020    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
25021        final int callingUid = Binder.getCallingUid();
25022        if (getInstantAppPackageName(callingUid) != null) {
25023            return false;
25024        }
25025        if (packageName == null || ks == null) {
25026            return false;
25027        }
25028        synchronized(mPackages) {
25029            final PackageParser.Package pkg = mPackages.get(packageName);
25030            if (pkg == null
25031                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
25032                            UserHandle.getUserId(callingUid))) {
25033                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
25034                throw new IllegalArgumentException("Unknown package: " + packageName);
25035            }
25036            IBinder ksh = ks.getToken();
25037            if (ksh instanceof KeySetHandle) {
25038                KeySetManagerService ksms = mSettings.mKeySetManagerService;
25039                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
25040            }
25041            return false;
25042        }
25043    }
25044
25045    private void deletePackageIfUnusedLPr(final String packageName) {
25046        PackageSetting ps = mSettings.mPackages.get(packageName);
25047        if (ps == null) {
25048            return;
25049        }
25050        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
25051            // TODO Implement atomic delete if package is unused
25052            // It is currently possible that the package will be deleted even if it is installed
25053            // after this method returns.
25054            mHandler.post(new Runnable() {
25055                public void run() {
25056                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
25057                            0, PackageManager.DELETE_ALL_USERS);
25058                }
25059            });
25060        }
25061    }
25062
25063    /**
25064     * Check and throw if the given before/after packages would be considered a
25065     * downgrade.
25066     */
25067    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
25068            throws PackageManagerException {
25069        if (after.versionCode < before.mVersionCode) {
25070            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25071                    "Update version code " + after.versionCode + " is older than current "
25072                    + before.mVersionCode);
25073        } else if (after.versionCode == before.mVersionCode) {
25074            if (after.baseRevisionCode < before.baseRevisionCode) {
25075                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25076                        "Update base revision code " + after.baseRevisionCode
25077                        + " is older than current " + before.baseRevisionCode);
25078            }
25079
25080            if (!ArrayUtils.isEmpty(after.splitNames)) {
25081                for (int i = 0; i < after.splitNames.length; i++) {
25082                    final String splitName = after.splitNames[i];
25083                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
25084                    if (j != -1) {
25085                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
25086                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25087                                    "Update split " + splitName + " revision code "
25088                                    + after.splitRevisionCodes[i] + " is older than current "
25089                                    + before.splitRevisionCodes[j]);
25090                        }
25091                    }
25092                }
25093            }
25094        }
25095    }
25096
25097    private static class MoveCallbacks extends Handler {
25098        private static final int MSG_CREATED = 1;
25099        private static final int MSG_STATUS_CHANGED = 2;
25100
25101        private final RemoteCallbackList<IPackageMoveObserver>
25102                mCallbacks = new RemoteCallbackList<>();
25103
25104        private final SparseIntArray mLastStatus = new SparseIntArray();
25105
25106        public MoveCallbacks(Looper looper) {
25107            super(looper);
25108        }
25109
25110        public void register(IPackageMoveObserver callback) {
25111            mCallbacks.register(callback);
25112        }
25113
25114        public void unregister(IPackageMoveObserver callback) {
25115            mCallbacks.unregister(callback);
25116        }
25117
25118        @Override
25119        public void handleMessage(Message msg) {
25120            final SomeArgs args = (SomeArgs) msg.obj;
25121            final int n = mCallbacks.beginBroadcast();
25122            for (int i = 0; i < n; i++) {
25123                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
25124                try {
25125                    invokeCallback(callback, msg.what, args);
25126                } catch (RemoteException ignored) {
25127                }
25128            }
25129            mCallbacks.finishBroadcast();
25130            args.recycle();
25131        }
25132
25133        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
25134                throws RemoteException {
25135            switch (what) {
25136                case MSG_CREATED: {
25137                    callback.onCreated(args.argi1, (Bundle) args.arg2);
25138                    break;
25139                }
25140                case MSG_STATUS_CHANGED: {
25141                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
25142                    break;
25143                }
25144            }
25145        }
25146
25147        private void notifyCreated(int moveId, Bundle extras) {
25148            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
25149
25150            final SomeArgs args = SomeArgs.obtain();
25151            args.argi1 = moveId;
25152            args.arg2 = extras;
25153            obtainMessage(MSG_CREATED, args).sendToTarget();
25154        }
25155
25156        private void notifyStatusChanged(int moveId, int status) {
25157            notifyStatusChanged(moveId, status, -1);
25158        }
25159
25160        private void notifyStatusChanged(int moveId, int status, long estMillis) {
25161            Slog.v(TAG, "Move " + moveId + " status " + status);
25162
25163            final SomeArgs args = SomeArgs.obtain();
25164            args.argi1 = moveId;
25165            args.argi2 = status;
25166            args.arg3 = estMillis;
25167            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
25168
25169            synchronized (mLastStatus) {
25170                mLastStatus.put(moveId, status);
25171            }
25172        }
25173    }
25174
25175    private final static class OnPermissionChangeListeners extends Handler {
25176        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
25177
25178        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
25179                new RemoteCallbackList<>();
25180
25181        public OnPermissionChangeListeners(Looper looper) {
25182            super(looper);
25183        }
25184
25185        @Override
25186        public void handleMessage(Message msg) {
25187            switch (msg.what) {
25188                case MSG_ON_PERMISSIONS_CHANGED: {
25189                    final int uid = msg.arg1;
25190                    handleOnPermissionsChanged(uid);
25191                } break;
25192            }
25193        }
25194
25195        public void addListenerLocked(IOnPermissionsChangeListener listener) {
25196            mPermissionListeners.register(listener);
25197
25198        }
25199
25200        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
25201            mPermissionListeners.unregister(listener);
25202        }
25203
25204        public void onPermissionsChanged(int uid) {
25205            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
25206                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
25207            }
25208        }
25209
25210        private void handleOnPermissionsChanged(int uid) {
25211            final int count = mPermissionListeners.beginBroadcast();
25212            try {
25213                for (int i = 0; i < count; i++) {
25214                    IOnPermissionsChangeListener callback = mPermissionListeners
25215                            .getBroadcastItem(i);
25216                    try {
25217                        callback.onPermissionsChanged(uid);
25218                    } catch (RemoteException e) {
25219                        Log.e(TAG, "Permission listener is dead", e);
25220                    }
25221                }
25222            } finally {
25223                mPermissionListeners.finishBroadcast();
25224            }
25225        }
25226    }
25227
25228    private class PackageManagerNative extends IPackageManagerNative.Stub {
25229        @Override
25230        public String[] getNamesForUids(int[] uids) throws RemoteException {
25231            final String[] results = PackageManagerService.this.getNamesForUids(uids);
25232            // massage results so they can be parsed by the native binder
25233            for (int i = results.length - 1; i >= 0; --i) {
25234                if (results[i] == null) {
25235                    results[i] = "";
25236                }
25237            }
25238            return results;
25239        }
25240
25241        // NB: this differentiates between preloads and sideloads
25242        @Override
25243        public String getInstallerForPackage(String packageName) throws RemoteException {
25244            final String installerName = getInstallerPackageName(packageName);
25245            if (!TextUtils.isEmpty(installerName)) {
25246                return installerName;
25247            }
25248            // differentiate between preload and sideload
25249            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
25250            ApplicationInfo appInfo = getApplicationInfo(packageName,
25251                                    /*flags*/ 0,
25252                                    /*userId*/ callingUser);
25253            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
25254                return "preload";
25255            }
25256            return "";
25257        }
25258
25259        @Override
25260        public int getVersionCodeForPackage(String packageName) throws RemoteException {
25261            try {
25262                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
25263                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
25264                if (pInfo != null) {
25265                    return pInfo.versionCode;
25266                }
25267            } catch (Exception e) {
25268            }
25269            return 0;
25270        }
25271    }
25272
25273    private class PackageManagerInternalImpl extends PackageManagerInternal {
25274        @Override
25275        public void setLocationPackagesProvider(PackagesProvider provider) {
25276            synchronized (mPackages) {
25277                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
25278            }
25279        }
25280
25281        @Override
25282        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
25283            synchronized (mPackages) {
25284                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
25285            }
25286        }
25287
25288        @Override
25289        public void setSmsAppPackagesProvider(PackagesProvider provider) {
25290            synchronized (mPackages) {
25291                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
25292            }
25293        }
25294
25295        @Override
25296        public void setDialerAppPackagesProvider(PackagesProvider provider) {
25297            synchronized (mPackages) {
25298                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
25299            }
25300        }
25301
25302        @Override
25303        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
25304            synchronized (mPackages) {
25305                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
25306            }
25307        }
25308
25309        @Override
25310        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
25311            synchronized (mPackages) {
25312                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
25313            }
25314        }
25315
25316        @Override
25317        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
25318            synchronized (mPackages) {
25319                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
25320                        packageName, userId);
25321            }
25322        }
25323
25324        @Override
25325        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
25326            synchronized (mPackages) {
25327                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
25328                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
25329                        packageName, userId);
25330            }
25331        }
25332
25333        @Override
25334        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
25335            synchronized (mPackages) {
25336                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
25337                        packageName, userId);
25338            }
25339        }
25340
25341        @Override
25342        public void setKeepUninstalledPackages(final List<String> packageList) {
25343            Preconditions.checkNotNull(packageList);
25344            List<String> removedFromList = null;
25345            synchronized (mPackages) {
25346                if (mKeepUninstalledPackages != null) {
25347                    final int packagesCount = mKeepUninstalledPackages.size();
25348                    for (int i = 0; i < packagesCount; i++) {
25349                        String oldPackage = mKeepUninstalledPackages.get(i);
25350                        if (packageList != null && packageList.contains(oldPackage)) {
25351                            continue;
25352                        }
25353                        if (removedFromList == null) {
25354                            removedFromList = new ArrayList<>();
25355                        }
25356                        removedFromList.add(oldPackage);
25357                    }
25358                }
25359                mKeepUninstalledPackages = new ArrayList<>(packageList);
25360                if (removedFromList != null) {
25361                    final int removedCount = removedFromList.size();
25362                    for (int i = 0; i < removedCount; i++) {
25363                        deletePackageIfUnusedLPr(removedFromList.get(i));
25364                    }
25365                }
25366            }
25367        }
25368
25369        @Override
25370        public boolean isPermissionsReviewRequired(String packageName, int userId) {
25371            synchronized (mPackages) {
25372                // If we do not support permission review, done.
25373                if (!mPermissionReviewRequired) {
25374                    return false;
25375                }
25376
25377                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
25378                if (packageSetting == null) {
25379                    return false;
25380                }
25381
25382                // Permission review applies only to apps not supporting the new permission model.
25383                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
25384                    return false;
25385                }
25386
25387                // Legacy apps have the permission and get user consent on launch.
25388                PermissionsState permissionsState = packageSetting.getPermissionsState();
25389                return permissionsState.isPermissionReviewRequired(userId);
25390            }
25391        }
25392
25393        @Override
25394        public PackageInfo getPackageInfo(
25395                String packageName, int flags, int filterCallingUid, int userId) {
25396            return PackageManagerService.this
25397                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
25398                            flags, filterCallingUid, userId);
25399        }
25400
25401        @Override
25402        public ApplicationInfo getApplicationInfo(
25403                String packageName, int flags, int filterCallingUid, int userId) {
25404            return PackageManagerService.this
25405                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
25406        }
25407
25408        @Override
25409        public ActivityInfo getActivityInfo(
25410                ComponentName component, int flags, int filterCallingUid, int userId) {
25411            return PackageManagerService.this
25412                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
25413        }
25414
25415        @Override
25416        public List<ResolveInfo> queryIntentActivities(
25417                Intent intent, int flags, int filterCallingUid, int userId) {
25418            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25419            return PackageManagerService.this
25420                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
25421                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
25422        }
25423
25424        @Override
25425        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
25426                int userId) {
25427            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
25428        }
25429
25430        @Override
25431        public void setDeviceAndProfileOwnerPackages(
25432                int deviceOwnerUserId, String deviceOwnerPackage,
25433                SparseArray<String> profileOwnerPackages) {
25434            mProtectedPackages.setDeviceAndProfileOwnerPackages(
25435                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
25436        }
25437
25438        @Override
25439        public boolean isPackageDataProtected(int userId, String packageName) {
25440            return mProtectedPackages.isPackageDataProtected(userId, packageName);
25441        }
25442
25443        @Override
25444        public boolean isPackageEphemeral(int userId, String packageName) {
25445            synchronized (mPackages) {
25446                final PackageSetting ps = mSettings.mPackages.get(packageName);
25447                return ps != null ? ps.getInstantApp(userId) : false;
25448            }
25449        }
25450
25451        @Override
25452        public boolean wasPackageEverLaunched(String packageName, int userId) {
25453            synchronized (mPackages) {
25454                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25455            }
25456        }
25457
25458        @Override
25459        public void grantRuntimePermission(String packageName, String name, int userId,
25460                boolean overridePolicy) {
25461            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25462                    overridePolicy);
25463        }
25464
25465        @Override
25466        public void revokeRuntimePermission(String packageName, String name, int userId,
25467                boolean overridePolicy) {
25468            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25469                    overridePolicy);
25470        }
25471
25472        @Override
25473        public String getNameForUid(int uid) {
25474            return PackageManagerService.this.getNameForUid(uid);
25475        }
25476
25477        @Override
25478        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25479                Intent origIntent, String resolvedType, String callingPackage,
25480                Bundle verificationBundle, int userId) {
25481            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25482                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25483                    userId);
25484        }
25485
25486        @Override
25487        public void grantEphemeralAccess(int userId, Intent intent,
25488                int targetAppId, int ephemeralAppId) {
25489            synchronized (mPackages) {
25490                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25491                        targetAppId, ephemeralAppId);
25492            }
25493        }
25494
25495        @Override
25496        public boolean isInstantAppInstallerComponent(ComponentName component) {
25497            synchronized (mPackages) {
25498                return mInstantAppInstallerActivity != null
25499                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25500            }
25501        }
25502
25503        @Override
25504        public void pruneInstantApps() {
25505            mInstantAppRegistry.pruneInstantApps();
25506        }
25507
25508        @Override
25509        public String getSetupWizardPackageName() {
25510            return mSetupWizardPackage;
25511        }
25512
25513        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25514            if (policy != null) {
25515                mExternalSourcesPolicy = policy;
25516            }
25517        }
25518
25519        @Override
25520        public boolean isPackagePersistent(String packageName) {
25521            synchronized (mPackages) {
25522                PackageParser.Package pkg = mPackages.get(packageName);
25523                return pkg != null
25524                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25525                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25526                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25527                        : false;
25528            }
25529        }
25530
25531        @Override
25532        public List<PackageInfo> getOverlayPackages(int userId) {
25533            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25534            synchronized (mPackages) {
25535                for (PackageParser.Package p : mPackages.values()) {
25536                    if (p.mOverlayTarget != null) {
25537                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25538                        if (pkg != null) {
25539                            overlayPackages.add(pkg);
25540                        }
25541                    }
25542                }
25543            }
25544            return overlayPackages;
25545        }
25546
25547        @Override
25548        public List<String> getTargetPackageNames(int userId) {
25549            List<String> targetPackages = new ArrayList<>();
25550            synchronized (mPackages) {
25551                for (PackageParser.Package p : mPackages.values()) {
25552                    if (p.mOverlayTarget == null) {
25553                        targetPackages.add(p.packageName);
25554                    }
25555                }
25556            }
25557            return targetPackages;
25558        }
25559
25560        @Override
25561        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25562                @Nullable List<String> overlayPackageNames) {
25563            synchronized (mPackages) {
25564                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25565                    Slog.e(TAG, "failed to find package " + targetPackageName);
25566                    return false;
25567                }
25568                ArrayList<String> overlayPaths = null;
25569                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25570                    final int N = overlayPackageNames.size();
25571                    overlayPaths = new ArrayList<>(N);
25572                    for (int i = 0; i < N; i++) {
25573                        final String packageName = overlayPackageNames.get(i);
25574                        final PackageParser.Package pkg = mPackages.get(packageName);
25575                        if (pkg == null) {
25576                            Slog.e(TAG, "failed to find package " + packageName);
25577                            return false;
25578                        }
25579                        overlayPaths.add(pkg.baseCodePath);
25580                    }
25581                }
25582
25583                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25584                ps.setOverlayPaths(overlayPaths, userId);
25585                return true;
25586            }
25587        }
25588
25589        @Override
25590        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25591                int flags, int userId) {
25592            return resolveIntentInternal(
25593                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25594        }
25595
25596        @Override
25597        public ResolveInfo resolveService(Intent intent, String resolvedType,
25598                int flags, int userId, int callingUid) {
25599            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25600        }
25601
25602        @Override
25603        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25604            synchronized (mPackages) {
25605                mIsolatedOwners.put(isolatedUid, ownerUid);
25606            }
25607        }
25608
25609        @Override
25610        public void removeIsolatedUid(int isolatedUid) {
25611            synchronized (mPackages) {
25612                mIsolatedOwners.delete(isolatedUid);
25613            }
25614        }
25615
25616        @Override
25617        public int getUidTargetSdkVersion(int uid) {
25618            synchronized (mPackages) {
25619                return getUidTargetSdkVersionLockedLPr(uid);
25620            }
25621        }
25622
25623        @Override
25624        public boolean canAccessInstantApps(int callingUid, int userId) {
25625            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25626        }
25627
25628        @Override
25629        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
25630            synchronized (mPackages) {
25631                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
25632            }
25633        }
25634
25635        @Override
25636        public void notifyPackageUse(String packageName, int reason) {
25637            synchronized (mPackages) {
25638                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
25639            }
25640        }
25641    }
25642
25643    @Override
25644    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25645        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25646        synchronized (mPackages) {
25647            final long identity = Binder.clearCallingIdentity();
25648            try {
25649                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25650                        packageNames, userId);
25651            } finally {
25652                Binder.restoreCallingIdentity(identity);
25653            }
25654        }
25655    }
25656
25657    @Override
25658    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25659        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25660        synchronized (mPackages) {
25661            final long identity = Binder.clearCallingIdentity();
25662            try {
25663                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25664                        packageNames, userId);
25665            } finally {
25666                Binder.restoreCallingIdentity(identity);
25667            }
25668        }
25669    }
25670
25671    private static void enforceSystemOrPhoneCaller(String tag) {
25672        int callingUid = Binder.getCallingUid();
25673        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25674            throw new SecurityException(
25675                    "Cannot call " + tag + " from UID " + callingUid);
25676        }
25677    }
25678
25679    boolean isHistoricalPackageUsageAvailable() {
25680        return mPackageUsage.isHistoricalPackageUsageAvailable();
25681    }
25682
25683    /**
25684     * Return a <b>copy</b> of the collection of packages known to the package manager.
25685     * @return A copy of the values of mPackages.
25686     */
25687    Collection<PackageParser.Package> getPackages() {
25688        synchronized (mPackages) {
25689            return new ArrayList<>(mPackages.values());
25690        }
25691    }
25692
25693    /**
25694     * Logs process start information (including base APK hash) to the security log.
25695     * @hide
25696     */
25697    @Override
25698    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25699            String apkFile, int pid) {
25700        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25701            return;
25702        }
25703        if (!SecurityLog.isLoggingEnabled()) {
25704            return;
25705        }
25706        Bundle data = new Bundle();
25707        data.putLong("startTimestamp", System.currentTimeMillis());
25708        data.putString("processName", processName);
25709        data.putInt("uid", uid);
25710        data.putString("seinfo", seinfo);
25711        data.putString("apkFile", apkFile);
25712        data.putInt("pid", pid);
25713        Message msg = mProcessLoggingHandler.obtainMessage(
25714                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25715        msg.setData(data);
25716        mProcessLoggingHandler.sendMessage(msg);
25717    }
25718
25719    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25720        return mCompilerStats.getPackageStats(pkgName);
25721    }
25722
25723    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25724        return getOrCreateCompilerPackageStats(pkg.packageName);
25725    }
25726
25727    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25728        return mCompilerStats.getOrCreatePackageStats(pkgName);
25729    }
25730
25731    public void deleteCompilerPackageStats(String pkgName) {
25732        mCompilerStats.deletePackageStats(pkgName);
25733    }
25734
25735    @Override
25736    public int getInstallReason(String packageName, int userId) {
25737        final int callingUid = Binder.getCallingUid();
25738        enforceCrossUserPermission(callingUid, userId,
25739                true /* requireFullPermission */, false /* checkShell */,
25740                "get install reason");
25741        synchronized (mPackages) {
25742            final PackageSetting ps = mSettings.mPackages.get(packageName);
25743            if (filterAppAccessLPr(ps, callingUid, userId)) {
25744                return PackageManager.INSTALL_REASON_UNKNOWN;
25745            }
25746            if (ps != null) {
25747                return ps.getInstallReason(userId);
25748            }
25749        }
25750        return PackageManager.INSTALL_REASON_UNKNOWN;
25751    }
25752
25753    @Override
25754    public boolean canRequestPackageInstalls(String packageName, int userId) {
25755        return canRequestPackageInstallsInternal(packageName, 0, userId,
25756                true /* throwIfPermNotDeclared*/);
25757    }
25758
25759    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25760            boolean throwIfPermNotDeclared) {
25761        int callingUid = Binder.getCallingUid();
25762        int uid = getPackageUid(packageName, 0, userId);
25763        if (callingUid != uid && callingUid != Process.ROOT_UID
25764                && callingUid != Process.SYSTEM_UID) {
25765            throw new SecurityException(
25766                    "Caller uid " + callingUid + " does not own package " + packageName);
25767        }
25768        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25769        if (info == null) {
25770            return false;
25771        }
25772        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25773            return false;
25774        }
25775        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25776        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25777        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25778            if (throwIfPermNotDeclared) {
25779                throw new SecurityException("Need to declare " + appOpPermission
25780                        + " to call this api");
25781            } else {
25782                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25783                return false;
25784            }
25785        }
25786        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25787            return false;
25788        }
25789        if (mExternalSourcesPolicy != null) {
25790            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25791            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25792                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25793            }
25794        }
25795        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25796    }
25797
25798    @Override
25799    public ComponentName getInstantAppResolverSettingsComponent() {
25800        return mInstantAppResolverSettingsComponent;
25801    }
25802
25803    @Override
25804    public ComponentName getInstantAppInstallerComponent() {
25805        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25806            return null;
25807        }
25808        return mInstantAppInstallerActivity == null
25809                ? null : mInstantAppInstallerActivity.getComponentName();
25810    }
25811
25812    @Override
25813    public String getInstantAppAndroidId(String packageName, int userId) {
25814        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25815                "getInstantAppAndroidId");
25816        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25817                true /* requireFullPermission */, false /* checkShell */,
25818                "getInstantAppAndroidId");
25819        // Make sure the target is an Instant App.
25820        if (!isInstantApp(packageName, userId)) {
25821            return null;
25822        }
25823        synchronized (mPackages) {
25824            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25825        }
25826    }
25827
25828    boolean canHaveOatDir(String packageName) {
25829        synchronized (mPackages) {
25830            PackageParser.Package p = mPackages.get(packageName);
25831            if (p == null) {
25832                return false;
25833            }
25834            return p.canHaveOatDir();
25835        }
25836    }
25837
25838    private String getOatDir(PackageParser.Package pkg) {
25839        if (!pkg.canHaveOatDir()) {
25840            return null;
25841        }
25842        File codePath = new File(pkg.codePath);
25843        if (codePath.isDirectory()) {
25844            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25845        }
25846        return null;
25847    }
25848
25849    void deleteOatArtifactsOfPackage(String packageName) {
25850        final String[] instructionSets;
25851        final List<String> codePaths;
25852        final String oatDir;
25853        final PackageParser.Package pkg;
25854        synchronized (mPackages) {
25855            pkg = mPackages.get(packageName);
25856        }
25857        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25858        codePaths = pkg.getAllCodePaths();
25859        oatDir = getOatDir(pkg);
25860
25861        for (String codePath : codePaths) {
25862            for (String isa : instructionSets) {
25863                try {
25864                    mInstaller.deleteOdex(codePath, isa, oatDir);
25865                } catch (InstallerException e) {
25866                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25867                }
25868            }
25869        }
25870    }
25871
25872    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25873        Set<String> unusedPackages = new HashSet<>();
25874        long currentTimeInMillis = System.currentTimeMillis();
25875        synchronized (mPackages) {
25876            for (PackageParser.Package pkg : mPackages.values()) {
25877                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25878                if (ps == null) {
25879                    continue;
25880                }
25881                PackageDexUsage.PackageUseInfo packageUseInfo =
25882                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25883                if (PackageManagerServiceUtils
25884                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25885                                downgradeTimeThresholdMillis, packageUseInfo,
25886                                pkg.getLatestPackageUseTimeInMills(),
25887                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25888                    unusedPackages.add(pkg.packageName);
25889                }
25890            }
25891        }
25892        return unusedPackages;
25893    }
25894}
25895
25896interface PackageSender {
25897    void sendPackageBroadcast(final String action, final String pkg,
25898        final Bundle extras, final int flags, final String targetPkg,
25899        final IIntentReceiver finishedReceiver, final int[] userIds);
25900    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25901        boolean includeStopped, int appId, int... userIds);
25902}
25903