PackageManagerService.java revision dcf4c6dc2629bef9e05fbc27f034304abd653d10
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 static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
110
111import android.Manifest;
112import android.annotation.IntDef;
113import android.annotation.NonNull;
114import android.annotation.Nullable;
115import android.app.ActivityManager;
116import android.app.AppOpsManager;
117import android.app.IActivityManager;
118import android.app.ResourcesManager;
119import android.app.admin.IDevicePolicyManager;
120import android.app.admin.SecurityLog;
121import android.app.backup.IBackupManager;
122import android.content.BroadcastReceiver;
123import android.content.ComponentName;
124import android.content.ContentResolver;
125import android.content.Context;
126import android.content.IIntentReceiver;
127import android.content.Intent;
128import android.content.IntentFilter;
129import android.content.IntentSender;
130import android.content.IntentSender.SendIntentException;
131import android.content.ServiceConnection;
132import android.content.pm.ActivityInfo;
133import android.content.pm.ApplicationInfo;
134import android.content.pm.AppsQueryHelper;
135import android.content.pm.AuxiliaryResolveInfo;
136import android.content.pm.ChangedPackages;
137import android.content.pm.ComponentInfo;
138import android.content.pm.FallbackCategoryProvider;
139import android.content.pm.FeatureInfo;
140import android.content.pm.IDexModuleRegisterCallback;
141import android.content.pm.IOnPermissionsChangeListener;
142import android.content.pm.IPackageDataObserver;
143import android.content.pm.IPackageDeleteObserver;
144import android.content.pm.IPackageDeleteObserver2;
145import android.content.pm.IPackageInstallObserver2;
146import android.content.pm.IPackageInstaller;
147import android.content.pm.IPackageManager;
148import android.content.pm.IPackageManagerNative;
149import android.content.pm.IPackageMoveObserver;
150import android.content.pm.IPackageStatsObserver;
151import android.content.pm.InstantAppInfo;
152import android.content.pm.InstantAppRequest;
153import android.content.pm.InstantAppResolveInfo;
154import android.content.pm.InstrumentationInfo;
155import android.content.pm.IntentFilterVerificationInfo;
156import android.content.pm.KeySet;
157import android.content.pm.PackageCleanItem;
158import android.content.pm.PackageInfo;
159import android.content.pm.PackageInfoLite;
160import android.content.pm.PackageInstaller;
161import android.content.pm.PackageManager;
162import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
163import android.content.pm.PackageManagerInternal;
164import android.content.pm.PackageParser;
165import android.content.pm.PackageParser.ActivityIntentInfo;
166import android.content.pm.PackageParser.PackageLite;
167import android.content.pm.PackageParser.PackageParserException;
168import android.content.pm.PackageStats;
169import android.content.pm.PackageUserState;
170import android.content.pm.ParceledListSlice;
171import android.content.pm.PermissionGroupInfo;
172import android.content.pm.PermissionInfo;
173import android.content.pm.ProviderInfo;
174import android.content.pm.ResolveInfo;
175import android.content.pm.ServiceInfo;
176import android.content.pm.SharedLibraryInfo;
177import android.content.pm.Signature;
178import android.content.pm.UserInfo;
179import android.content.pm.VerifierDeviceIdentity;
180import android.content.pm.VerifierInfo;
181import android.content.pm.VersionedPackage;
182import android.content.res.Resources;
183import android.database.ContentObserver;
184import android.graphics.Bitmap;
185import android.hardware.display.DisplayManager;
186import android.net.Uri;
187import android.os.Binder;
188import android.os.Build;
189import android.os.Bundle;
190import android.os.Debug;
191import android.os.Environment;
192import android.os.Environment.UserEnvironment;
193import android.os.FileUtils;
194import android.os.Handler;
195import android.os.IBinder;
196import android.os.Looper;
197import android.os.Message;
198import android.os.Parcel;
199import android.os.ParcelFileDescriptor;
200import android.os.PatternMatcher;
201import android.os.Process;
202import android.os.RemoteCallbackList;
203import android.os.RemoteException;
204import android.os.ResultReceiver;
205import android.os.SELinux;
206import android.os.ServiceManager;
207import android.os.ShellCallback;
208import android.os.SystemClock;
209import android.os.SystemProperties;
210import android.os.Trace;
211import android.os.UserHandle;
212import android.os.UserManager;
213import android.os.UserManagerInternal;
214import android.os.storage.IStorageManager;
215import android.os.storage.StorageEventListener;
216import android.os.storage.StorageManager;
217import android.os.storage.StorageManagerInternal;
218import android.os.storage.VolumeInfo;
219import android.os.storage.VolumeRecord;
220import android.provider.Settings.Global;
221import android.provider.Settings.Secure;
222import android.security.KeyStore;
223import android.security.SystemKeyStore;
224import android.service.pm.PackageServiceDumpProto;
225import android.system.ErrnoException;
226import android.system.Os;
227import android.text.TextUtils;
228import android.text.format.DateUtils;
229import android.util.ArrayMap;
230import android.util.ArraySet;
231import android.util.Base64;
232import android.util.TimingsTraceLog;
233import android.util.DisplayMetrics;
234import android.util.EventLog;
235import android.util.ExceptionUtils;
236import android.util.Log;
237import android.util.LogPrinter;
238import android.util.MathUtils;
239import android.util.PackageUtils;
240import android.util.Pair;
241import android.util.PrintStreamPrinter;
242import android.util.Slog;
243import android.util.SparseArray;
244import android.util.SparseBooleanArray;
245import android.util.SparseIntArray;
246import android.util.Xml;
247import android.util.jar.StrictJarFile;
248import android.util.proto.ProtoOutputStream;
249import android.view.Display;
250
251import com.android.internal.R;
252import com.android.internal.annotations.GuardedBy;
253import com.android.internal.app.IMediaContainerService;
254import com.android.internal.app.ResolverActivity;
255import com.android.internal.content.NativeLibraryHelper;
256import com.android.internal.content.PackageHelper;
257import com.android.internal.logging.MetricsLogger;
258import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
259import com.android.internal.os.IParcelFileDescriptorFactory;
260import com.android.internal.os.RoSystemProperties;
261import com.android.internal.os.SomeArgs;
262import com.android.internal.os.Zygote;
263import com.android.internal.telephony.CarrierAppUtils;
264import com.android.internal.util.ArrayUtils;
265import com.android.internal.util.ConcurrentUtils;
266import com.android.internal.util.DumpUtils;
267import com.android.internal.util.FastPrintWriter;
268import com.android.internal.util.FastXmlSerializer;
269import com.android.internal.util.IndentingPrintWriter;
270import com.android.internal.util.Preconditions;
271import com.android.internal.util.XmlUtils;
272import com.android.server.AttributeCache;
273import com.android.server.DeviceIdleController;
274import com.android.server.EventLogTags;
275import com.android.server.FgThread;
276import com.android.server.IntentResolver;
277import com.android.server.LocalServices;
278import com.android.server.LockGuard;
279import com.android.server.ServiceThread;
280import com.android.server.SystemConfig;
281import com.android.server.SystemServerInitThreadPool;
282import com.android.server.Watchdog;
283import com.android.server.net.NetworkPolicyManagerInternal;
284import com.android.server.pm.Installer.InstallerException;
285import com.android.server.pm.PermissionsState.PermissionState;
286import com.android.server.pm.Settings.DatabaseVersion;
287import com.android.server.pm.Settings.VersionInfo;
288import com.android.server.pm.dex.DexManager;
289import com.android.server.pm.dex.DexoptOptions;
290import com.android.server.pm.dex.PackageDexUsage;
291import com.android.server.storage.DeviceStorageMonitorInternal;
292
293import dalvik.system.CloseGuard;
294import dalvik.system.DexFile;
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
616
617    /**
618     * Version number for the package parser cache. Increment this whenever the format or
619     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
620     */
621    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
622
623    /**
624     * Whether the package parser cache is enabled.
625     */
626    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
627
628    final ServiceThread mHandlerThread;
629
630    final PackageHandler mHandler;
631
632    private final ProcessLoggingHandler mProcessLoggingHandler;
633
634    /**
635     * Messages for {@link #mHandler} that need to wait for system ready before
636     * being dispatched.
637     */
638    private ArrayList<Message> mPostSystemReadyMessages;
639
640    final int mSdkVersion = Build.VERSION.SDK_INT;
641
642    final Context mContext;
643    final boolean mFactoryTest;
644    final boolean mOnlyCore;
645    final DisplayMetrics mMetrics;
646    final int mDefParseFlags;
647    final String[] mSeparateProcesses;
648    final boolean mIsUpgrade;
649    final boolean mIsPreNUpgrade;
650    final boolean mIsPreNMR1Upgrade;
651
652    // Have we told the Activity Manager to whitelist the default container service by uid yet?
653    @GuardedBy("mPackages")
654    boolean mDefaultContainerWhitelisted = false;
655
656    @GuardedBy("mPackages")
657    private boolean mDexOptDialogShown;
658
659    /** The location for ASEC container files on internal storage. */
660    final String mAsecInternalPath;
661
662    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
663    // LOCK HELD.  Can be called with mInstallLock held.
664    @GuardedBy("mInstallLock")
665    final Installer mInstaller;
666
667    /** Directory where installed third-party apps stored */
668    final File mAppInstallDir;
669
670    /**
671     * Directory to which applications installed internally have their
672     * 32 bit native libraries copied.
673     */
674    private File mAppLib32InstallDir;
675
676    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
677    // apps.
678    final File mDrmAppPrivateInstallDir;
679
680    // ----------------------------------------------------------------
681
682    // Lock for state used when installing and doing other long running
683    // operations.  Methods that must be called with this lock held have
684    // the suffix "LI".
685    final Object mInstallLock = new Object();
686
687    // ----------------------------------------------------------------
688
689    // Keys are String (package name), values are Package.  This also serves
690    // as the lock for the global state.  Methods that must be called with
691    // this lock held have the prefix "LP".
692    @GuardedBy("mPackages")
693    final ArrayMap<String, PackageParser.Package> mPackages =
694            new ArrayMap<String, PackageParser.Package>();
695
696    final ArrayMap<String, Set<String>> mKnownCodebase =
697            new ArrayMap<String, Set<String>>();
698
699    // Keys are isolated uids and values are the uid of the application
700    // that created the isolated proccess.
701    @GuardedBy("mPackages")
702    final SparseIntArray mIsolatedOwners = new SparseIntArray();
703
704    /**
705     * Tracks new system packages [received in an OTA] that we expect to
706     * find updated user-installed versions. Keys are package name, values
707     * are package location.
708     */
709    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
710    /**
711     * Tracks high priority intent filters for protected actions. During boot, certain
712     * filter actions are protected and should never be allowed to have a high priority
713     * intent filter for them. However, there is one, and only one exception -- the
714     * setup wizard. It must be able to define a high priority intent filter for these
715     * actions to ensure there are no escapes from the wizard. We need to delay processing
716     * of these during boot as we need to look at all of the system packages in order
717     * to know which component is the setup wizard.
718     */
719    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
720    /**
721     * Whether or not processing protected filters should be deferred.
722     */
723    private boolean mDeferProtectedFilters = true;
724
725    /**
726     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
727     */
728    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
729    /**
730     * Whether or not system app permissions should be promoted from install to runtime.
731     */
732    boolean mPromoteSystemApps;
733
734    @GuardedBy("mPackages")
735    final Settings mSettings;
736
737    /**
738     * Set of package names that are currently "frozen", which means active
739     * surgery is being done on the code/data for that package. The platform
740     * will refuse to launch frozen packages to avoid race conditions.
741     *
742     * @see PackageFreezer
743     */
744    @GuardedBy("mPackages")
745    final ArraySet<String> mFrozenPackages = new ArraySet<>();
746
747    final ProtectedPackages mProtectedPackages;
748
749    @GuardedBy("mLoadedVolumes")
750    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
751
752    boolean mFirstBoot;
753
754    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
755
756    // System configuration read by SystemConfig.
757    final int[] mGlobalGids;
758    final SparseArray<ArraySet<String>> mSystemPermissions;
759    @GuardedBy("mAvailableFeatures")
760    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
761
762    // If mac_permissions.xml was found for seinfo labeling.
763    boolean mFoundPolicyFile;
764
765    private final InstantAppRegistry mInstantAppRegistry;
766
767    @GuardedBy("mPackages")
768    int mChangedPackagesSequenceNumber;
769    /**
770     * List of changed [installed, removed or updated] packages.
771     * mapping from user id -> sequence number -> package name
772     */
773    @GuardedBy("mPackages")
774    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
775    /**
776     * The sequence number of the last change to a package.
777     * mapping from user id -> package name -> sequence number
778     */
779    @GuardedBy("mPackages")
780    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
781
782    class PackageParserCallback implements PackageParser.Callback {
783        @Override public final boolean hasFeature(String feature) {
784            return PackageManagerService.this.hasSystemFeature(feature, 0);
785        }
786
787        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
788                Collection<PackageParser.Package> allPackages, String targetPackageName) {
789            List<PackageParser.Package> overlayPackages = null;
790            for (PackageParser.Package p : allPackages) {
791                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
792                    if (overlayPackages == null) {
793                        overlayPackages = new ArrayList<PackageParser.Package>();
794                    }
795                    overlayPackages.add(p);
796                }
797            }
798            if (overlayPackages != null) {
799                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
800                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
801                        return p1.mOverlayPriority - p2.mOverlayPriority;
802                    }
803                };
804                Collections.sort(overlayPackages, cmp);
805            }
806            return overlayPackages;
807        }
808
809        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
810                String targetPackageName, String targetPath) {
811            if ("android".equals(targetPackageName)) {
812                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
813                // native AssetManager.
814                return null;
815            }
816            List<PackageParser.Package> overlayPackages =
817                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
818            if (overlayPackages == null || overlayPackages.isEmpty()) {
819                return null;
820            }
821            List<String> overlayPathList = null;
822            for (PackageParser.Package overlayPackage : overlayPackages) {
823                if (targetPath == null) {
824                    if (overlayPathList == null) {
825                        overlayPathList = new ArrayList<String>();
826                    }
827                    overlayPathList.add(overlayPackage.baseCodePath);
828                    continue;
829                }
830
831                try {
832                    // Creates idmaps for system to parse correctly the Android manifest of the
833                    // target package.
834                    //
835                    // OverlayManagerService will update each of them with a correct gid from its
836                    // target package app id.
837                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
838                            UserHandle.getSharedAppGid(
839                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
840                    if (overlayPathList == null) {
841                        overlayPathList = new ArrayList<String>();
842                    }
843                    overlayPathList.add(overlayPackage.baseCodePath);
844                } catch (InstallerException e) {
845                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
846                            overlayPackage.baseCodePath);
847                }
848            }
849            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
850        }
851
852        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
853            synchronized (mPackages) {
854                return getStaticOverlayPathsLocked(
855                        mPackages.values(), targetPackageName, targetPath);
856            }
857        }
858
859        @Override public final String[] getOverlayApks(String targetPackageName) {
860            return getStaticOverlayPaths(targetPackageName, null);
861        }
862
863        @Override public final String[] getOverlayPaths(String targetPackageName,
864                String targetPath) {
865            return getStaticOverlayPaths(targetPackageName, targetPath);
866        }
867    };
868
869    class ParallelPackageParserCallback extends PackageParserCallback {
870        List<PackageParser.Package> mOverlayPackages = null;
871
872        void findStaticOverlayPackages() {
873            synchronized (mPackages) {
874                for (PackageParser.Package p : mPackages.values()) {
875                    if (p.mIsStaticOverlay) {
876                        if (mOverlayPackages == null) {
877                            mOverlayPackages = new ArrayList<PackageParser.Package>();
878                        }
879                        mOverlayPackages.add(p);
880                    }
881                }
882            }
883        }
884
885        @Override
886        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
887            // We can trust mOverlayPackages without holding mPackages because package uninstall
888            // can't happen while running parallel parsing.
889            // Moreover holding mPackages on each parsing thread causes dead-lock.
890            return mOverlayPackages == null ? null :
891                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
892        }
893    }
894
895    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
896    final ParallelPackageParserCallback mParallelPackageParserCallback =
897            new ParallelPackageParserCallback();
898
899    public static final class SharedLibraryEntry {
900        public final @Nullable String path;
901        public final @Nullable String apk;
902        public final @NonNull SharedLibraryInfo info;
903
904        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
905                String declaringPackageName, int declaringPackageVersionCode) {
906            path = _path;
907            apk = _apk;
908            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
909                    declaringPackageName, declaringPackageVersionCode), null);
910        }
911    }
912
913    // Currently known shared libraries.
914    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
915    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
916            new ArrayMap<>();
917
918    // All available activities, for your resolving pleasure.
919    final ActivityIntentResolver mActivities =
920            new ActivityIntentResolver();
921
922    // All available receivers, for your resolving pleasure.
923    final ActivityIntentResolver mReceivers =
924            new ActivityIntentResolver();
925
926    // All available services, for your resolving pleasure.
927    final ServiceIntentResolver mServices = new ServiceIntentResolver();
928
929    // All available providers, for your resolving pleasure.
930    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
931
932    // Mapping from provider base names (first directory in content URI codePath)
933    // to the provider information.
934    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
935            new ArrayMap<String, PackageParser.Provider>();
936
937    // Mapping from instrumentation class names to info about them.
938    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
939            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
940
941    // Mapping from permission names to info about them.
942    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
943            new ArrayMap<String, PackageParser.PermissionGroup>();
944
945    // Packages whose data we have transfered into another package, thus
946    // should no longer exist.
947    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
948
949    // Broadcast actions that are only available to the system.
950    @GuardedBy("mProtectedBroadcasts")
951    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
952
953    /** List of packages waiting for verification. */
954    final SparseArray<PackageVerificationState> mPendingVerification
955            = new SparseArray<PackageVerificationState>();
956
957    /** Set of packages associated with each app op permission. */
958    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
959
960    final PackageInstallerService mInstallerService;
961
962    private final PackageDexOptimizer mPackageDexOptimizer;
963    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
964    // is used by other apps).
965    private final DexManager mDexManager;
966
967    private AtomicInteger mNextMoveId = new AtomicInteger();
968    private final MoveCallbacks mMoveCallbacks;
969
970    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
971
972    // Cache of users who need badging.
973    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
974
975    /** Token for keys in mPendingVerification. */
976    private int mPendingVerificationToken = 0;
977
978    volatile boolean mSystemReady;
979    volatile boolean mSafeMode;
980    volatile boolean mHasSystemUidErrors;
981    private volatile boolean mEphemeralAppsDisabled;
982
983    ApplicationInfo mAndroidApplication;
984    final ActivityInfo mResolveActivity = new ActivityInfo();
985    final ResolveInfo mResolveInfo = new ResolveInfo();
986    ComponentName mResolveComponentName;
987    PackageParser.Package mPlatformPackage;
988    ComponentName mCustomResolverComponentName;
989
990    boolean mResolverReplaced = false;
991
992    private final @Nullable ComponentName mIntentFilterVerifierComponent;
993    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
994
995    private int mIntentFilterVerificationToken = 0;
996
997    /** The service connection to the ephemeral resolver */
998    final EphemeralResolverConnection mInstantAppResolverConnection;
999    /** Component used to show resolver settings for Instant Apps */
1000    final ComponentName mInstantAppResolverSettingsComponent;
1001
1002    /** Activity used to install instant applications */
1003    ActivityInfo mInstantAppInstallerActivity;
1004    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1005
1006    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1007            = new SparseArray<IntentFilterVerificationState>();
1008
1009    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1010
1011    // List of packages names to keep cached, even if they are uninstalled for all users
1012    private List<String> mKeepUninstalledPackages;
1013
1014    private UserManagerInternal mUserManagerInternal;
1015
1016    private DeviceIdleController.LocalService mDeviceIdleController;
1017
1018    private File mCacheDir;
1019
1020    private ArraySet<String> mPrivappPermissionsViolations;
1021
1022    private Future<?> mPrepareAppDataFuture;
1023
1024    private static class IFVerificationParams {
1025        PackageParser.Package pkg;
1026        boolean replacing;
1027        int userId;
1028        int verifierUid;
1029
1030        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1031                int _userId, int _verifierUid) {
1032            pkg = _pkg;
1033            replacing = _replacing;
1034            userId = _userId;
1035            replacing = _replacing;
1036            verifierUid = _verifierUid;
1037        }
1038    }
1039
1040    private interface IntentFilterVerifier<T extends IntentFilter> {
1041        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1042                                               T filter, String packageName);
1043        void startVerifications(int userId);
1044        void receiveVerificationResponse(int verificationId);
1045    }
1046
1047    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1048        private Context mContext;
1049        private ComponentName mIntentFilterVerifierComponent;
1050        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1051
1052        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1053            mContext = context;
1054            mIntentFilterVerifierComponent = verifierComponent;
1055        }
1056
1057        private String getDefaultScheme() {
1058            return IntentFilter.SCHEME_HTTPS;
1059        }
1060
1061        @Override
1062        public void startVerifications(int userId) {
1063            // Launch verifications requests
1064            int count = mCurrentIntentFilterVerifications.size();
1065            for (int n=0; n<count; n++) {
1066                int verificationId = mCurrentIntentFilterVerifications.get(n);
1067                final IntentFilterVerificationState ivs =
1068                        mIntentFilterVerificationStates.get(verificationId);
1069
1070                String packageName = ivs.getPackageName();
1071
1072                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1073                final int filterCount = filters.size();
1074                ArraySet<String> domainsSet = new ArraySet<>();
1075                for (int m=0; m<filterCount; m++) {
1076                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1077                    domainsSet.addAll(filter.getHostsList());
1078                }
1079                synchronized (mPackages) {
1080                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1081                            packageName, domainsSet) != null) {
1082                        scheduleWriteSettingsLocked();
1083                    }
1084                }
1085                sendVerificationRequest(verificationId, ivs);
1086            }
1087            mCurrentIntentFilterVerifications.clear();
1088        }
1089
1090        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1091            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1092            verificationIntent.putExtra(
1093                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1094                    verificationId);
1095            verificationIntent.putExtra(
1096                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1097                    getDefaultScheme());
1098            verificationIntent.putExtra(
1099                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1100                    ivs.getHostsString());
1101            verificationIntent.putExtra(
1102                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1103                    ivs.getPackageName());
1104            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1105            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1106
1107            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1108            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1109                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1110                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1111
1112            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1113            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1114                    "Sending IntentFilter verification broadcast");
1115        }
1116
1117        public void receiveVerificationResponse(int verificationId) {
1118            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1119
1120            final boolean verified = ivs.isVerified();
1121
1122            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1123            final int count = filters.size();
1124            if (DEBUG_DOMAIN_VERIFICATION) {
1125                Slog.i(TAG, "Received verification response " + verificationId
1126                        + " for " + count + " filters, verified=" + verified);
1127            }
1128            for (int n=0; n<count; n++) {
1129                PackageParser.ActivityIntentInfo filter = filters.get(n);
1130                filter.setVerified(verified);
1131
1132                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1133                        + " verified with result:" + verified + " and hosts:"
1134                        + ivs.getHostsString());
1135            }
1136
1137            mIntentFilterVerificationStates.remove(verificationId);
1138
1139            final String packageName = ivs.getPackageName();
1140            IntentFilterVerificationInfo ivi = null;
1141
1142            synchronized (mPackages) {
1143                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1144            }
1145            if (ivi == null) {
1146                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1147                        + verificationId + " packageName:" + packageName);
1148                return;
1149            }
1150            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1151                    "Updating IntentFilterVerificationInfo for package " + packageName
1152                            +" verificationId:" + verificationId);
1153
1154            synchronized (mPackages) {
1155                if (verified) {
1156                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1157                } else {
1158                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1159                }
1160                scheduleWriteSettingsLocked();
1161
1162                final int userId = ivs.getUserId();
1163                if (userId != UserHandle.USER_ALL) {
1164                    final int userStatus =
1165                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1166
1167                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1168                    boolean needUpdate = false;
1169
1170                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1171                    // already been set by the User thru the Disambiguation dialog
1172                    switch (userStatus) {
1173                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1174                            if (verified) {
1175                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1176                            } else {
1177                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1178                            }
1179                            needUpdate = true;
1180                            break;
1181
1182                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1183                            if (verified) {
1184                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1185                                needUpdate = true;
1186                            }
1187                            break;
1188
1189                        default:
1190                            // Nothing to do
1191                    }
1192
1193                    if (needUpdate) {
1194                        mSettings.updateIntentFilterVerificationStatusLPw(
1195                                packageName, updatedStatus, userId);
1196                        scheduleWritePackageRestrictionsLocked(userId);
1197                    }
1198                }
1199            }
1200        }
1201
1202        @Override
1203        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1204                    ActivityIntentInfo filter, String packageName) {
1205            if (!hasValidDomains(filter)) {
1206                return false;
1207            }
1208            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1209            if (ivs == null) {
1210                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1211                        packageName);
1212            }
1213            if (DEBUG_DOMAIN_VERIFICATION) {
1214                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1215            }
1216            ivs.addFilter(filter);
1217            return true;
1218        }
1219
1220        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1221                int userId, int verificationId, String packageName) {
1222            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1223                    verifierUid, userId, packageName);
1224            ivs.setPendingState();
1225            synchronized (mPackages) {
1226                mIntentFilterVerificationStates.append(verificationId, ivs);
1227                mCurrentIntentFilterVerifications.add(verificationId);
1228            }
1229            return ivs;
1230        }
1231    }
1232
1233    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1234        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1235                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1236                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1237    }
1238
1239    // Set of pending broadcasts for aggregating enable/disable of components.
1240    static class PendingPackageBroadcasts {
1241        // for each user id, a map of <package name -> components within that package>
1242        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1243
1244        public PendingPackageBroadcasts() {
1245            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1246        }
1247
1248        public ArrayList<String> get(int userId, String packageName) {
1249            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1250            return packages.get(packageName);
1251        }
1252
1253        public void put(int userId, String packageName, ArrayList<String> components) {
1254            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1255            packages.put(packageName, components);
1256        }
1257
1258        public void remove(int userId, String packageName) {
1259            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1260            if (packages != null) {
1261                packages.remove(packageName);
1262            }
1263        }
1264
1265        public void remove(int userId) {
1266            mUidMap.remove(userId);
1267        }
1268
1269        public int userIdCount() {
1270            return mUidMap.size();
1271        }
1272
1273        public int userIdAt(int n) {
1274            return mUidMap.keyAt(n);
1275        }
1276
1277        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1278            return mUidMap.get(userId);
1279        }
1280
1281        public int size() {
1282            // total number of pending broadcast entries across all userIds
1283            int num = 0;
1284            for (int i = 0; i< mUidMap.size(); i++) {
1285                num += mUidMap.valueAt(i).size();
1286            }
1287            return num;
1288        }
1289
1290        public void clear() {
1291            mUidMap.clear();
1292        }
1293
1294        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1295            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1296            if (map == null) {
1297                map = new ArrayMap<String, ArrayList<String>>();
1298                mUidMap.put(userId, map);
1299            }
1300            return map;
1301        }
1302    }
1303    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1304
1305    // Service Connection to remote media container service to copy
1306    // package uri's from external media onto secure containers
1307    // or internal storage.
1308    private IMediaContainerService mContainerService = null;
1309
1310    static final int SEND_PENDING_BROADCAST = 1;
1311    static final int MCS_BOUND = 3;
1312    static final int END_COPY = 4;
1313    static final int INIT_COPY = 5;
1314    static final int MCS_UNBIND = 6;
1315    static final int START_CLEANING_PACKAGE = 7;
1316    static final int FIND_INSTALL_LOC = 8;
1317    static final int POST_INSTALL = 9;
1318    static final int MCS_RECONNECT = 10;
1319    static final int MCS_GIVE_UP = 11;
1320    static final int UPDATED_MEDIA_STATUS = 12;
1321    static final int WRITE_SETTINGS = 13;
1322    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1323    static final int PACKAGE_VERIFIED = 15;
1324    static final int CHECK_PENDING_VERIFICATION = 16;
1325    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1326    static final int INTENT_FILTER_VERIFIED = 18;
1327    static final int WRITE_PACKAGE_LIST = 19;
1328    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1329
1330    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1331
1332    // Delay time in millisecs
1333    static final int BROADCAST_DELAY = 10 * 1000;
1334
1335    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1336            2 * 60 * 60 * 1000L; /* two hours */
1337
1338    static UserManagerService sUserManager;
1339
1340    // Stores a list of users whose package restrictions file needs to be updated
1341    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1342
1343    final private DefaultContainerConnection mDefContainerConn =
1344            new DefaultContainerConnection();
1345    class DefaultContainerConnection implements ServiceConnection {
1346        public void onServiceConnected(ComponentName name, IBinder service) {
1347            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1348            final IMediaContainerService imcs = IMediaContainerService.Stub
1349                    .asInterface(Binder.allowBlocking(service));
1350            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1351        }
1352
1353        public void onServiceDisconnected(ComponentName name) {
1354            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1355        }
1356    }
1357
1358    // Recordkeeping of restore-after-install operations that are currently in flight
1359    // between the Package Manager and the Backup Manager
1360    static class PostInstallData {
1361        public InstallArgs args;
1362        public PackageInstalledInfo res;
1363
1364        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1365            args = _a;
1366            res = _r;
1367        }
1368    }
1369
1370    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1371    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1372
1373    // XML tags for backup/restore of various bits of state
1374    private static final String TAG_PREFERRED_BACKUP = "pa";
1375    private static final String TAG_DEFAULT_APPS = "da";
1376    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1377
1378    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1379    private static final String TAG_ALL_GRANTS = "rt-grants";
1380    private static final String TAG_GRANT = "grant";
1381    private static final String ATTR_PACKAGE_NAME = "pkg";
1382
1383    private static final String TAG_PERMISSION = "perm";
1384    private static final String ATTR_PERMISSION_NAME = "name";
1385    private static final String ATTR_IS_GRANTED = "g";
1386    private static final String ATTR_USER_SET = "set";
1387    private static final String ATTR_USER_FIXED = "fixed";
1388    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1389
1390    // System/policy permission grants are not backed up
1391    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1392            FLAG_PERMISSION_POLICY_FIXED
1393            | FLAG_PERMISSION_SYSTEM_FIXED
1394            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1395
1396    // And we back up these user-adjusted states
1397    private static final int USER_RUNTIME_GRANT_MASK =
1398            FLAG_PERMISSION_USER_SET
1399            | FLAG_PERMISSION_USER_FIXED
1400            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1401
1402    final @Nullable String mRequiredVerifierPackage;
1403    final @NonNull String mRequiredInstallerPackage;
1404    final @NonNull String mRequiredUninstallerPackage;
1405    final @Nullable String mSetupWizardPackage;
1406    final @Nullable String mStorageManagerPackage;
1407    final @NonNull String mServicesSystemSharedLibraryPackageName;
1408    final @NonNull String mSharedSystemSharedLibraryPackageName;
1409
1410    final boolean mPermissionReviewRequired;
1411
1412    private final PackageUsage mPackageUsage = new PackageUsage();
1413    private final CompilerStats mCompilerStats = new CompilerStats();
1414
1415    class PackageHandler extends Handler {
1416        private boolean mBound = false;
1417        final ArrayList<HandlerParams> mPendingInstalls =
1418            new ArrayList<HandlerParams>();
1419
1420        private boolean connectToService() {
1421            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1422                    " DefaultContainerService");
1423            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1424            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1425            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1426                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1427                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1428                mBound = true;
1429                return true;
1430            }
1431            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1432            return false;
1433        }
1434
1435        private void disconnectService() {
1436            mContainerService = null;
1437            mBound = false;
1438            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1439            mContext.unbindService(mDefContainerConn);
1440            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1441        }
1442
1443        PackageHandler(Looper looper) {
1444            super(looper);
1445        }
1446
1447        public void handleMessage(Message msg) {
1448            try {
1449                doHandleMessage(msg);
1450            } finally {
1451                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1452            }
1453        }
1454
1455        void doHandleMessage(Message msg) {
1456            switch (msg.what) {
1457                case INIT_COPY: {
1458                    HandlerParams params = (HandlerParams) msg.obj;
1459                    int idx = mPendingInstalls.size();
1460                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1461                    // If a bind was already initiated we dont really
1462                    // need to do anything. The pending install
1463                    // will be processed later on.
1464                    if (!mBound) {
1465                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1466                                System.identityHashCode(mHandler));
1467                        // If this is the only one pending we might
1468                        // have to bind to the service again.
1469                        if (!connectToService()) {
1470                            Slog.e(TAG, "Failed to bind to media container service");
1471                            params.serviceError();
1472                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1473                                    System.identityHashCode(mHandler));
1474                            if (params.traceMethod != null) {
1475                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1476                                        params.traceCookie);
1477                            }
1478                            return;
1479                        } else {
1480                            // Once we bind to the service, the first
1481                            // pending request will be processed.
1482                            mPendingInstalls.add(idx, params);
1483                        }
1484                    } else {
1485                        mPendingInstalls.add(idx, params);
1486                        // Already bound to the service. Just make
1487                        // sure we trigger off processing the first request.
1488                        if (idx == 0) {
1489                            mHandler.sendEmptyMessage(MCS_BOUND);
1490                        }
1491                    }
1492                    break;
1493                }
1494                case MCS_BOUND: {
1495                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1496                    if (msg.obj != null) {
1497                        mContainerService = (IMediaContainerService) msg.obj;
1498                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1499                                System.identityHashCode(mHandler));
1500                    }
1501                    if (mContainerService == null) {
1502                        if (!mBound) {
1503                            // Something seriously wrong since we are not bound and we are not
1504                            // waiting for connection. Bail out.
1505                            Slog.e(TAG, "Cannot bind to media container service");
1506                            for (HandlerParams params : mPendingInstalls) {
1507                                // Indicate service bind error
1508                                params.serviceError();
1509                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1510                                        System.identityHashCode(params));
1511                                if (params.traceMethod != null) {
1512                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1513                                            params.traceMethod, params.traceCookie);
1514                                }
1515                                return;
1516                            }
1517                            mPendingInstalls.clear();
1518                        } else {
1519                            Slog.w(TAG, "Waiting to connect to media container service");
1520                        }
1521                    } else if (mPendingInstalls.size() > 0) {
1522                        HandlerParams params = mPendingInstalls.get(0);
1523                        if (params != null) {
1524                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1525                                    System.identityHashCode(params));
1526                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1527                            if (params.startCopy()) {
1528                                // We are done...  look for more work or to
1529                                // go idle.
1530                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1531                                        "Checking for more work or unbind...");
1532                                // Delete pending install
1533                                if (mPendingInstalls.size() > 0) {
1534                                    mPendingInstalls.remove(0);
1535                                }
1536                                if (mPendingInstalls.size() == 0) {
1537                                    if (mBound) {
1538                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1539                                                "Posting delayed MCS_UNBIND");
1540                                        removeMessages(MCS_UNBIND);
1541                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1542                                        // Unbind after a little delay, to avoid
1543                                        // continual thrashing.
1544                                        sendMessageDelayed(ubmsg, 10000);
1545                                    }
1546                                } else {
1547                                    // There are more pending requests in queue.
1548                                    // Just post MCS_BOUND message to trigger processing
1549                                    // of next pending install.
1550                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1551                                            "Posting MCS_BOUND for next work");
1552                                    mHandler.sendEmptyMessage(MCS_BOUND);
1553                                }
1554                            }
1555                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1556                        }
1557                    } else {
1558                        // Should never happen ideally.
1559                        Slog.w(TAG, "Empty queue");
1560                    }
1561                    break;
1562                }
1563                case MCS_RECONNECT: {
1564                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1565                    if (mPendingInstalls.size() > 0) {
1566                        if (mBound) {
1567                            disconnectService();
1568                        }
1569                        if (!connectToService()) {
1570                            Slog.e(TAG, "Failed to bind to media container service");
1571                            for (HandlerParams params : mPendingInstalls) {
1572                                // Indicate service bind error
1573                                params.serviceError();
1574                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1575                                        System.identityHashCode(params));
1576                            }
1577                            mPendingInstalls.clear();
1578                        }
1579                    }
1580                    break;
1581                }
1582                case MCS_UNBIND: {
1583                    // If there is no actual work left, then time to unbind.
1584                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1585
1586                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1587                        if (mBound) {
1588                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1589
1590                            disconnectService();
1591                        }
1592                    } else if (mPendingInstalls.size() > 0) {
1593                        // There are more pending requests in queue.
1594                        // Just post MCS_BOUND message to trigger processing
1595                        // of next pending install.
1596                        mHandler.sendEmptyMessage(MCS_BOUND);
1597                    }
1598
1599                    break;
1600                }
1601                case MCS_GIVE_UP: {
1602                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1603                    HandlerParams params = mPendingInstalls.remove(0);
1604                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1605                            System.identityHashCode(params));
1606                    break;
1607                }
1608                case SEND_PENDING_BROADCAST: {
1609                    String packages[];
1610                    ArrayList<String> components[];
1611                    int size = 0;
1612                    int uids[];
1613                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1614                    synchronized (mPackages) {
1615                        if (mPendingBroadcasts == null) {
1616                            return;
1617                        }
1618                        size = mPendingBroadcasts.size();
1619                        if (size <= 0) {
1620                            // Nothing to be done. Just return
1621                            return;
1622                        }
1623                        packages = new String[size];
1624                        components = new ArrayList[size];
1625                        uids = new int[size];
1626                        int i = 0;  // filling out the above arrays
1627
1628                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1629                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1630                            Iterator<Map.Entry<String, ArrayList<String>>> it
1631                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1632                                            .entrySet().iterator();
1633                            while (it.hasNext() && i < size) {
1634                                Map.Entry<String, ArrayList<String>> ent = it.next();
1635                                packages[i] = ent.getKey();
1636                                components[i] = ent.getValue();
1637                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1638                                uids[i] = (ps != null)
1639                                        ? UserHandle.getUid(packageUserId, ps.appId)
1640                                        : -1;
1641                                i++;
1642                            }
1643                        }
1644                        size = i;
1645                        mPendingBroadcasts.clear();
1646                    }
1647                    // Send broadcasts
1648                    for (int i = 0; i < size; i++) {
1649                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1650                    }
1651                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1652                    break;
1653                }
1654                case START_CLEANING_PACKAGE: {
1655                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1656                    final String packageName = (String)msg.obj;
1657                    final int userId = msg.arg1;
1658                    final boolean andCode = msg.arg2 != 0;
1659                    synchronized (mPackages) {
1660                        if (userId == UserHandle.USER_ALL) {
1661                            int[] users = sUserManager.getUserIds();
1662                            for (int user : users) {
1663                                mSettings.addPackageToCleanLPw(
1664                                        new PackageCleanItem(user, packageName, andCode));
1665                            }
1666                        } else {
1667                            mSettings.addPackageToCleanLPw(
1668                                    new PackageCleanItem(userId, packageName, andCode));
1669                        }
1670                    }
1671                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1672                    startCleaningPackages();
1673                } break;
1674                case POST_INSTALL: {
1675                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1676
1677                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1678                    final boolean didRestore = (msg.arg2 != 0);
1679                    mRunningInstalls.delete(msg.arg1);
1680
1681                    if (data != null) {
1682                        InstallArgs args = data.args;
1683                        PackageInstalledInfo parentRes = data.res;
1684
1685                        final boolean grantPermissions = (args.installFlags
1686                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1687                        final boolean killApp = (args.installFlags
1688                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1689                        final boolean virtualPreload = ((args.installFlags
1690                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1691                        final String[] grantedPermissions = args.installGrantPermissions;
1692
1693                        // Handle the parent package
1694                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1695                                virtualPreload, grantedPermissions, didRestore,
1696                                args.installerPackageName, args.observer);
1697
1698                        // Handle the child packages
1699                        final int childCount = (parentRes.addedChildPackages != null)
1700                                ? parentRes.addedChildPackages.size() : 0;
1701                        for (int i = 0; i < childCount; i++) {
1702                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1703                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1704                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1705                                    args.installerPackageName, args.observer);
1706                        }
1707
1708                        // Log tracing if needed
1709                        if (args.traceMethod != null) {
1710                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1711                                    args.traceCookie);
1712                        }
1713                    } else {
1714                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1715                    }
1716
1717                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1718                } break;
1719                case UPDATED_MEDIA_STATUS: {
1720                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1721                    boolean reportStatus = msg.arg1 == 1;
1722                    boolean doGc = msg.arg2 == 1;
1723                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1724                    if (doGc) {
1725                        // Force a gc to clear up stale containers.
1726                        Runtime.getRuntime().gc();
1727                    }
1728                    if (msg.obj != null) {
1729                        @SuppressWarnings("unchecked")
1730                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1731                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1732                        // Unload containers
1733                        unloadAllContainers(args);
1734                    }
1735                    if (reportStatus) {
1736                        try {
1737                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1738                                    "Invoking StorageManagerService call back");
1739                            PackageHelper.getStorageManager().finishMediaUpdate();
1740                        } catch (RemoteException e) {
1741                            Log.e(TAG, "StorageManagerService not running?");
1742                        }
1743                    }
1744                } break;
1745                case WRITE_SETTINGS: {
1746                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1747                    synchronized (mPackages) {
1748                        removeMessages(WRITE_SETTINGS);
1749                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1750                        mSettings.writeLPr();
1751                        mDirtyUsers.clear();
1752                    }
1753                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1754                } break;
1755                case WRITE_PACKAGE_RESTRICTIONS: {
1756                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1757                    synchronized (mPackages) {
1758                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1759                        for (int userId : mDirtyUsers) {
1760                            mSettings.writePackageRestrictionsLPr(userId);
1761                        }
1762                        mDirtyUsers.clear();
1763                    }
1764                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1765                } break;
1766                case WRITE_PACKAGE_LIST: {
1767                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1768                    synchronized (mPackages) {
1769                        removeMessages(WRITE_PACKAGE_LIST);
1770                        mSettings.writePackageListLPr(msg.arg1);
1771                    }
1772                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1773                } break;
1774                case CHECK_PENDING_VERIFICATION: {
1775                    final int verificationId = msg.arg1;
1776                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1777
1778                    if ((state != null) && !state.timeoutExtended()) {
1779                        final InstallArgs args = state.getInstallArgs();
1780                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1781
1782                        Slog.i(TAG, "Verification timed out for " + originUri);
1783                        mPendingVerification.remove(verificationId);
1784
1785                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1786
1787                        final UserHandle user = args.getUser();
1788                        if (getDefaultVerificationResponse(user)
1789                                == PackageManager.VERIFICATION_ALLOW) {
1790                            Slog.i(TAG, "Continuing with installation of " + originUri);
1791                            state.setVerifierResponse(Binder.getCallingUid(),
1792                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1793                            broadcastPackageVerified(verificationId, originUri,
1794                                    PackageManager.VERIFICATION_ALLOW, user);
1795                            try {
1796                                ret = args.copyApk(mContainerService, true);
1797                            } catch (RemoteException e) {
1798                                Slog.e(TAG, "Could not contact the ContainerService");
1799                            }
1800                        } else {
1801                            broadcastPackageVerified(verificationId, originUri,
1802                                    PackageManager.VERIFICATION_REJECT, user);
1803                        }
1804
1805                        Trace.asyncTraceEnd(
1806                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1807
1808                        processPendingInstall(args, ret);
1809                        mHandler.sendEmptyMessage(MCS_UNBIND);
1810                    }
1811                    break;
1812                }
1813                case PACKAGE_VERIFIED: {
1814                    final int verificationId = msg.arg1;
1815
1816                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1817                    if (state == null) {
1818                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1819                        break;
1820                    }
1821
1822                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1823
1824                    state.setVerifierResponse(response.callerUid, response.code);
1825
1826                    if (state.isVerificationComplete()) {
1827                        mPendingVerification.remove(verificationId);
1828
1829                        final InstallArgs args = state.getInstallArgs();
1830                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1831
1832                        int ret;
1833                        if (state.isInstallAllowed()) {
1834                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1835                            broadcastPackageVerified(verificationId, originUri,
1836                                    response.code, state.getInstallArgs().getUser());
1837                            try {
1838                                ret = args.copyApk(mContainerService, true);
1839                            } catch (RemoteException e) {
1840                                Slog.e(TAG, "Could not contact the ContainerService");
1841                            }
1842                        } else {
1843                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1844                        }
1845
1846                        Trace.asyncTraceEnd(
1847                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1848
1849                        processPendingInstall(args, ret);
1850                        mHandler.sendEmptyMessage(MCS_UNBIND);
1851                    }
1852
1853                    break;
1854                }
1855                case START_INTENT_FILTER_VERIFICATIONS: {
1856                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1857                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1858                            params.replacing, params.pkg);
1859                    break;
1860                }
1861                case INTENT_FILTER_VERIFIED: {
1862                    final int verificationId = msg.arg1;
1863
1864                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1865                            verificationId);
1866                    if (state == null) {
1867                        Slog.w(TAG, "Invalid IntentFilter verification token "
1868                                + verificationId + " received");
1869                        break;
1870                    }
1871
1872                    final int userId = state.getUserId();
1873
1874                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1875                            "Processing IntentFilter verification with token:"
1876                            + verificationId + " and userId:" + userId);
1877
1878                    final IntentFilterVerificationResponse response =
1879                            (IntentFilterVerificationResponse) msg.obj;
1880
1881                    state.setVerifierResponse(response.callerUid, response.code);
1882
1883                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1884                            "IntentFilter verification with token:" + verificationId
1885                            + " and userId:" + userId
1886                            + " is settings verifier response with response code:"
1887                            + response.code);
1888
1889                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1890                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1891                                + response.getFailedDomainsString());
1892                    }
1893
1894                    if (state.isVerificationComplete()) {
1895                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1896                    } else {
1897                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1898                                "IntentFilter verification with token:" + verificationId
1899                                + " was not said to be complete");
1900                    }
1901
1902                    break;
1903                }
1904                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1905                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1906                            mInstantAppResolverConnection,
1907                            (InstantAppRequest) msg.obj,
1908                            mInstantAppInstallerActivity,
1909                            mHandler);
1910                }
1911            }
1912        }
1913    }
1914
1915    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1916            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1917            boolean launchedForRestore, String installerPackage,
1918            IPackageInstallObserver2 installObserver) {
1919        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1920            // Send the removed broadcasts
1921            if (res.removedInfo != null) {
1922                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1923            }
1924
1925            // Now that we successfully installed the package, grant runtime
1926            // permissions if requested before broadcasting the install. Also
1927            // for legacy apps in permission review mode we clear the permission
1928            // review flag which is used to emulate runtime permissions for
1929            // legacy apps.
1930            if (grantPermissions) {
1931                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1932            }
1933
1934            final boolean update = res.removedInfo != null
1935                    && res.removedInfo.removedPackage != null;
1936            final String installerPackageName =
1937                    res.installerPackageName != null
1938                            ? res.installerPackageName
1939                            : res.removedInfo != null
1940                                    ? res.removedInfo.installerPackageName
1941                                    : null;
1942
1943            // If this is the first time we have child packages for a disabled privileged
1944            // app that had no children, we grant requested runtime permissions to the new
1945            // children if the parent on the system image had them already granted.
1946            if (res.pkg.parentPackage != null) {
1947                synchronized (mPackages) {
1948                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1949                }
1950            }
1951
1952            synchronized (mPackages) {
1953                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1954            }
1955
1956            final String packageName = res.pkg.applicationInfo.packageName;
1957
1958            // Determine the set of users who are adding this package for
1959            // the first time vs. those who are seeing an update.
1960            int[] firstUsers = EMPTY_INT_ARRAY;
1961            int[] updateUsers = EMPTY_INT_ARRAY;
1962            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1963            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1964            for (int newUser : res.newUsers) {
1965                if (ps.getInstantApp(newUser)) {
1966                    continue;
1967                }
1968                if (allNewUsers) {
1969                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1970                    continue;
1971                }
1972                boolean isNew = true;
1973                for (int origUser : res.origUsers) {
1974                    if (origUser == newUser) {
1975                        isNew = false;
1976                        break;
1977                    }
1978                }
1979                if (isNew) {
1980                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1981                } else {
1982                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1983                }
1984            }
1985
1986            // Send installed broadcasts if the package is not a static shared lib.
1987            if (res.pkg.staticSharedLibName == null) {
1988                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1989
1990                // Send added for users that see the package for the first time
1991                // sendPackageAddedForNewUsers also deals with system apps
1992                int appId = UserHandle.getAppId(res.uid);
1993                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1994                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1995                        virtualPreload /*startReceiver*/, appId, firstUsers);
1996
1997                // Send added for users that don't see the package for the first time
1998                Bundle extras = new Bundle(1);
1999                extras.putInt(Intent.EXTRA_UID, res.uid);
2000                if (update) {
2001                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2002                }
2003                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2004                        extras, 0 /*flags*/,
2005                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2006                if (installerPackageName != null) {
2007                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2008                            extras, 0 /*flags*/,
2009                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2010                }
2011
2012                // Send replaced for users that don't see the package for the first time
2013                if (update) {
2014                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2015                            packageName, extras, 0 /*flags*/,
2016                            null /*targetPackage*/, null /*finishedReceiver*/,
2017                            updateUsers);
2018                    if (installerPackageName != null) {
2019                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2020                                extras, 0 /*flags*/,
2021                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2022                    }
2023                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2024                            null /*package*/, null /*extras*/, 0 /*flags*/,
2025                            packageName /*targetPackage*/,
2026                            null /*finishedReceiver*/, updateUsers);
2027                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2028                    // First-install and we did a restore, so we're responsible for the
2029                    // first-launch broadcast.
2030                    if (DEBUG_BACKUP) {
2031                        Slog.i(TAG, "Post-restore of " + packageName
2032                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2033                    }
2034                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2035                }
2036
2037                // Send broadcast package appeared if forward locked/external for all users
2038                // treat asec-hosted packages like removable media on upgrade
2039                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2040                    if (DEBUG_INSTALL) {
2041                        Slog.i(TAG, "upgrading pkg " + res.pkg
2042                                + " is ASEC-hosted -> AVAILABLE");
2043                    }
2044                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2045                    ArrayList<String> pkgList = new ArrayList<>(1);
2046                    pkgList.add(packageName);
2047                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2048                }
2049            }
2050
2051            // Work that needs to happen on first install within each user
2052            if (firstUsers != null && firstUsers.length > 0) {
2053                synchronized (mPackages) {
2054                    for (int userId : firstUsers) {
2055                        // If this app is a browser and it's newly-installed for some
2056                        // users, clear any default-browser state in those users. The
2057                        // app's nature doesn't depend on the user, so we can just check
2058                        // its browser nature in any user and generalize.
2059                        if (packageIsBrowser(packageName, userId)) {
2060                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2061                        }
2062
2063                        // We may also need to apply pending (restored) runtime
2064                        // permission grants within these users.
2065                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2066                    }
2067                }
2068            }
2069
2070            // Log current value of "unknown sources" setting
2071            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2072                    getUnknownSourcesSettings());
2073
2074            // Remove the replaced package's older resources safely now
2075            // We delete after a gc for applications  on sdcard.
2076            if (res.removedInfo != null && res.removedInfo.args != null) {
2077                Runtime.getRuntime().gc();
2078                synchronized (mInstallLock) {
2079                    res.removedInfo.args.doPostDeleteLI(true);
2080                }
2081            } else {
2082                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2083                // and not block here.
2084                VMRuntime.getRuntime().requestConcurrentGC();
2085            }
2086
2087            // Notify DexManager that the package was installed for new users.
2088            // The updated users should already be indexed and the package code paths
2089            // should not change.
2090            // Don't notify the manager for ephemeral apps as they are not expected to
2091            // survive long enough to benefit of background optimizations.
2092            for (int userId : firstUsers) {
2093                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2094                // There's a race currently where some install events may interleave with an uninstall.
2095                // This can lead to package info being null (b/36642664).
2096                if (info != null) {
2097                    mDexManager.notifyPackageInstalled(info, userId);
2098                }
2099            }
2100        }
2101
2102        // If someone is watching installs - notify them
2103        if (installObserver != null) {
2104            try {
2105                Bundle extras = extrasForInstallResult(res);
2106                installObserver.onPackageInstalled(res.name, res.returnCode,
2107                        res.returnMsg, extras);
2108            } catch (RemoteException e) {
2109                Slog.i(TAG, "Observer no longer exists.");
2110            }
2111        }
2112    }
2113
2114    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2115            PackageParser.Package pkg) {
2116        if (pkg.parentPackage == null) {
2117            return;
2118        }
2119        if (pkg.requestedPermissions == null) {
2120            return;
2121        }
2122        final PackageSetting disabledSysParentPs = mSettings
2123                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2124        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2125                || !disabledSysParentPs.isPrivileged()
2126                || (disabledSysParentPs.childPackageNames != null
2127                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2128            return;
2129        }
2130        final int[] allUserIds = sUserManager.getUserIds();
2131        final int permCount = pkg.requestedPermissions.size();
2132        for (int i = 0; i < permCount; i++) {
2133            String permission = pkg.requestedPermissions.get(i);
2134            BasePermission bp = mSettings.mPermissions.get(permission);
2135            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2136                continue;
2137            }
2138            for (int userId : allUserIds) {
2139                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2140                        permission, userId)) {
2141                    grantRuntimePermission(pkg.packageName, permission, userId);
2142                }
2143            }
2144        }
2145    }
2146
2147    private StorageEventListener mStorageListener = new StorageEventListener() {
2148        @Override
2149        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2150            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2151                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2152                    final String volumeUuid = vol.getFsUuid();
2153
2154                    // Clean up any users or apps that were removed or recreated
2155                    // while this volume was missing
2156                    sUserManager.reconcileUsers(volumeUuid);
2157                    reconcileApps(volumeUuid);
2158
2159                    // Clean up any install sessions that expired or were
2160                    // cancelled while this volume was missing
2161                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2162
2163                    loadPrivatePackages(vol);
2164
2165                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2166                    unloadPrivatePackages(vol);
2167                }
2168            }
2169
2170            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2171                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2172                    updateExternalMediaStatus(true, false);
2173                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2174                    updateExternalMediaStatus(false, false);
2175                }
2176            }
2177        }
2178
2179        @Override
2180        public void onVolumeForgotten(String fsUuid) {
2181            if (TextUtils.isEmpty(fsUuid)) {
2182                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2183                return;
2184            }
2185
2186            // Remove any apps installed on the forgotten volume
2187            synchronized (mPackages) {
2188                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2189                for (PackageSetting ps : packages) {
2190                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2191                    deletePackageVersioned(new VersionedPackage(ps.name,
2192                            PackageManager.VERSION_CODE_HIGHEST),
2193                            new LegacyPackageDeleteObserver(null).getBinder(),
2194                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2195                    // Try very hard to release any references to this package
2196                    // so we don't risk the system server being killed due to
2197                    // open FDs
2198                    AttributeCache.instance().removePackage(ps.name);
2199                }
2200
2201                mSettings.onVolumeForgotten(fsUuid);
2202                mSettings.writeLPr();
2203            }
2204        }
2205    };
2206
2207    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2208            String[] grantedPermissions) {
2209        for (int userId : userIds) {
2210            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2211        }
2212    }
2213
2214    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2215            String[] grantedPermissions) {
2216        PackageSetting ps = (PackageSetting) pkg.mExtras;
2217        if (ps == null) {
2218            return;
2219        }
2220
2221        PermissionsState permissionsState = ps.getPermissionsState();
2222
2223        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2224                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2225
2226        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2227                >= Build.VERSION_CODES.M;
2228
2229        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2230
2231        for (String permission : pkg.requestedPermissions) {
2232            final BasePermission bp;
2233            synchronized (mPackages) {
2234                bp = mSettings.mPermissions.get(permission);
2235            }
2236            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2237                    && (!instantApp || bp.isInstant())
2238                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2239                    && (grantedPermissions == null
2240                           || ArrayUtils.contains(grantedPermissions, permission))) {
2241                final int flags = permissionsState.getPermissionFlags(permission, userId);
2242                if (supportsRuntimePermissions) {
2243                    // Installer cannot change immutable permissions.
2244                    if ((flags & immutableFlags) == 0) {
2245                        grantRuntimePermission(pkg.packageName, permission, userId);
2246                    }
2247                } else if (mPermissionReviewRequired) {
2248                    // In permission review mode we clear the review flag when we
2249                    // are asked to install the app with all permissions granted.
2250                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2251                        updatePermissionFlags(permission, pkg.packageName,
2252                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2253                    }
2254                }
2255            }
2256        }
2257    }
2258
2259    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2260        Bundle extras = null;
2261        switch (res.returnCode) {
2262            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2263                extras = new Bundle();
2264                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2265                        res.origPermission);
2266                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2267                        res.origPackage);
2268                break;
2269            }
2270            case PackageManager.INSTALL_SUCCEEDED: {
2271                extras = new Bundle();
2272                extras.putBoolean(Intent.EXTRA_REPLACING,
2273                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2274                break;
2275            }
2276        }
2277        return extras;
2278    }
2279
2280    void scheduleWriteSettingsLocked() {
2281        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2282            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2283        }
2284    }
2285
2286    void scheduleWritePackageListLocked(int userId) {
2287        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2288            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2289            msg.arg1 = userId;
2290            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2291        }
2292    }
2293
2294    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2295        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2296        scheduleWritePackageRestrictionsLocked(userId);
2297    }
2298
2299    void scheduleWritePackageRestrictionsLocked(int userId) {
2300        final int[] userIds = (userId == UserHandle.USER_ALL)
2301                ? sUserManager.getUserIds() : new int[]{userId};
2302        for (int nextUserId : userIds) {
2303            if (!sUserManager.exists(nextUserId)) return;
2304            mDirtyUsers.add(nextUserId);
2305            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2306                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2307            }
2308        }
2309    }
2310
2311    public static PackageManagerService main(Context context, Installer installer,
2312            boolean factoryTest, boolean onlyCore) {
2313        // Self-check for initial settings.
2314        PackageManagerServiceCompilerMapping.checkProperties();
2315
2316        PackageManagerService m = new PackageManagerService(context, installer,
2317                factoryTest, onlyCore);
2318        m.enableSystemUserPackages();
2319        ServiceManager.addService("package", m);
2320        final PackageManagerNative pmn = m.new PackageManagerNative();
2321        ServiceManager.addService("package_native", pmn);
2322        return m;
2323    }
2324
2325    private void enableSystemUserPackages() {
2326        if (!UserManager.isSplitSystemUser()) {
2327            return;
2328        }
2329        // For system user, enable apps based on the following conditions:
2330        // - app is whitelisted or belong to one of these groups:
2331        //   -- system app which has no launcher icons
2332        //   -- system app which has INTERACT_ACROSS_USERS permission
2333        //   -- system IME app
2334        // - app is not in the blacklist
2335        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2336        Set<String> enableApps = new ArraySet<>();
2337        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2338                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2339                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2340        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2341        enableApps.addAll(wlApps);
2342        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2343                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2344        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2345        enableApps.removeAll(blApps);
2346        Log.i(TAG, "Applications installed for system user: " + enableApps);
2347        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2348                UserHandle.SYSTEM);
2349        final int allAppsSize = allAps.size();
2350        synchronized (mPackages) {
2351            for (int i = 0; i < allAppsSize; i++) {
2352                String pName = allAps.get(i);
2353                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2354                // Should not happen, but we shouldn't be failing if it does
2355                if (pkgSetting == null) {
2356                    continue;
2357                }
2358                boolean install = enableApps.contains(pName);
2359                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2360                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2361                            + " for system user");
2362                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2363                }
2364            }
2365            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2366        }
2367    }
2368
2369    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2370        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2371                Context.DISPLAY_SERVICE);
2372        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2373    }
2374
2375    /**
2376     * Requests that files preopted on a secondary system partition be copied to the data partition
2377     * if possible.  Note that the actual copying of the files is accomplished by init for security
2378     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2379     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2380     */
2381    private static void requestCopyPreoptedFiles() {
2382        final int WAIT_TIME_MS = 100;
2383        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2384        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2385            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2386            // We will wait for up to 100 seconds.
2387            final long timeStart = SystemClock.uptimeMillis();
2388            final long timeEnd = timeStart + 100 * 1000;
2389            long timeNow = timeStart;
2390            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2391                try {
2392                    Thread.sleep(WAIT_TIME_MS);
2393                } catch (InterruptedException e) {
2394                    // Do nothing
2395                }
2396                timeNow = SystemClock.uptimeMillis();
2397                if (timeNow > timeEnd) {
2398                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2399                    Slog.wtf(TAG, "cppreopt did not finish!");
2400                    break;
2401                }
2402            }
2403
2404            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2405        }
2406    }
2407
2408    public PackageManagerService(Context context, Installer installer,
2409            boolean factoryTest, boolean onlyCore) {
2410        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2411        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2412        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2413                SystemClock.uptimeMillis());
2414
2415        if (mSdkVersion <= 0) {
2416            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2417        }
2418
2419        mContext = context;
2420
2421        mPermissionReviewRequired = context.getResources().getBoolean(
2422                R.bool.config_permissionReviewRequired);
2423
2424        mFactoryTest = factoryTest;
2425        mOnlyCore = onlyCore;
2426        mMetrics = new DisplayMetrics();
2427        mSettings = new Settings(mPackages);
2428        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2429                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2430        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2431                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2432        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2433                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2434        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2435                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2436        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2437                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2438        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2439                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2440        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2441                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2442
2443        String separateProcesses = SystemProperties.get("debug.separate_processes");
2444        if (separateProcesses != null && separateProcesses.length() > 0) {
2445            if ("*".equals(separateProcesses)) {
2446                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2447                mSeparateProcesses = null;
2448                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2449            } else {
2450                mDefParseFlags = 0;
2451                mSeparateProcesses = separateProcesses.split(",");
2452                Slog.w(TAG, "Running with debug.separate_processes: "
2453                        + separateProcesses);
2454            }
2455        } else {
2456            mDefParseFlags = 0;
2457            mSeparateProcesses = null;
2458        }
2459
2460        mInstaller = installer;
2461        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2462                "*dexopt*");
2463        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2464        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2465
2466        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2467                FgThread.get().getLooper());
2468
2469        getDefaultDisplayMetrics(context, mMetrics);
2470
2471        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2472        SystemConfig systemConfig = SystemConfig.getInstance();
2473        mGlobalGids = systemConfig.getGlobalGids();
2474        mSystemPermissions = systemConfig.getSystemPermissions();
2475        mAvailableFeatures = systemConfig.getAvailableFeatures();
2476        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2477
2478        mProtectedPackages = new ProtectedPackages(mContext);
2479
2480        synchronized (mInstallLock) {
2481        // writer
2482        synchronized (mPackages) {
2483            mHandlerThread = new ServiceThread(TAG,
2484                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2485            mHandlerThread.start();
2486            mHandler = new PackageHandler(mHandlerThread.getLooper());
2487            mProcessLoggingHandler = new ProcessLoggingHandler();
2488            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2489
2490            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2491            mInstantAppRegistry = new InstantAppRegistry(this);
2492
2493            File dataDir = Environment.getDataDirectory();
2494            mAppInstallDir = new File(dataDir, "app");
2495            mAppLib32InstallDir = new File(dataDir, "app-lib");
2496            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2497            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2498            sUserManager = new UserManagerService(context, this,
2499                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2500
2501            // Propagate permission configuration in to package manager.
2502            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2503                    = systemConfig.getPermissions();
2504            for (int i=0; i<permConfig.size(); i++) {
2505                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2506                BasePermission bp = mSettings.mPermissions.get(perm.name);
2507                if (bp == null) {
2508                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2509                    mSettings.mPermissions.put(perm.name, bp);
2510                }
2511                if (perm.gids != null) {
2512                    bp.setGids(perm.gids, perm.perUser);
2513                }
2514            }
2515
2516            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2517            final int builtInLibCount = libConfig.size();
2518            for (int i = 0; i < builtInLibCount; i++) {
2519                String name = libConfig.keyAt(i);
2520                String path = libConfig.valueAt(i);
2521                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2522                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2523            }
2524
2525            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2526
2527            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2528            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2529            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2530
2531            // Clean up orphaned packages for which the code path doesn't exist
2532            // and they are an update to a system app - caused by bug/32321269
2533            final int packageSettingCount = mSettings.mPackages.size();
2534            for (int i = packageSettingCount - 1; i >= 0; i--) {
2535                PackageSetting ps = mSettings.mPackages.valueAt(i);
2536                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2537                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2538                    mSettings.mPackages.removeAt(i);
2539                    mSettings.enableSystemPackageLPw(ps.name);
2540                }
2541            }
2542
2543            if (mFirstBoot) {
2544                requestCopyPreoptedFiles();
2545            }
2546
2547            String customResolverActivity = Resources.getSystem().getString(
2548                    R.string.config_customResolverActivity);
2549            if (TextUtils.isEmpty(customResolverActivity)) {
2550                customResolverActivity = null;
2551            } else {
2552                mCustomResolverComponentName = ComponentName.unflattenFromString(
2553                        customResolverActivity);
2554            }
2555
2556            long startTime = SystemClock.uptimeMillis();
2557
2558            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2559                    startTime);
2560
2561            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2562            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2563
2564            if (bootClassPath == null) {
2565                Slog.w(TAG, "No BOOTCLASSPATH found!");
2566            }
2567
2568            if (systemServerClassPath == null) {
2569                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2570            }
2571
2572            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2573
2574            final VersionInfo ver = mSettings.getInternalVersion();
2575            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2576            if (mIsUpgrade) {
2577                logCriticalInfo(Log.INFO,
2578                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2579            }
2580
2581            // when upgrading from pre-M, promote system app permissions from install to runtime
2582            mPromoteSystemApps =
2583                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2584
2585            // When upgrading from pre-N, we need to handle package extraction like first boot,
2586            // as there is no profiling data available.
2587            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2588
2589            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2590
2591            // save off the names of pre-existing system packages prior to scanning; we don't
2592            // want to automatically grant runtime permissions for new system apps
2593            if (mPromoteSystemApps) {
2594                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2595                while (pkgSettingIter.hasNext()) {
2596                    PackageSetting ps = pkgSettingIter.next();
2597                    if (isSystemApp(ps)) {
2598                        mExistingSystemPackages.add(ps.name);
2599                    }
2600                }
2601            }
2602
2603            mCacheDir = preparePackageParserCache(mIsUpgrade);
2604
2605            // Set flag to monitor and not change apk file paths when
2606            // scanning install directories.
2607            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2608
2609            if (mIsUpgrade || mFirstBoot) {
2610                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2611            }
2612
2613            // Collect vendor overlay packages. (Do this before scanning any apps.)
2614            // For security and version matching reason, only consider
2615            // overlay packages if they reside in the right directory.
2616            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2617                    | PackageParser.PARSE_IS_SYSTEM
2618                    | PackageParser.PARSE_IS_SYSTEM_DIR
2619                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2620
2621            mParallelPackageParserCallback.findStaticOverlayPackages();
2622
2623            // Find base frameworks (resource packages without code).
2624            scanDirTracedLI(frameworkDir, mDefParseFlags
2625                    | PackageParser.PARSE_IS_SYSTEM
2626                    | PackageParser.PARSE_IS_SYSTEM_DIR
2627                    | PackageParser.PARSE_IS_PRIVILEGED,
2628                    scanFlags | SCAN_NO_DEX, 0);
2629
2630            // Collected privileged system packages.
2631            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2632            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2633                    | PackageParser.PARSE_IS_SYSTEM
2634                    | PackageParser.PARSE_IS_SYSTEM_DIR
2635                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2636
2637            // Collect ordinary system packages.
2638            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2639            scanDirTracedLI(systemAppDir, mDefParseFlags
2640                    | PackageParser.PARSE_IS_SYSTEM
2641                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2642
2643            // Collect all vendor packages.
2644            File vendorAppDir = new File("/vendor/app");
2645            try {
2646                vendorAppDir = vendorAppDir.getCanonicalFile();
2647            } catch (IOException e) {
2648                // failed to look up canonical path, continue with original one
2649            }
2650            scanDirTracedLI(vendorAppDir, mDefParseFlags
2651                    | PackageParser.PARSE_IS_SYSTEM
2652                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2653
2654            // Collect all OEM packages.
2655            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2656            scanDirTracedLI(oemAppDir, mDefParseFlags
2657                    | PackageParser.PARSE_IS_SYSTEM
2658                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2659
2660            // Prune any system packages that no longer exist.
2661            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2662            // Stub packages must either be replaced with full versions in the /data
2663            // partition or be disabled.
2664            final List<String> stubSystemApps = new ArrayList<>();
2665            if (!mOnlyCore) {
2666                // do this first before mucking with mPackages for the "expecting better" case
2667                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2668                while (pkgIterator.hasNext()) {
2669                    final PackageParser.Package pkg = pkgIterator.next();
2670                    if (pkg.isStub) {
2671                        stubSystemApps.add(pkg.packageName);
2672                    }
2673                }
2674
2675                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2676                while (psit.hasNext()) {
2677                    PackageSetting ps = psit.next();
2678
2679                    /*
2680                     * If this is not a system app, it can't be a
2681                     * disable system app.
2682                     */
2683                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2684                        continue;
2685                    }
2686
2687                    /*
2688                     * If the package is scanned, it's not erased.
2689                     */
2690                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2691                    if (scannedPkg != null) {
2692                        /*
2693                         * If the system app is both scanned and in the
2694                         * disabled packages list, then it must have been
2695                         * added via OTA. Remove it from the currently
2696                         * scanned package so the previously user-installed
2697                         * application can be scanned.
2698                         */
2699                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2700                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2701                                    + ps.name + "; removing system app.  Last known codePath="
2702                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2703                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2704                                    + scannedPkg.mVersionCode);
2705                            removePackageLI(scannedPkg, true);
2706                            mExpectingBetter.put(ps.name, ps.codePath);
2707                        }
2708
2709                        continue;
2710                    }
2711
2712                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2713                        psit.remove();
2714                        logCriticalInfo(Log.WARN, "System package " + ps.name
2715                                + " no longer exists; it's data will be wiped");
2716                        // Actual deletion of code and data will be handled by later
2717                        // reconciliation step
2718                    } else {
2719                        // we still have a disabled system package, but, it still might have
2720                        // been removed. check the code path still exists and check there's
2721                        // still a package. the latter can happen if an OTA keeps the same
2722                        // code path, but, changes the package name.
2723                        final PackageSetting disabledPs =
2724                                mSettings.getDisabledSystemPkgLPr(ps.name);
2725                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2726                                || disabledPs.pkg == null) {
2727                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2728                        }
2729                    }
2730                }
2731            }
2732
2733            //look for any incomplete package installations
2734            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2735            for (int i = 0; i < deletePkgsList.size(); i++) {
2736                // Actual deletion of code and data will be handled by later
2737                // reconciliation step
2738                final String packageName = deletePkgsList.get(i).name;
2739                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2740                synchronized (mPackages) {
2741                    mSettings.removePackageLPw(packageName);
2742                }
2743            }
2744
2745            //delete tmp files
2746            deleteTempPackageFiles();
2747
2748            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2749
2750            // Remove any shared userIDs that have no associated packages
2751            mSettings.pruneSharedUsersLPw();
2752            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2753            final int systemPackagesCount = mPackages.size();
2754            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2755                    + " ms, packageCount: " + systemPackagesCount
2756                    + " , timePerPackage: "
2757                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2758                    + " , cached: " + cachedSystemApps);
2759            if (mIsUpgrade && systemPackagesCount > 0) {
2760                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2761                        ((int) systemScanTime) / systemPackagesCount);
2762            }
2763            if (!mOnlyCore) {
2764                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2765                        SystemClock.uptimeMillis());
2766                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2767
2768                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2769                        | PackageParser.PARSE_FORWARD_LOCK,
2770                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2771
2772                // Remove disable package settings for updated system apps that were
2773                // removed via an OTA. If the update is no longer present, remove the
2774                // app completely. Otherwise, revoke their system privileges.
2775                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2776                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2777                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2778
2779                    final String msg;
2780                    if (deletedPkg == null) {
2781                        // should have found an update, but, we didn't; remove everything
2782                        msg = "Updated system package " + deletedAppName
2783                                + " no longer exists; removing its data";
2784                        // Actual deletion of code and data will be handled by later
2785                        // reconciliation step
2786                    } else {
2787                        // found an update; revoke system privileges
2788                        msg = "Updated system package + " + deletedAppName
2789                                + " no longer exists; revoking system privileges";
2790
2791                        // Don't do anything if a stub is removed from the system image. If
2792                        // we were to remove the uncompressed version from the /data partition,
2793                        // this is where it'd be done.
2794
2795                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2796                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2797                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2798                    }
2799                    logCriticalInfo(Log.WARN, msg);
2800                }
2801
2802                /*
2803                 * Make sure all system apps that we expected to appear on
2804                 * the userdata partition actually showed up. If they never
2805                 * appeared, crawl back and revive the system version.
2806                 */
2807                for (int i = 0; i < mExpectingBetter.size(); i++) {
2808                    final String packageName = mExpectingBetter.keyAt(i);
2809                    if (!mPackages.containsKey(packageName)) {
2810                        final File scanFile = mExpectingBetter.valueAt(i);
2811
2812                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2813                                + " but never showed up; reverting to system");
2814
2815                        int reparseFlags = mDefParseFlags;
2816                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2817                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2818                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2819                                    | PackageParser.PARSE_IS_PRIVILEGED;
2820                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2821                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2822                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2823                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2824                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2825                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2826                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2827                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2828                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2829                        } else {
2830                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2831                            continue;
2832                        }
2833
2834                        mSettings.enableSystemPackageLPw(packageName);
2835
2836                        try {
2837                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2838                        } catch (PackageManagerException e) {
2839                            Slog.e(TAG, "Failed to parse original system package: "
2840                                    + e.getMessage());
2841                        }
2842                    }
2843                }
2844
2845                // Uncompress and install any stubbed system applications.
2846                // This must be done last to ensure all stubs are replaced or disabled.
2847                decompressSystemApplications(stubSystemApps, scanFlags);
2848
2849                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2850                                - cachedSystemApps;
2851
2852                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2853                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2854                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2855                        + " ms, packageCount: " + dataPackagesCount
2856                        + " , timePerPackage: "
2857                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2858                        + " , cached: " + cachedNonSystemApps);
2859                if (mIsUpgrade && dataPackagesCount > 0) {
2860                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2861                            ((int) dataScanTime) / dataPackagesCount);
2862                }
2863            }
2864            mExpectingBetter.clear();
2865
2866            // Resolve the storage manager.
2867            mStorageManagerPackage = getStorageManagerPackageName();
2868
2869            // Resolve protected action filters. Only the setup wizard is allowed to
2870            // have a high priority filter for these actions.
2871            mSetupWizardPackage = getSetupWizardPackageName();
2872            if (mProtectedFilters.size() > 0) {
2873                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2874                    Slog.i(TAG, "No setup wizard;"
2875                        + " All protected intents capped to priority 0");
2876                }
2877                for (ActivityIntentInfo filter : mProtectedFilters) {
2878                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2879                        if (DEBUG_FILTERS) {
2880                            Slog.i(TAG, "Found setup wizard;"
2881                                + " allow priority " + filter.getPriority() + ";"
2882                                + " package: " + filter.activity.info.packageName
2883                                + " activity: " + filter.activity.className
2884                                + " priority: " + filter.getPriority());
2885                        }
2886                        // skip setup wizard; allow it to keep the high priority filter
2887                        continue;
2888                    }
2889                    if (DEBUG_FILTERS) {
2890                        Slog.i(TAG, "Protected action; cap priority to 0;"
2891                                + " package: " + filter.activity.info.packageName
2892                                + " activity: " + filter.activity.className
2893                                + " origPrio: " + filter.getPriority());
2894                    }
2895                    filter.setPriority(0);
2896                }
2897            }
2898            mDeferProtectedFilters = false;
2899            mProtectedFilters.clear();
2900
2901            // Now that we know all of the shared libraries, update all clients to have
2902            // the correct library paths.
2903            updateAllSharedLibrariesLPw(null);
2904
2905            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2906                // NOTE: We ignore potential failures here during a system scan (like
2907                // the rest of the commands above) because there's precious little we
2908                // can do about it. A settings error is reported, though.
2909                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2910            }
2911
2912            // Now that we know all the packages we are keeping,
2913            // read and update their last usage times.
2914            mPackageUsage.read(mPackages);
2915            mCompilerStats.read();
2916
2917            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2918                    SystemClock.uptimeMillis());
2919            Slog.i(TAG, "Time to scan packages: "
2920                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2921                    + " seconds");
2922
2923            // If the platform SDK has changed since the last time we booted,
2924            // we need to re-grant app permission to catch any new ones that
2925            // appear.  This is really a hack, and means that apps can in some
2926            // cases get permissions that the user didn't initially explicitly
2927            // allow...  it would be nice to have some better way to handle
2928            // this situation.
2929            int updateFlags = UPDATE_PERMISSIONS_ALL;
2930            if (ver.sdkVersion != mSdkVersion) {
2931                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2932                        + mSdkVersion + "; regranting permissions for internal storage");
2933                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2934            }
2935            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2936            ver.sdkVersion = mSdkVersion;
2937
2938            // If this is the first boot or an update from pre-M, and it is a normal
2939            // boot, then we need to initialize the default preferred apps across
2940            // all defined users.
2941            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2942                for (UserInfo user : sUserManager.getUsers(true)) {
2943                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2944                    applyFactoryDefaultBrowserLPw(user.id);
2945                    primeDomainVerificationsLPw(user.id);
2946                }
2947            }
2948
2949            // Prepare storage for system user really early during boot,
2950            // since core system apps like SettingsProvider and SystemUI
2951            // can't wait for user to start
2952            final int storageFlags;
2953            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2954                storageFlags = StorageManager.FLAG_STORAGE_DE;
2955            } else {
2956                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2957            }
2958            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2959                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2960                    true /* onlyCoreApps */);
2961            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2962                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2963                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2964                traceLog.traceBegin("AppDataFixup");
2965                try {
2966                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2967                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2968                } catch (InstallerException e) {
2969                    Slog.w(TAG, "Trouble fixing GIDs", e);
2970                }
2971                traceLog.traceEnd();
2972
2973                traceLog.traceBegin("AppDataPrepare");
2974                if (deferPackages == null || deferPackages.isEmpty()) {
2975                    return;
2976                }
2977                int count = 0;
2978                for (String pkgName : deferPackages) {
2979                    PackageParser.Package pkg = null;
2980                    synchronized (mPackages) {
2981                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2982                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2983                            pkg = ps.pkg;
2984                        }
2985                    }
2986                    if (pkg != null) {
2987                        synchronized (mInstallLock) {
2988                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2989                                    true /* maybeMigrateAppData */);
2990                        }
2991                        count++;
2992                    }
2993                }
2994                traceLog.traceEnd();
2995                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2996            }, "prepareAppData");
2997
2998            // If this is first boot after an OTA, and a normal boot, then
2999            // we need to clear code cache directories.
3000            // Note that we do *not* clear the application profiles. These remain valid
3001            // across OTAs and are used to drive profile verification (post OTA) and
3002            // profile compilation (without waiting to collect a fresh set of profiles).
3003            if (mIsUpgrade && !onlyCore) {
3004                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3005                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3006                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3007                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3008                        // No apps are running this early, so no need to freeze
3009                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3010                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3011                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3012                    }
3013                }
3014                ver.fingerprint = Build.FINGERPRINT;
3015            }
3016
3017            checkDefaultBrowser();
3018
3019            // clear only after permissions and other defaults have been updated
3020            mExistingSystemPackages.clear();
3021            mPromoteSystemApps = false;
3022
3023            // All the changes are done during package scanning.
3024            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3025
3026            // can downgrade to reader
3027            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3028            mSettings.writeLPr();
3029            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3030            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3031                    SystemClock.uptimeMillis());
3032
3033            if (!mOnlyCore) {
3034                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3035                mRequiredInstallerPackage = getRequiredInstallerLPr();
3036                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3037                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3038                if (mIntentFilterVerifierComponent != null) {
3039                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3040                            mIntentFilterVerifierComponent);
3041                } else {
3042                    mIntentFilterVerifier = null;
3043                }
3044                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3045                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3046                        SharedLibraryInfo.VERSION_UNDEFINED);
3047                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3048                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3049                        SharedLibraryInfo.VERSION_UNDEFINED);
3050            } else {
3051                mRequiredVerifierPackage = null;
3052                mRequiredInstallerPackage = null;
3053                mRequiredUninstallerPackage = null;
3054                mIntentFilterVerifierComponent = null;
3055                mIntentFilterVerifier = null;
3056                mServicesSystemSharedLibraryPackageName = null;
3057                mSharedSystemSharedLibraryPackageName = null;
3058            }
3059
3060            mInstallerService = new PackageInstallerService(context, this);
3061            final Pair<ComponentName, String> instantAppResolverComponent =
3062                    getInstantAppResolverLPr();
3063            if (instantAppResolverComponent != null) {
3064                if (DEBUG_EPHEMERAL) {
3065                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3066                }
3067                mInstantAppResolverConnection = new EphemeralResolverConnection(
3068                        mContext, instantAppResolverComponent.first,
3069                        instantAppResolverComponent.second);
3070                mInstantAppResolverSettingsComponent =
3071                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3072            } else {
3073                mInstantAppResolverConnection = null;
3074                mInstantAppResolverSettingsComponent = null;
3075            }
3076            updateInstantAppInstallerLocked(null);
3077
3078            // Read and update the usage of dex files.
3079            // Do this at the end of PM init so that all the packages have their
3080            // data directory reconciled.
3081            // At this point we know the code paths of the packages, so we can validate
3082            // the disk file and build the internal cache.
3083            // The usage file is expected to be small so loading and verifying it
3084            // should take a fairly small time compare to the other activities (e.g. package
3085            // scanning).
3086            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3087            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3088            for (int userId : currentUserIds) {
3089                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3090            }
3091            mDexManager.load(userPackages);
3092            if (mIsUpgrade) {
3093                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3094                        (int) (SystemClock.uptimeMillis() - startTime));
3095            }
3096        } // synchronized (mPackages)
3097        } // synchronized (mInstallLock)
3098
3099        // Now after opening every single application zip, make sure they
3100        // are all flushed.  Not really needed, but keeps things nice and
3101        // tidy.
3102        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3103        Runtime.getRuntime().gc();
3104        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3105
3106        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3107        FallbackCategoryProvider.loadFallbacks();
3108        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3109
3110        // The initial scanning above does many calls into installd while
3111        // holding the mPackages lock, but we're mostly interested in yelling
3112        // once we have a booted system.
3113        mInstaller.setWarnIfHeld(mPackages);
3114
3115        // Expose private service for system components to use.
3116        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3117        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3118    }
3119
3120    /**
3121     * Uncompress and install stub applications.
3122     * <p>In order to save space on the system partition, some applications are shipped in a
3123     * compressed form. In addition the compressed bits for the full application, the
3124     * system image contains a tiny stub comprised of only the Android manifest.
3125     * <p>During the first boot, attempt to uncompress and install the full application. If
3126     * the application can't be installed for any reason, disable the stub and prevent
3127     * uncompressing the full application during future boots.
3128     * <p>In order to forcefully attempt an installation of a full application, go to app
3129     * settings and enable the application.
3130     */
3131    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3132        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3133            final String pkgName = stubSystemApps.get(i);
3134            // skip if the system package is already disabled
3135            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3136                stubSystemApps.remove(i);
3137                continue;
3138            }
3139            // skip if the package isn't installed (?!); this should never happen
3140            final PackageParser.Package pkg = mPackages.get(pkgName);
3141            if (pkg == null) {
3142                stubSystemApps.remove(i);
3143                continue;
3144            }
3145            // skip if the package has been disabled by the user
3146            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3147            if (ps != null) {
3148                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3149                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3150                    stubSystemApps.remove(i);
3151                    continue;
3152                }
3153            }
3154
3155            if (DEBUG_COMPRESSION) {
3156                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3157            }
3158
3159            // uncompress the binary to its eventual destination on /data
3160            final File scanFile = decompressPackage(pkg);
3161            if (scanFile == null) {
3162                continue;
3163            }
3164
3165            // install the package to replace the stub on /system
3166            try {
3167                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3168                removePackageLI(pkg, true /*chatty*/);
3169                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3170                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3171                        UserHandle.USER_SYSTEM, "android");
3172                stubSystemApps.remove(i);
3173                continue;
3174            } catch (PackageManagerException e) {
3175                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3176            }
3177
3178            // any failed attempt to install the package will be cleaned up later
3179        }
3180
3181        // disable any stub still left; these failed to install the full application
3182        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3183            final String pkgName = stubSystemApps.get(i);
3184            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3185            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3186                    UserHandle.USER_SYSTEM, "android");
3187            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3188        }
3189    }
3190
3191    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3192        if (DEBUG_COMPRESSION) {
3193            Slog.i(TAG, "Decompress file"
3194                    + "; src: " + srcFile.getAbsolutePath()
3195                    + ", dst: " + dstFile.getAbsolutePath());
3196        }
3197        try (
3198                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3199                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3200        ) {
3201            Streams.copy(fileIn, fileOut);
3202            Os.chmod(dstFile.getAbsolutePath(), 0644);
3203            return PackageManager.INSTALL_SUCCEEDED;
3204        } catch (IOException e) {
3205            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3206                    + "; src: " + srcFile.getAbsolutePath()
3207                    + ", dst: " + dstFile.getAbsolutePath());
3208        }
3209        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3210    }
3211
3212    private File[] getCompressedFiles(String codePath) {
3213        final File stubCodePath = new File(codePath);
3214        final String stubName = stubCodePath.getName();
3215
3216        // The layout of a compressed package on a given partition is as follows :
3217        //
3218        // Compressed artifacts:
3219        //
3220        // /partition/ModuleName/foo.gz
3221        // /partation/ModuleName/bar.gz
3222        //
3223        // Stub artifact:
3224        //
3225        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3226        //
3227        // In other words, stub is on the same partition as the compressed artifacts
3228        // and in a directory that's suffixed with "-Stub".
3229        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3230        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3231            return null;
3232        }
3233
3234        final File stubParentDir = stubCodePath.getParentFile();
3235        if (stubParentDir == null) {
3236            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3237            return null;
3238        }
3239
3240        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3241        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3242            @Override
3243            public boolean accept(File dir, String name) {
3244                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3245            }
3246        });
3247
3248        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3249            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3250        }
3251
3252        return files;
3253    }
3254
3255    private boolean compressedFileExists(String codePath) {
3256        final File[] compressedFiles = getCompressedFiles(codePath);
3257        return compressedFiles != null && compressedFiles.length > 0;
3258    }
3259
3260    /**
3261     * Decompresses the given package on the system image onto
3262     * the /data partition.
3263     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3264     */
3265    private File decompressPackage(PackageParser.Package pkg) {
3266        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3267        if (compressedFiles == null || compressedFiles.length == 0) {
3268            if (DEBUG_COMPRESSION) {
3269                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3270            }
3271            return null;
3272        }
3273        final File dstCodePath =
3274                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3275        int ret = PackageManager.INSTALL_SUCCEEDED;
3276        try {
3277            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3278            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3279            for (File srcFile : compressedFiles) {
3280                final String srcFileName = srcFile.getName();
3281                final String dstFileName = srcFileName.substring(
3282                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3283                final File dstFile = new File(dstCodePath, dstFileName);
3284                ret = decompressFile(srcFile, dstFile);
3285                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3286                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3287                            + "; pkg: " + pkg.packageName
3288                            + ", file: " + dstFileName);
3289                    break;
3290                }
3291            }
3292        } catch (ErrnoException e) {
3293            logCriticalInfo(Log.ERROR, "Failed to decompress"
3294                    + "; pkg: " + pkg.packageName
3295                    + ", err: " + e.errno);
3296        }
3297        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3298            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3299            NativeLibraryHelper.Handle handle = null;
3300            try {
3301                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3302                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3303                        null /*abiOverride*/);
3304            } catch (IOException e) {
3305                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3306                        + "; pkg: " + pkg.packageName);
3307                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3308            } finally {
3309                IoUtils.closeQuietly(handle);
3310            }
3311        }
3312        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3313            if (dstCodePath == null || !dstCodePath.exists()) {
3314                return null;
3315            }
3316            removeCodePathLI(dstCodePath);
3317            return null;
3318        }
3319
3320        return dstCodePath;
3321    }
3322
3323    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3324        // we're only interested in updating the installer appliction when 1) it's not
3325        // already set or 2) the modified package is the installer
3326        if (mInstantAppInstallerActivity != null
3327                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3328                        .equals(modifiedPackage)) {
3329            return;
3330        }
3331        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3332    }
3333
3334    private static File preparePackageParserCache(boolean isUpgrade) {
3335        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3336            return null;
3337        }
3338
3339        // Disable package parsing on eng builds to allow for faster incremental development.
3340        if (Build.IS_ENG) {
3341            return null;
3342        }
3343
3344        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3345            Slog.i(TAG, "Disabling package parser cache due to system property.");
3346            return null;
3347        }
3348
3349        // The base directory for the package parser cache lives under /data/system/.
3350        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3351                "package_cache");
3352        if (cacheBaseDir == null) {
3353            return null;
3354        }
3355
3356        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3357        // This also serves to "GC" unused entries when the package cache version changes (which
3358        // can only happen during upgrades).
3359        if (isUpgrade) {
3360            FileUtils.deleteContents(cacheBaseDir);
3361        }
3362
3363
3364        // Return the versioned package cache directory. This is something like
3365        // "/data/system/package_cache/1"
3366        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3367
3368        // The following is a workaround to aid development on non-numbered userdebug
3369        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3370        // the system partition is newer.
3371        //
3372        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3373        // that starts with "eng." to signify that this is an engineering build and not
3374        // destined for release.
3375        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3376            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3377
3378            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3379            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3380            // in general and should not be used for production changes. In this specific case,
3381            // we know that they will work.
3382            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3383            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3384                FileUtils.deleteContents(cacheBaseDir);
3385                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3386            }
3387        }
3388
3389        return cacheDir;
3390    }
3391
3392    @Override
3393    public boolean isFirstBoot() {
3394        // allow instant applications
3395        return mFirstBoot;
3396    }
3397
3398    @Override
3399    public boolean isOnlyCoreApps() {
3400        // allow instant applications
3401        return mOnlyCore;
3402    }
3403
3404    @Override
3405    public boolean isUpgrade() {
3406        // allow instant applications
3407        return mIsUpgrade;
3408    }
3409
3410    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3411        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3412
3413        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3414                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3415                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3416        if (matches.size() == 1) {
3417            return matches.get(0).getComponentInfo().packageName;
3418        } else if (matches.size() == 0) {
3419            Log.e(TAG, "There should probably be a verifier, but, none were found");
3420            return null;
3421        }
3422        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3423    }
3424
3425    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3426        synchronized (mPackages) {
3427            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3428            if (libraryEntry == null) {
3429                throw new IllegalStateException("Missing required shared library:" + name);
3430            }
3431            return libraryEntry.apk;
3432        }
3433    }
3434
3435    private @NonNull String getRequiredInstallerLPr() {
3436        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3437        intent.addCategory(Intent.CATEGORY_DEFAULT);
3438        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3439
3440        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3441                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3442                UserHandle.USER_SYSTEM);
3443        if (matches.size() == 1) {
3444            ResolveInfo resolveInfo = matches.get(0);
3445            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3446                throw new RuntimeException("The installer must be a privileged app");
3447            }
3448            return matches.get(0).getComponentInfo().packageName;
3449        } else {
3450            throw new RuntimeException("There must be exactly one installer; found " + matches);
3451        }
3452    }
3453
3454    private @NonNull String getRequiredUninstallerLPr() {
3455        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3456        intent.addCategory(Intent.CATEGORY_DEFAULT);
3457        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3458
3459        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3460                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3461                UserHandle.USER_SYSTEM);
3462        if (resolveInfo == null ||
3463                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3464            throw new RuntimeException("There must be exactly one uninstaller; found "
3465                    + resolveInfo);
3466        }
3467        return resolveInfo.getComponentInfo().packageName;
3468    }
3469
3470    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3471        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3472
3473        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3474                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3475                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3476        ResolveInfo best = null;
3477        final int N = matches.size();
3478        for (int i = 0; i < N; i++) {
3479            final ResolveInfo cur = matches.get(i);
3480            final String packageName = cur.getComponentInfo().packageName;
3481            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3482                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3483                continue;
3484            }
3485
3486            if (best == null || cur.priority > best.priority) {
3487                best = cur;
3488            }
3489        }
3490
3491        if (best != null) {
3492            return best.getComponentInfo().getComponentName();
3493        }
3494        Slog.w(TAG, "Intent filter verifier not found");
3495        return null;
3496    }
3497
3498    @Override
3499    public @Nullable ComponentName getInstantAppResolverComponent() {
3500        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3501            return null;
3502        }
3503        synchronized (mPackages) {
3504            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3505            if (instantAppResolver == null) {
3506                return null;
3507            }
3508            return instantAppResolver.first;
3509        }
3510    }
3511
3512    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3513        final String[] packageArray =
3514                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3515        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3516            if (DEBUG_EPHEMERAL) {
3517                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3518            }
3519            return null;
3520        }
3521
3522        final int callingUid = Binder.getCallingUid();
3523        final int resolveFlags =
3524                MATCH_DIRECT_BOOT_AWARE
3525                | MATCH_DIRECT_BOOT_UNAWARE
3526                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3527        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3528        final Intent resolverIntent = new Intent(actionName);
3529        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3530                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3531        // temporarily look for the old action
3532        if (resolvers.size() == 0) {
3533            if (DEBUG_EPHEMERAL) {
3534                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3535            }
3536            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3537            resolverIntent.setAction(actionName);
3538            resolvers = queryIntentServicesInternal(resolverIntent, null,
3539                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3540        }
3541        final int N = resolvers.size();
3542        if (N == 0) {
3543            if (DEBUG_EPHEMERAL) {
3544                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3545            }
3546            return null;
3547        }
3548
3549        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3550        for (int i = 0; i < N; i++) {
3551            final ResolveInfo info = resolvers.get(i);
3552
3553            if (info.serviceInfo == null) {
3554                continue;
3555            }
3556
3557            final String packageName = info.serviceInfo.packageName;
3558            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3559                if (DEBUG_EPHEMERAL) {
3560                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3561                            + " pkg: " + packageName + ", info:" + info);
3562                }
3563                continue;
3564            }
3565
3566            if (DEBUG_EPHEMERAL) {
3567                Slog.v(TAG, "Ephemeral resolver found;"
3568                        + " pkg: " + packageName + ", info:" + info);
3569            }
3570            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3571        }
3572        if (DEBUG_EPHEMERAL) {
3573            Slog.v(TAG, "Ephemeral resolver NOT found");
3574        }
3575        return null;
3576    }
3577
3578    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3579        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3580        intent.addCategory(Intent.CATEGORY_DEFAULT);
3581        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3582
3583        final int resolveFlags =
3584                MATCH_DIRECT_BOOT_AWARE
3585                | MATCH_DIRECT_BOOT_UNAWARE
3586                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3587        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3588                resolveFlags, UserHandle.USER_SYSTEM);
3589        // temporarily look for the old action
3590        if (matches.isEmpty()) {
3591            if (DEBUG_EPHEMERAL) {
3592                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3593            }
3594            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3595            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3596                    resolveFlags, UserHandle.USER_SYSTEM);
3597        }
3598        Iterator<ResolveInfo> iter = matches.iterator();
3599        while (iter.hasNext()) {
3600            final ResolveInfo rInfo = iter.next();
3601            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3602            if (ps != null) {
3603                final PermissionsState permissionsState = ps.getPermissionsState();
3604                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3605                    continue;
3606                }
3607            }
3608            iter.remove();
3609        }
3610        if (matches.size() == 0) {
3611            return null;
3612        } else if (matches.size() == 1) {
3613            return (ActivityInfo) matches.get(0).getComponentInfo();
3614        } else {
3615            throw new RuntimeException(
3616                    "There must be at most one ephemeral installer; found " + matches);
3617        }
3618    }
3619
3620    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3621            @NonNull ComponentName resolver) {
3622        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3623                .addCategory(Intent.CATEGORY_DEFAULT)
3624                .setPackage(resolver.getPackageName());
3625        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3626        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3627                UserHandle.USER_SYSTEM);
3628        // temporarily look for the old action
3629        if (matches.isEmpty()) {
3630            if (DEBUG_EPHEMERAL) {
3631                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3632            }
3633            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3634            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3635                    UserHandle.USER_SYSTEM);
3636        }
3637        if (matches.isEmpty()) {
3638            return null;
3639        }
3640        return matches.get(0).getComponentInfo().getComponentName();
3641    }
3642
3643    private void primeDomainVerificationsLPw(int userId) {
3644        if (DEBUG_DOMAIN_VERIFICATION) {
3645            Slog.d(TAG, "Priming domain verifications in user " + userId);
3646        }
3647
3648        SystemConfig systemConfig = SystemConfig.getInstance();
3649        ArraySet<String> packages = systemConfig.getLinkedApps();
3650
3651        for (String packageName : packages) {
3652            PackageParser.Package pkg = mPackages.get(packageName);
3653            if (pkg != null) {
3654                if (!pkg.isSystemApp()) {
3655                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3656                    continue;
3657                }
3658
3659                ArraySet<String> domains = null;
3660                for (PackageParser.Activity a : pkg.activities) {
3661                    for (ActivityIntentInfo filter : a.intents) {
3662                        if (hasValidDomains(filter)) {
3663                            if (domains == null) {
3664                                domains = new ArraySet<String>();
3665                            }
3666                            domains.addAll(filter.getHostsList());
3667                        }
3668                    }
3669                }
3670
3671                if (domains != null && domains.size() > 0) {
3672                    if (DEBUG_DOMAIN_VERIFICATION) {
3673                        Slog.v(TAG, "      + " + packageName);
3674                    }
3675                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3676                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3677                    // and then 'always' in the per-user state actually used for intent resolution.
3678                    final IntentFilterVerificationInfo ivi;
3679                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3680                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3681                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3682                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3683                } else {
3684                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3685                            + "' does not handle web links");
3686                }
3687            } else {
3688                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3689            }
3690        }
3691
3692        scheduleWritePackageRestrictionsLocked(userId);
3693        scheduleWriteSettingsLocked();
3694    }
3695
3696    private void applyFactoryDefaultBrowserLPw(int userId) {
3697        // The default browser app's package name is stored in a string resource,
3698        // with a product-specific overlay used for vendor customization.
3699        String browserPkg = mContext.getResources().getString(
3700                com.android.internal.R.string.default_browser);
3701        if (!TextUtils.isEmpty(browserPkg)) {
3702            // non-empty string => required to be a known package
3703            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3704            if (ps == null) {
3705                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3706                browserPkg = null;
3707            } else {
3708                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3709            }
3710        }
3711
3712        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3713        // default.  If there's more than one, just leave everything alone.
3714        if (browserPkg == null) {
3715            calculateDefaultBrowserLPw(userId);
3716        }
3717    }
3718
3719    private void calculateDefaultBrowserLPw(int userId) {
3720        List<String> allBrowsers = resolveAllBrowserApps(userId);
3721        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3722        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3723    }
3724
3725    private List<String> resolveAllBrowserApps(int userId) {
3726        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3727        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3728                PackageManager.MATCH_ALL, userId);
3729
3730        final int count = list.size();
3731        List<String> result = new ArrayList<String>(count);
3732        for (int i=0; i<count; i++) {
3733            ResolveInfo info = list.get(i);
3734            if (info.activityInfo == null
3735                    || !info.handleAllWebDataURI
3736                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3737                    || result.contains(info.activityInfo.packageName)) {
3738                continue;
3739            }
3740            result.add(info.activityInfo.packageName);
3741        }
3742
3743        return result;
3744    }
3745
3746    private boolean packageIsBrowser(String packageName, int userId) {
3747        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3748                PackageManager.MATCH_ALL, userId);
3749        final int N = list.size();
3750        for (int i = 0; i < N; i++) {
3751            ResolveInfo info = list.get(i);
3752            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3753                return true;
3754            }
3755        }
3756        return false;
3757    }
3758
3759    private void checkDefaultBrowser() {
3760        final int myUserId = UserHandle.myUserId();
3761        final String packageName = getDefaultBrowserPackageName(myUserId);
3762        if (packageName != null) {
3763            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3764            if (info == null) {
3765                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3766                synchronized (mPackages) {
3767                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3768                }
3769            }
3770        }
3771    }
3772
3773    @Override
3774    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3775            throws RemoteException {
3776        try {
3777            return super.onTransact(code, data, reply, flags);
3778        } catch (RuntimeException e) {
3779            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3780                Slog.wtf(TAG, "Package Manager Crash", e);
3781            }
3782            throw e;
3783        }
3784    }
3785
3786    static int[] appendInts(int[] cur, int[] add) {
3787        if (add == null) return cur;
3788        if (cur == null) return add;
3789        final int N = add.length;
3790        for (int i=0; i<N; i++) {
3791            cur = appendInt(cur, add[i]);
3792        }
3793        return cur;
3794    }
3795
3796    /**
3797     * Returns whether or not a full application can see an instant application.
3798     * <p>
3799     * Currently, there are three cases in which this can occur:
3800     * <ol>
3801     * <li>The calling application is a "special" process. The special
3802     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3803     *     and {@code 0}</li>
3804     * <li>The calling application has the permission
3805     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3806     * <li>The calling application is the default launcher on the
3807     *     system partition.</li>
3808     * </ol>
3809     */
3810    private boolean canViewInstantApps(int callingUid, int userId) {
3811        if (callingUid == Process.SYSTEM_UID
3812                || callingUid == Process.SHELL_UID
3813                || callingUid == Process.ROOT_UID) {
3814            return true;
3815        }
3816        if (mContext.checkCallingOrSelfPermission(
3817                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3818            return true;
3819        }
3820        if (mContext.checkCallingOrSelfPermission(
3821                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3822            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3823            if (homeComponent != null
3824                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3825                return true;
3826            }
3827        }
3828        return false;
3829    }
3830
3831    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3832        if (!sUserManager.exists(userId)) return null;
3833        if (ps == null) {
3834            return null;
3835        }
3836        PackageParser.Package p = ps.pkg;
3837        if (p == null) {
3838            return null;
3839        }
3840        final int callingUid = Binder.getCallingUid();
3841        // Filter out ephemeral app metadata:
3842        //   * The system/shell/root can see metadata for any app
3843        //   * An installed app can see metadata for 1) other installed apps
3844        //     and 2) ephemeral apps that have explicitly interacted with it
3845        //   * Ephemeral apps can only see their own data and exposed installed apps
3846        //   * Holding a signature permission allows seeing instant apps
3847        if (filterAppAccessLPr(ps, callingUid, userId)) {
3848            return null;
3849        }
3850
3851        final PermissionsState permissionsState = ps.getPermissionsState();
3852
3853        // Compute GIDs only if requested
3854        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3855                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3856        // Compute granted permissions only if package has requested permissions
3857        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3858                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3859        final PackageUserState state = ps.readUserState(userId);
3860
3861        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3862                && ps.isSystem()) {
3863            flags |= MATCH_ANY_USER;
3864        }
3865
3866        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3867                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3868
3869        if (packageInfo == null) {
3870            return null;
3871        }
3872
3873        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3874                resolveExternalPackageNameLPr(p);
3875
3876        return packageInfo;
3877    }
3878
3879    @Override
3880    public void checkPackageStartable(String packageName, int userId) {
3881        final int callingUid = Binder.getCallingUid();
3882        if (getInstantAppPackageName(callingUid) != null) {
3883            throw new SecurityException("Instant applications don't have access to this method");
3884        }
3885        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3886        synchronized (mPackages) {
3887            final PackageSetting ps = mSettings.mPackages.get(packageName);
3888            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3889                throw new SecurityException("Package " + packageName + " was not found!");
3890            }
3891
3892            if (!ps.getInstalled(userId)) {
3893                throw new SecurityException(
3894                        "Package " + packageName + " was not installed for user " + userId + "!");
3895            }
3896
3897            if (mSafeMode && !ps.isSystem()) {
3898                throw new SecurityException("Package " + packageName + " not a system app!");
3899            }
3900
3901            if (mFrozenPackages.contains(packageName)) {
3902                throw new SecurityException("Package " + packageName + " is currently frozen!");
3903            }
3904
3905            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3906                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3907            }
3908        }
3909    }
3910
3911    @Override
3912    public boolean isPackageAvailable(String packageName, int userId) {
3913        if (!sUserManager.exists(userId)) return false;
3914        final int callingUid = Binder.getCallingUid();
3915        enforceCrossUserPermission(callingUid, userId,
3916                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3917        synchronized (mPackages) {
3918            PackageParser.Package p = mPackages.get(packageName);
3919            if (p != null) {
3920                final PackageSetting ps = (PackageSetting) p.mExtras;
3921                if (filterAppAccessLPr(ps, callingUid, userId)) {
3922                    return false;
3923                }
3924                if (ps != null) {
3925                    final PackageUserState state = ps.readUserState(userId);
3926                    if (state != null) {
3927                        return PackageParser.isAvailable(state);
3928                    }
3929                }
3930            }
3931        }
3932        return false;
3933    }
3934
3935    @Override
3936    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3937        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3938                flags, Binder.getCallingUid(), userId);
3939    }
3940
3941    @Override
3942    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3943            int flags, int userId) {
3944        return getPackageInfoInternal(versionedPackage.getPackageName(),
3945                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3946    }
3947
3948    /**
3949     * Important: The provided filterCallingUid is used exclusively to filter out packages
3950     * that can be seen based on user state. It's typically the original caller uid prior
3951     * to clearing. Because it can only be provided by trusted code, it's value can be
3952     * trusted and will be used as-is; unlike userId which will be validated by this method.
3953     */
3954    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3955            int flags, int filterCallingUid, int userId) {
3956        if (!sUserManager.exists(userId)) return null;
3957        flags = updateFlagsForPackage(flags, userId, packageName);
3958        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3959                false /* requireFullPermission */, false /* checkShell */, "get package info");
3960
3961        // reader
3962        synchronized (mPackages) {
3963            // Normalize package name to handle renamed packages and static libs
3964            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3965
3966            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3967            if (matchFactoryOnly) {
3968                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3969                if (ps != null) {
3970                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3971                        return null;
3972                    }
3973                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3974                        return null;
3975                    }
3976                    return generatePackageInfo(ps, flags, userId);
3977                }
3978            }
3979
3980            PackageParser.Package p = mPackages.get(packageName);
3981            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3982                return null;
3983            }
3984            if (DEBUG_PACKAGE_INFO)
3985                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3986            if (p != null) {
3987                final PackageSetting ps = (PackageSetting) p.mExtras;
3988                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3989                    return null;
3990                }
3991                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3992                    return null;
3993                }
3994                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3995            }
3996            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3997                final PackageSetting ps = mSettings.mPackages.get(packageName);
3998                if (ps == null) return null;
3999                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4000                    return null;
4001                }
4002                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4003                    return null;
4004                }
4005                return generatePackageInfo(ps, flags, userId);
4006            }
4007        }
4008        return null;
4009    }
4010
4011    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4012        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4013            return true;
4014        }
4015        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4016            return true;
4017        }
4018        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4019            return true;
4020        }
4021        return false;
4022    }
4023
4024    private boolean isComponentVisibleToInstantApp(
4025            @Nullable ComponentName component, @ComponentType int type) {
4026        if (type == TYPE_ACTIVITY) {
4027            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4028            return activity != null
4029                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4030                    : false;
4031        } else if (type == TYPE_RECEIVER) {
4032            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4033            return activity != null
4034                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4035                    : false;
4036        } else if (type == TYPE_SERVICE) {
4037            final PackageParser.Service service = mServices.mServices.get(component);
4038            return service != null
4039                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4040                    : false;
4041        } else if (type == TYPE_PROVIDER) {
4042            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4043            return provider != null
4044                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4045                    : false;
4046        } else if (type == TYPE_UNKNOWN) {
4047            return isComponentVisibleToInstantApp(component);
4048        }
4049        return false;
4050    }
4051
4052    /**
4053     * Returns whether or not access to the application should be filtered.
4054     * <p>
4055     * Access may be limited based upon whether the calling or target applications
4056     * are instant applications.
4057     *
4058     * @see #canAccessInstantApps(int)
4059     */
4060    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4061            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4062        // if we're in an isolated process, get the real calling UID
4063        if (Process.isIsolated(callingUid)) {
4064            callingUid = mIsolatedOwners.get(callingUid);
4065        }
4066        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4067        final boolean callerIsInstantApp = instantAppPkgName != null;
4068        if (ps == null) {
4069            if (callerIsInstantApp) {
4070                // pretend the application exists, but, needs to be filtered
4071                return true;
4072            }
4073            return false;
4074        }
4075        // if the target and caller are the same application, don't filter
4076        if (isCallerSameApp(ps.name, callingUid)) {
4077            return false;
4078        }
4079        if (callerIsInstantApp) {
4080            // request for a specific component; if it hasn't been explicitly exposed, filter
4081            if (component != null) {
4082                return !isComponentVisibleToInstantApp(component, componentType);
4083            }
4084            // request for application; if no components have been explicitly exposed, filter
4085            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4086        }
4087        if (ps.getInstantApp(userId)) {
4088            // caller can see all components of all instant applications, don't filter
4089            if (canViewInstantApps(callingUid, userId)) {
4090                return false;
4091            }
4092            // request for a specific instant application component, filter
4093            if (component != null) {
4094                return true;
4095            }
4096            // request for an instant application; if the caller hasn't been granted access, filter
4097            return !mInstantAppRegistry.isInstantAccessGranted(
4098                    userId, UserHandle.getAppId(callingUid), ps.appId);
4099        }
4100        return false;
4101    }
4102
4103    /**
4104     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4105     */
4106    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4107        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4108    }
4109
4110    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4111            int flags) {
4112        // Callers can access only the libs they depend on, otherwise they need to explicitly
4113        // ask for the shared libraries given the caller is allowed to access all static libs.
4114        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4115            // System/shell/root get to see all static libs
4116            final int appId = UserHandle.getAppId(uid);
4117            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4118                    || appId == Process.ROOT_UID) {
4119                return false;
4120            }
4121        }
4122
4123        // No package means no static lib as it is always on internal storage
4124        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4125            return false;
4126        }
4127
4128        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4129                ps.pkg.staticSharedLibVersion);
4130        if (libEntry == null) {
4131            return false;
4132        }
4133
4134        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4135        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4136        if (uidPackageNames == null) {
4137            return true;
4138        }
4139
4140        for (String uidPackageName : uidPackageNames) {
4141            if (ps.name.equals(uidPackageName)) {
4142                return false;
4143            }
4144            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4145            if (uidPs != null) {
4146                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4147                        libEntry.info.getName());
4148                if (index < 0) {
4149                    continue;
4150                }
4151                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4152                    return false;
4153                }
4154            }
4155        }
4156        return true;
4157    }
4158
4159    @Override
4160    public String[] currentToCanonicalPackageNames(String[] names) {
4161        final int callingUid = Binder.getCallingUid();
4162        if (getInstantAppPackageName(callingUid) != null) {
4163            return names;
4164        }
4165        final String[] out = new String[names.length];
4166        // reader
4167        synchronized (mPackages) {
4168            final int callingUserId = UserHandle.getUserId(callingUid);
4169            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4170            for (int i=names.length-1; i>=0; i--) {
4171                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4172                boolean translateName = false;
4173                if (ps != null && ps.realName != null) {
4174                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4175                    translateName = !targetIsInstantApp
4176                            || canViewInstantApps
4177                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4178                                    UserHandle.getAppId(callingUid), ps.appId);
4179                }
4180                out[i] = translateName ? ps.realName : names[i];
4181            }
4182        }
4183        return out;
4184    }
4185
4186    @Override
4187    public String[] canonicalToCurrentPackageNames(String[] names) {
4188        final int callingUid = Binder.getCallingUid();
4189        if (getInstantAppPackageName(callingUid) != null) {
4190            return names;
4191        }
4192        final String[] out = new String[names.length];
4193        // reader
4194        synchronized (mPackages) {
4195            final int callingUserId = UserHandle.getUserId(callingUid);
4196            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4197            for (int i=names.length-1; i>=0; i--) {
4198                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4199                boolean translateName = false;
4200                if (cur != null) {
4201                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4202                    final boolean targetIsInstantApp =
4203                            ps != null && ps.getInstantApp(callingUserId);
4204                    translateName = !targetIsInstantApp
4205                            || canViewInstantApps
4206                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4207                                    UserHandle.getAppId(callingUid), ps.appId);
4208                }
4209                out[i] = translateName ? cur : names[i];
4210            }
4211        }
4212        return out;
4213    }
4214
4215    @Override
4216    public int getPackageUid(String packageName, int flags, int userId) {
4217        if (!sUserManager.exists(userId)) return -1;
4218        final int callingUid = Binder.getCallingUid();
4219        flags = updateFlagsForPackage(flags, userId, packageName);
4220        enforceCrossUserPermission(callingUid, userId,
4221                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4222
4223        // reader
4224        synchronized (mPackages) {
4225            final PackageParser.Package p = mPackages.get(packageName);
4226            if (p != null && p.isMatch(flags)) {
4227                PackageSetting ps = (PackageSetting) p.mExtras;
4228                if (filterAppAccessLPr(ps, callingUid, userId)) {
4229                    return -1;
4230                }
4231                return UserHandle.getUid(userId, p.applicationInfo.uid);
4232            }
4233            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4234                final PackageSetting ps = mSettings.mPackages.get(packageName);
4235                if (ps != null && ps.isMatch(flags)
4236                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4237                    return UserHandle.getUid(userId, ps.appId);
4238                }
4239            }
4240        }
4241
4242        return -1;
4243    }
4244
4245    @Override
4246    public int[] getPackageGids(String packageName, int flags, int userId) {
4247        if (!sUserManager.exists(userId)) return null;
4248        final int callingUid = Binder.getCallingUid();
4249        flags = updateFlagsForPackage(flags, userId, packageName);
4250        enforceCrossUserPermission(callingUid, userId,
4251                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4252
4253        // reader
4254        synchronized (mPackages) {
4255            final PackageParser.Package p = mPackages.get(packageName);
4256            if (p != null && p.isMatch(flags)) {
4257                PackageSetting ps = (PackageSetting) p.mExtras;
4258                if (filterAppAccessLPr(ps, callingUid, userId)) {
4259                    return null;
4260                }
4261                // TODO: Shouldn't this be checking for package installed state for userId and
4262                // return null?
4263                return ps.getPermissionsState().computeGids(userId);
4264            }
4265            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4266                final PackageSetting ps = mSettings.mPackages.get(packageName);
4267                if (ps != null && ps.isMatch(flags)
4268                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4269                    return ps.getPermissionsState().computeGids(userId);
4270                }
4271            }
4272        }
4273
4274        return null;
4275    }
4276
4277    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4278        if (bp.perm != null) {
4279            return PackageParser.generatePermissionInfo(bp.perm, flags);
4280        }
4281        PermissionInfo pi = new PermissionInfo();
4282        pi.name = bp.name;
4283        pi.packageName = bp.sourcePackage;
4284        pi.nonLocalizedLabel = bp.name;
4285        pi.protectionLevel = bp.protectionLevel;
4286        return pi;
4287    }
4288
4289    @Override
4290    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4291        final int callingUid = Binder.getCallingUid();
4292        if (getInstantAppPackageName(callingUid) != null) {
4293            return null;
4294        }
4295        // reader
4296        synchronized (mPackages) {
4297            final BasePermission p = mSettings.mPermissions.get(name);
4298            if (p == null) {
4299                return null;
4300            }
4301            // If the caller is an app that targets pre 26 SDK drop protection flags.
4302            PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4303            if (permissionInfo != null) {
4304                final int protectionLevel = adjustPermissionProtectionFlagsLPr(
4305                        permissionInfo.protectionLevel, packageName, callingUid);
4306                if (permissionInfo.protectionLevel != protectionLevel) {
4307                    // If we return different protection level, don't use the cached info
4308                    if (p.perm != null && p.perm.info == permissionInfo) {
4309                        permissionInfo = new PermissionInfo(permissionInfo);
4310                    }
4311                    permissionInfo.protectionLevel = protectionLevel;
4312                }
4313            }
4314            return permissionInfo;
4315        }
4316    }
4317
4318    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4319            String packageName, int uid) {
4320        // Signature permission flags area always reported
4321        final int protectionLevelMasked = protectionLevel
4322                & (PermissionInfo.PROTECTION_NORMAL
4323                | PermissionInfo.PROTECTION_DANGEROUS
4324                | PermissionInfo.PROTECTION_SIGNATURE);
4325        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4326            return protectionLevel;
4327        }
4328
4329        // System sees all flags.
4330        final int appId = UserHandle.getAppId(uid);
4331        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4332                || appId == Process.SHELL_UID) {
4333            return protectionLevel;
4334        }
4335
4336        // Normalize package name to handle renamed packages and static libs
4337        packageName = resolveInternalPackageNameLPr(packageName,
4338                PackageManager.VERSION_CODE_HIGHEST);
4339
4340        // Apps that target O see flags for all protection levels.
4341        final PackageSetting ps = mSettings.mPackages.get(packageName);
4342        if (ps == null) {
4343            return protectionLevel;
4344        }
4345        if (ps.appId != appId) {
4346            return protectionLevel;
4347        }
4348
4349        final PackageParser.Package pkg = mPackages.get(packageName);
4350        if (pkg == null) {
4351            return protectionLevel;
4352        }
4353        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4354            return protectionLevelMasked;
4355        }
4356
4357        return protectionLevel;
4358    }
4359
4360    @Override
4361    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4362            int flags) {
4363        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4364            return null;
4365        }
4366        // reader
4367        synchronized (mPackages) {
4368            if (group != null && !mPermissionGroups.containsKey(group)) {
4369                // This is thrown as NameNotFoundException
4370                return null;
4371            }
4372
4373            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4374            for (BasePermission p : mSettings.mPermissions.values()) {
4375                if (group == null) {
4376                    if (p.perm == null || p.perm.info.group == null) {
4377                        out.add(generatePermissionInfo(p, flags));
4378                    }
4379                } else {
4380                    if (p.perm != null && group.equals(p.perm.info.group)) {
4381                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4382                    }
4383                }
4384            }
4385            return new ParceledListSlice<>(out);
4386        }
4387    }
4388
4389    @Override
4390    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4391        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4392            return null;
4393        }
4394        // reader
4395        synchronized (mPackages) {
4396            return PackageParser.generatePermissionGroupInfo(
4397                    mPermissionGroups.get(name), flags);
4398        }
4399    }
4400
4401    @Override
4402    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4403        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4404            return ParceledListSlice.emptyList();
4405        }
4406        // reader
4407        synchronized (mPackages) {
4408            final int N = mPermissionGroups.size();
4409            ArrayList<PermissionGroupInfo> out
4410                    = new ArrayList<PermissionGroupInfo>(N);
4411            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4412                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4413            }
4414            return new ParceledListSlice<>(out);
4415        }
4416    }
4417
4418    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4419            int filterCallingUid, int userId) {
4420        if (!sUserManager.exists(userId)) return null;
4421        PackageSetting ps = mSettings.mPackages.get(packageName);
4422        if (ps != null) {
4423            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4424                return null;
4425            }
4426            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4427                return null;
4428            }
4429            if (ps.pkg == null) {
4430                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4431                if (pInfo != null) {
4432                    return pInfo.applicationInfo;
4433                }
4434                return null;
4435            }
4436            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4437                    ps.readUserState(userId), userId);
4438            if (ai != null) {
4439                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4440            }
4441            return ai;
4442        }
4443        return null;
4444    }
4445
4446    @Override
4447    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4448        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4449    }
4450
4451    /**
4452     * Important: The provided filterCallingUid is used exclusively to filter out applications
4453     * that can be seen based on user state. It's typically the original caller uid prior
4454     * to clearing. Because it can only be provided by trusted code, it's value can be
4455     * trusted and will be used as-is; unlike userId which will be validated by this method.
4456     */
4457    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4458            int filterCallingUid, int userId) {
4459        if (!sUserManager.exists(userId)) return null;
4460        flags = updateFlagsForApplication(flags, userId, packageName);
4461        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4462                false /* requireFullPermission */, false /* checkShell */, "get application info");
4463
4464        // writer
4465        synchronized (mPackages) {
4466            // Normalize package name to handle renamed packages and static libs
4467            packageName = resolveInternalPackageNameLPr(packageName,
4468                    PackageManager.VERSION_CODE_HIGHEST);
4469
4470            PackageParser.Package p = mPackages.get(packageName);
4471            if (DEBUG_PACKAGE_INFO) Log.v(
4472                    TAG, "getApplicationInfo " + packageName
4473                    + ": " + p);
4474            if (p != null) {
4475                PackageSetting ps = mSettings.mPackages.get(packageName);
4476                if (ps == null) return null;
4477                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4478                    return null;
4479                }
4480                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4481                    return null;
4482                }
4483                // Note: isEnabledLP() does not apply here - always return info
4484                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4485                        p, flags, ps.readUserState(userId), userId);
4486                if (ai != null) {
4487                    ai.packageName = resolveExternalPackageNameLPr(p);
4488                }
4489                return ai;
4490            }
4491            if ("android".equals(packageName)||"system".equals(packageName)) {
4492                return mAndroidApplication;
4493            }
4494            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4495                // Already generates the external package name
4496                return generateApplicationInfoFromSettingsLPw(packageName,
4497                        flags, filterCallingUid, userId);
4498            }
4499        }
4500        return null;
4501    }
4502
4503    private String normalizePackageNameLPr(String packageName) {
4504        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4505        return normalizedPackageName != null ? normalizedPackageName : packageName;
4506    }
4507
4508    @Override
4509    public void deletePreloadsFileCache() {
4510        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4511            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4512        }
4513        File dir = Environment.getDataPreloadsFileCacheDirectory();
4514        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4515        FileUtils.deleteContents(dir);
4516    }
4517
4518    @Override
4519    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4520            final int storageFlags, final IPackageDataObserver observer) {
4521        mContext.enforceCallingOrSelfPermission(
4522                android.Manifest.permission.CLEAR_APP_CACHE, null);
4523        mHandler.post(() -> {
4524            boolean success = false;
4525            try {
4526                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4527                success = true;
4528            } catch (IOException e) {
4529                Slog.w(TAG, e);
4530            }
4531            if (observer != null) {
4532                try {
4533                    observer.onRemoveCompleted(null, success);
4534                } catch (RemoteException e) {
4535                    Slog.w(TAG, e);
4536                }
4537            }
4538        });
4539    }
4540
4541    @Override
4542    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4543            final int storageFlags, final IntentSender pi) {
4544        mContext.enforceCallingOrSelfPermission(
4545                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4546        mHandler.post(() -> {
4547            boolean success = false;
4548            try {
4549                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4550                success = true;
4551            } catch (IOException e) {
4552                Slog.w(TAG, e);
4553            }
4554            if (pi != null) {
4555                try {
4556                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4557                } catch (SendIntentException e) {
4558                    Slog.w(TAG, e);
4559                }
4560            }
4561        });
4562    }
4563
4564    /**
4565     * Blocking call to clear various types of cached data across the system
4566     * until the requested bytes are available.
4567     */
4568    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4569        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4570        final File file = storage.findPathForUuid(volumeUuid);
4571        if (file.getUsableSpace() >= bytes) return;
4572
4573        if (ENABLE_FREE_CACHE_V2) {
4574            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4575                    volumeUuid);
4576            final boolean aggressive = (storageFlags
4577                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4578            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4579
4580            // 1. Pre-flight to determine if we have any chance to succeed
4581            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4582            if (internalVolume && (aggressive || SystemProperties
4583                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4584                deletePreloadsFileCache();
4585                if (file.getUsableSpace() >= bytes) return;
4586            }
4587
4588            // 3. Consider parsed APK data (aggressive only)
4589            if (internalVolume && aggressive) {
4590                FileUtils.deleteContents(mCacheDir);
4591                if (file.getUsableSpace() >= bytes) return;
4592            }
4593
4594            // 4. Consider cached app data (above quotas)
4595            try {
4596                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4597                        Installer.FLAG_FREE_CACHE_V2);
4598            } catch (InstallerException ignored) {
4599            }
4600            if (file.getUsableSpace() >= bytes) return;
4601
4602            // 5. Consider shared libraries with refcount=0 and age>min cache period
4603            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4604                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4605                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4606                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4607                return;
4608            }
4609
4610            // 6. Consider dexopt output (aggressive only)
4611            // TODO: Implement
4612
4613            // 7. Consider installed instant apps unused longer than min cache period
4614            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4615                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4616                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4617                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4618                return;
4619            }
4620
4621            // 8. Consider cached app data (below quotas)
4622            try {
4623                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4624                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4625            } catch (InstallerException ignored) {
4626            }
4627            if (file.getUsableSpace() >= bytes) return;
4628
4629            // 9. Consider DropBox entries
4630            // TODO: Implement
4631
4632            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4633            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4634                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4635                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4636                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4637                return;
4638            }
4639        } else {
4640            try {
4641                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4642            } catch (InstallerException ignored) {
4643            }
4644            if (file.getUsableSpace() >= bytes) return;
4645        }
4646
4647        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4648    }
4649
4650    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4651            throws IOException {
4652        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4653        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4654
4655        List<VersionedPackage> packagesToDelete = null;
4656        final long now = System.currentTimeMillis();
4657
4658        synchronized (mPackages) {
4659            final int[] allUsers = sUserManager.getUserIds();
4660            final int libCount = mSharedLibraries.size();
4661            for (int i = 0; i < libCount; i++) {
4662                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4663                if (versionedLib == null) {
4664                    continue;
4665                }
4666                final int versionCount = versionedLib.size();
4667                for (int j = 0; j < versionCount; j++) {
4668                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4669                    // Skip packages that are not static shared libs.
4670                    if (!libInfo.isStatic()) {
4671                        break;
4672                    }
4673                    // Important: We skip static shared libs used for some user since
4674                    // in such a case we need to keep the APK on the device. The check for
4675                    // a lib being used for any user is performed by the uninstall call.
4676                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4677                    // Resolve the package name - we use synthetic package names internally
4678                    final String internalPackageName = resolveInternalPackageNameLPr(
4679                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4680                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4681                    // Skip unused static shared libs cached less than the min period
4682                    // to prevent pruning a lib needed by a subsequently installed package.
4683                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4684                        continue;
4685                    }
4686                    if (packagesToDelete == null) {
4687                        packagesToDelete = new ArrayList<>();
4688                    }
4689                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4690                            declaringPackage.getVersionCode()));
4691                }
4692            }
4693        }
4694
4695        if (packagesToDelete != null) {
4696            final int packageCount = packagesToDelete.size();
4697            for (int i = 0; i < packageCount; i++) {
4698                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4699                // Delete the package synchronously (will fail of the lib used for any user).
4700                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4701                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4702                                == PackageManager.DELETE_SUCCEEDED) {
4703                    if (volume.getUsableSpace() >= neededSpace) {
4704                        return true;
4705                    }
4706                }
4707            }
4708        }
4709
4710        return false;
4711    }
4712
4713    /**
4714     * Update given flags based on encryption status of current user.
4715     */
4716    private int updateFlags(int flags, int userId) {
4717        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4718                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4719            // Caller expressed an explicit opinion about what encryption
4720            // aware/unaware components they want to see, so fall through and
4721            // give them what they want
4722        } else {
4723            // Caller expressed no opinion, so match based on user state
4724            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4725                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4726            } else {
4727                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4728            }
4729        }
4730        return flags;
4731    }
4732
4733    private UserManagerInternal getUserManagerInternal() {
4734        if (mUserManagerInternal == null) {
4735            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4736        }
4737        return mUserManagerInternal;
4738    }
4739
4740    private DeviceIdleController.LocalService getDeviceIdleController() {
4741        if (mDeviceIdleController == null) {
4742            mDeviceIdleController =
4743                    LocalServices.getService(DeviceIdleController.LocalService.class);
4744        }
4745        return mDeviceIdleController;
4746    }
4747
4748    /**
4749     * Update given flags when being used to request {@link PackageInfo}.
4750     */
4751    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4752        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4753        boolean triaged = true;
4754        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4755                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4756            // Caller is asking for component details, so they'd better be
4757            // asking for specific encryption matching behavior, or be triaged
4758            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4759                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4760                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4761                triaged = false;
4762            }
4763        }
4764        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4765                | PackageManager.MATCH_SYSTEM_ONLY
4766                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4767            triaged = false;
4768        }
4769        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4770            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4771                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4772                    + Debug.getCallers(5));
4773        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4774                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4775            // If the caller wants all packages and has a restricted profile associated with it,
4776            // then match all users. This is to make sure that launchers that need to access work
4777            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4778            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4779            flags |= PackageManager.MATCH_ANY_USER;
4780        }
4781        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4782            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4783                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4784        }
4785        return updateFlags(flags, userId);
4786    }
4787
4788    /**
4789     * Update given flags when being used to request {@link ApplicationInfo}.
4790     */
4791    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4792        return updateFlagsForPackage(flags, userId, cookie);
4793    }
4794
4795    /**
4796     * Update given flags when being used to request {@link ComponentInfo}.
4797     */
4798    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4799        if (cookie instanceof Intent) {
4800            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4801                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4802            }
4803        }
4804
4805        boolean triaged = true;
4806        // Caller is asking for component details, so they'd better be
4807        // asking for specific encryption matching behavior, or be triaged
4808        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4809                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4810                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4811            triaged = false;
4812        }
4813        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4814            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4815                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4816        }
4817
4818        return updateFlags(flags, userId);
4819    }
4820
4821    /**
4822     * Update given intent when being used to request {@link ResolveInfo}.
4823     */
4824    private Intent updateIntentForResolve(Intent intent) {
4825        if (intent.getSelector() != null) {
4826            intent = intent.getSelector();
4827        }
4828        if (DEBUG_PREFERRED) {
4829            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4830        }
4831        return intent;
4832    }
4833
4834    /**
4835     * Update given flags when being used to request {@link ResolveInfo}.
4836     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4837     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4838     * flag set. However, this flag is only honoured in three circumstances:
4839     * <ul>
4840     * <li>when called from a system process</li>
4841     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4842     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4843     * action and a {@code android.intent.category.BROWSABLE} category</li>
4844     * </ul>
4845     */
4846    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4847        return updateFlagsForResolve(flags, userId, intent, callingUid,
4848                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4849    }
4850    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4851            boolean wantInstantApps) {
4852        return updateFlagsForResolve(flags, userId, intent, callingUid,
4853                wantInstantApps, false /*onlyExposedExplicitly*/);
4854    }
4855    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4856            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4857        // Safe mode means we shouldn't match any third-party components
4858        if (mSafeMode) {
4859            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4860        }
4861        if (getInstantAppPackageName(callingUid) != null) {
4862            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4863            if (onlyExposedExplicitly) {
4864                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4865            }
4866            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4867            flags |= PackageManager.MATCH_INSTANT;
4868        } else {
4869            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4870            final boolean allowMatchInstant =
4871                    (wantInstantApps
4872                            && Intent.ACTION_VIEW.equals(intent.getAction())
4873                            && hasWebURI(intent))
4874                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4875            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4876                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4877            if (!allowMatchInstant) {
4878                flags &= ~PackageManager.MATCH_INSTANT;
4879            }
4880        }
4881        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4882    }
4883
4884    @Override
4885    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4886        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4887    }
4888
4889    /**
4890     * Important: The provided filterCallingUid is used exclusively to filter out activities
4891     * that can be seen based on user state. It's typically the original caller uid prior
4892     * to clearing. Because it can only be provided by trusted code, it's value can be
4893     * trusted and will be used as-is; unlike userId which will be validated by this method.
4894     */
4895    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4896            int filterCallingUid, int userId) {
4897        if (!sUserManager.exists(userId)) return null;
4898        flags = updateFlagsForComponent(flags, userId, component);
4899        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4900                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4901        synchronized (mPackages) {
4902            PackageParser.Activity a = mActivities.mActivities.get(component);
4903
4904            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4905            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4906                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4907                if (ps == null) return null;
4908                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4909                    return null;
4910                }
4911                return PackageParser.generateActivityInfo(
4912                        a, flags, ps.readUserState(userId), userId);
4913            }
4914            if (mResolveComponentName.equals(component)) {
4915                return PackageParser.generateActivityInfo(
4916                        mResolveActivity, flags, new PackageUserState(), userId);
4917            }
4918        }
4919        return null;
4920    }
4921
4922    @Override
4923    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4924            String resolvedType) {
4925        synchronized (mPackages) {
4926            if (component.equals(mResolveComponentName)) {
4927                // The resolver supports EVERYTHING!
4928                return true;
4929            }
4930            final int callingUid = Binder.getCallingUid();
4931            final int callingUserId = UserHandle.getUserId(callingUid);
4932            PackageParser.Activity a = mActivities.mActivities.get(component);
4933            if (a == null) {
4934                return false;
4935            }
4936            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4937            if (ps == null) {
4938                return false;
4939            }
4940            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4941                return false;
4942            }
4943            for (int i=0; i<a.intents.size(); i++) {
4944                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4945                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4946                    return true;
4947                }
4948            }
4949            return false;
4950        }
4951    }
4952
4953    @Override
4954    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4955        if (!sUserManager.exists(userId)) return null;
4956        final int callingUid = Binder.getCallingUid();
4957        flags = updateFlagsForComponent(flags, userId, component);
4958        enforceCrossUserPermission(callingUid, userId,
4959                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4960        synchronized (mPackages) {
4961            PackageParser.Activity a = mReceivers.mActivities.get(component);
4962            if (DEBUG_PACKAGE_INFO) Log.v(
4963                TAG, "getReceiverInfo " + component + ": " + a);
4964            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4965                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4966                if (ps == null) return null;
4967                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4968                    return null;
4969                }
4970                return PackageParser.generateActivityInfo(
4971                        a, flags, ps.readUserState(userId), userId);
4972            }
4973        }
4974        return null;
4975    }
4976
4977    @Override
4978    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4979            int flags, int userId) {
4980        if (!sUserManager.exists(userId)) return null;
4981        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4982        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4983            return null;
4984        }
4985
4986        flags = updateFlagsForPackage(flags, userId, null);
4987
4988        final boolean canSeeStaticLibraries =
4989                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4990                        == PERMISSION_GRANTED
4991                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4992                        == PERMISSION_GRANTED
4993                || canRequestPackageInstallsInternal(packageName,
4994                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4995                        false  /* throwIfPermNotDeclared*/)
4996                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4997                        == PERMISSION_GRANTED;
4998
4999        synchronized (mPackages) {
5000            List<SharedLibraryInfo> result = null;
5001
5002            final int libCount = mSharedLibraries.size();
5003            for (int i = 0; i < libCount; i++) {
5004                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5005                if (versionedLib == null) {
5006                    continue;
5007                }
5008
5009                final int versionCount = versionedLib.size();
5010                for (int j = 0; j < versionCount; j++) {
5011                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5012                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5013                        break;
5014                    }
5015                    final long identity = Binder.clearCallingIdentity();
5016                    try {
5017                        PackageInfo packageInfo = getPackageInfoVersioned(
5018                                libInfo.getDeclaringPackage(), flags
5019                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5020                        if (packageInfo == null) {
5021                            continue;
5022                        }
5023                    } finally {
5024                        Binder.restoreCallingIdentity(identity);
5025                    }
5026
5027                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5028                            libInfo.getVersion(), libInfo.getType(),
5029                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5030                            flags, userId));
5031
5032                    if (result == null) {
5033                        result = new ArrayList<>();
5034                    }
5035                    result.add(resLibInfo);
5036                }
5037            }
5038
5039            return result != null ? new ParceledListSlice<>(result) : null;
5040        }
5041    }
5042
5043    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5044            SharedLibraryInfo libInfo, int flags, int userId) {
5045        List<VersionedPackage> versionedPackages = null;
5046        final int packageCount = mSettings.mPackages.size();
5047        for (int i = 0; i < packageCount; i++) {
5048            PackageSetting ps = mSettings.mPackages.valueAt(i);
5049
5050            if (ps == null) {
5051                continue;
5052            }
5053
5054            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5055                continue;
5056            }
5057
5058            final String libName = libInfo.getName();
5059            if (libInfo.isStatic()) {
5060                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5061                if (libIdx < 0) {
5062                    continue;
5063                }
5064                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5065                    continue;
5066                }
5067                if (versionedPackages == null) {
5068                    versionedPackages = new ArrayList<>();
5069                }
5070                // If the dependent is a static shared lib, use the public package name
5071                String dependentPackageName = ps.name;
5072                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5073                    dependentPackageName = ps.pkg.manifestPackageName;
5074                }
5075                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5076            } else if (ps.pkg != null) {
5077                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5078                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5079                    if (versionedPackages == null) {
5080                        versionedPackages = new ArrayList<>();
5081                    }
5082                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5083                }
5084            }
5085        }
5086
5087        return versionedPackages;
5088    }
5089
5090    @Override
5091    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5092        if (!sUserManager.exists(userId)) return null;
5093        final int callingUid = Binder.getCallingUid();
5094        flags = updateFlagsForComponent(flags, userId, component);
5095        enforceCrossUserPermission(callingUid, userId,
5096                false /* requireFullPermission */, false /* checkShell */, "get service info");
5097        synchronized (mPackages) {
5098            PackageParser.Service s = mServices.mServices.get(component);
5099            if (DEBUG_PACKAGE_INFO) Log.v(
5100                TAG, "getServiceInfo " + component + ": " + s);
5101            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5102                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5103                if (ps == null) return null;
5104                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5105                    return null;
5106                }
5107                return PackageParser.generateServiceInfo(
5108                        s, flags, ps.readUserState(userId), userId);
5109            }
5110        }
5111        return null;
5112    }
5113
5114    @Override
5115    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5116        if (!sUserManager.exists(userId)) return null;
5117        final int callingUid = Binder.getCallingUid();
5118        flags = updateFlagsForComponent(flags, userId, component);
5119        enforceCrossUserPermission(callingUid, userId,
5120                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5121        synchronized (mPackages) {
5122            PackageParser.Provider p = mProviders.mProviders.get(component);
5123            if (DEBUG_PACKAGE_INFO) Log.v(
5124                TAG, "getProviderInfo " + component + ": " + p);
5125            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5126                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5127                if (ps == null) return null;
5128                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5129                    return null;
5130                }
5131                return PackageParser.generateProviderInfo(
5132                        p, flags, ps.readUserState(userId), userId);
5133            }
5134        }
5135        return null;
5136    }
5137
5138    @Override
5139    public String[] getSystemSharedLibraryNames() {
5140        // allow instant applications
5141        synchronized (mPackages) {
5142            Set<String> libs = null;
5143            final int libCount = mSharedLibraries.size();
5144            for (int i = 0; i < libCount; i++) {
5145                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5146                if (versionedLib == null) {
5147                    continue;
5148                }
5149                final int versionCount = versionedLib.size();
5150                for (int j = 0; j < versionCount; j++) {
5151                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5152                    if (!libEntry.info.isStatic()) {
5153                        if (libs == null) {
5154                            libs = new ArraySet<>();
5155                        }
5156                        libs.add(libEntry.info.getName());
5157                        break;
5158                    }
5159                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5160                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5161                            UserHandle.getUserId(Binder.getCallingUid()),
5162                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5163                        if (libs == null) {
5164                            libs = new ArraySet<>();
5165                        }
5166                        libs.add(libEntry.info.getName());
5167                        break;
5168                    }
5169                }
5170            }
5171
5172            if (libs != null) {
5173                String[] libsArray = new String[libs.size()];
5174                libs.toArray(libsArray);
5175                return libsArray;
5176            }
5177
5178            return null;
5179        }
5180    }
5181
5182    @Override
5183    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5184        // allow instant applications
5185        synchronized (mPackages) {
5186            return mServicesSystemSharedLibraryPackageName;
5187        }
5188    }
5189
5190    @Override
5191    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5192        // allow instant applications
5193        synchronized (mPackages) {
5194            return mSharedSystemSharedLibraryPackageName;
5195        }
5196    }
5197
5198    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5199        for (int i = userList.length - 1; i >= 0; --i) {
5200            final int userId = userList[i];
5201            // don't add instant app to the list of updates
5202            if (pkgSetting.getInstantApp(userId)) {
5203                continue;
5204            }
5205            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5206            if (changedPackages == null) {
5207                changedPackages = new SparseArray<>();
5208                mChangedPackages.put(userId, changedPackages);
5209            }
5210            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5211            if (sequenceNumbers == null) {
5212                sequenceNumbers = new HashMap<>();
5213                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5214            }
5215            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5216            if (sequenceNumber != null) {
5217                changedPackages.remove(sequenceNumber);
5218            }
5219            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5220            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5221        }
5222        mChangedPackagesSequenceNumber++;
5223    }
5224
5225    @Override
5226    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5227        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5228            return null;
5229        }
5230        synchronized (mPackages) {
5231            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5232                return null;
5233            }
5234            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5235            if (changedPackages == null) {
5236                return null;
5237            }
5238            final List<String> packageNames =
5239                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5240            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5241                final String packageName = changedPackages.get(i);
5242                if (packageName != null) {
5243                    packageNames.add(packageName);
5244                }
5245            }
5246            return packageNames.isEmpty()
5247                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5248        }
5249    }
5250
5251    @Override
5252    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5253        // allow instant applications
5254        ArrayList<FeatureInfo> res;
5255        synchronized (mAvailableFeatures) {
5256            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5257            res.addAll(mAvailableFeatures.values());
5258        }
5259        final FeatureInfo fi = new FeatureInfo();
5260        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5261                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5262        res.add(fi);
5263
5264        return new ParceledListSlice<>(res);
5265    }
5266
5267    @Override
5268    public boolean hasSystemFeature(String name, int version) {
5269        // allow instant applications
5270        synchronized (mAvailableFeatures) {
5271            final FeatureInfo feat = mAvailableFeatures.get(name);
5272            if (feat == null) {
5273                return false;
5274            } else {
5275                return feat.version >= version;
5276            }
5277        }
5278    }
5279
5280    @Override
5281    public int checkPermission(String permName, String pkgName, int userId) {
5282        if (!sUserManager.exists(userId)) {
5283            return PackageManager.PERMISSION_DENIED;
5284        }
5285        final int callingUid = Binder.getCallingUid();
5286
5287        synchronized (mPackages) {
5288            final PackageParser.Package p = mPackages.get(pkgName);
5289            if (p != null && p.mExtras != null) {
5290                final PackageSetting ps = (PackageSetting) p.mExtras;
5291                if (filterAppAccessLPr(ps, callingUid, userId)) {
5292                    return PackageManager.PERMISSION_DENIED;
5293                }
5294                final boolean instantApp = ps.getInstantApp(userId);
5295                final PermissionsState permissionsState = ps.getPermissionsState();
5296                if (permissionsState.hasPermission(permName, userId)) {
5297                    if (instantApp) {
5298                        BasePermission bp = mSettings.mPermissions.get(permName);
5299                        if (bp != null && bp.isInstant()) {
5300                            return PackageManager.PERMISSION_GRANTED;
5301                        }
5302                    } else {
5303                        return PackageManager.PERMISSION_GRANTED;
5304                    }
5305                }
5306                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5307                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5308                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5309                    return PackageManager.PERMISSION_GRANTED;
5310                }
5311            }
5312        }
5313
5314        return PackageManager.PERMISSION_DENIED;
5315    }
5316
5317    @Override
5318    public int checkUidPermission(String permName, int uid) {
5319        final int callingUid = Binder.getCallingUid();
5320        final int callingUserId = UserHandle.getUserId(callingUid);
5321        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5322        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5323        final int userId = UserHandle.getUserId(uid);
5324        if (!sUserManager.exists(userId)) {
5325            return PackageManager.PERMISSION_DENIED;
5326        }
5327
5328        synchronized (mPackages) {
5329            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5330            if (obj != null) {
5331                if (obj instanceof SharedUserSetting) {
5332                    if (isCallerInstantApp) {
5333                        return PackageManager.PERMISSION_DENIED;
5334                    }
5335                } else if (obj instanceof PackageSetting) {
5336                    final PackageSetting ps = (PackageSetting) obj;
5337                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5338                        return PackageManager.PERMISSION_DENIED;
5339                    }
5340                }
5341                final SettingBase settingBase = (SettingBase) obj;
5342                final PermissionsState permissionsState = settingBase.getPermissionsState();
5343                if (permissionsState.hasPermission(permName, userId)) {
5344                    if (isUidInstantApp) {
5345                        BasePermission bp = mSettings.mPermissions.get(permName);
5346                        if (bp != null && bp.isInstant()) {
5347                            return PackageManager.PERMISSION_GRANTED;
5348                        }
5349                    } else {
5350                        return PackageManager.PERMISSION_GRANTED;
5351                    }
5352                }
5353                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5354                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5355                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5356                    return PackageManager.PERMISSION_GRANTED;
5357                }
5358            } else {
5359                ArraySet<String> perms = mSystemPermissions.get(uid);
5360                if (perms != null) {
5361                    if (perms.contains(permName)) {
5362                        return PackageManager.PERMISSION_GRANTED;
5363                    }
5364                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5365                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5366                        return PackageManager.PERMISSION_GRANTED;
5367                    }
5368                }
5369            }
5370        }
5371
5372        return PackageManager.PERMISSION_DENIED;
5373    }
5374
5375    @Override
5376    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5377        if (UserHandle.getCallingUserId() != userId) {
5378            mContext.enforceCallingPermission(
5379                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5380                    "isPermissionRevokedByPolicy for user " + userId);
5381        }
5382
5383        if (checkPermission(permission, packageName, userId)
5384                == PackageManager.PERMISSION_GRANTED) {
5385            return false;
5386        }
5387
5388        final int callingUid = Binder.getCallingUid();
5389        if (getInstantAppPackageName(callingUid) != null) {
5390            if (!isCallerSameApp(packageName, callingUid)) {
5391                return false;
5392            }
5393        } else {
5394            if (isInstantApp(packageName, userId)) {
5395                return false;
5396            }
5397        }
5398
5399        final long identity = Binder.clearCallingIdentity();
5400        try {
5401            final int flags = getPermissionFlags(permission, packageName, userId);
5402            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5403        } finally {
5404            Binder.restoreCallingIdentity(identity);
5405        }
5406    }
5407
5408    @Override
5409    public String getPermissionControllerPackageName() {
5410        synchronized (mPackages) {
5411            return mRequiredInstallerPackage;
5412        }
5413    }
5414
5415    /**
5416     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5417     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5418     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5419     * @param message the message to log on security exception
5420     */
5421    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5422            boolean checkShell, String message) {
5423        if (userId < 0) {
5424            throw new IllegalArgumentException("Invalid userId " + userId);
5425        }
5426        if (checkShell) {
5427            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5428        }
5429        if (userId == UserHandle.getUserId(callingUid)) return;
5430        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5431            if (requireFullPermission) {
5432                mContext.enforceCallingOrSelfPermission(
5433                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5434            } else {
5435                try {
5436                    mContext.enforceCallingOrSelfPermission(
5437                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5438                } catch (SecurityException se) {
5439                    mContext.enforceCallingOrSelfPermission(
5440                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5441                }
5442            }
5443        }
5444    }
5445
5446    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5447        if (callingUid == Process.SHELL_UID) {
5448            if (userHandle >= 0
5449                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5450                throw new SecurityException("Shell does not have permission to access user "
5451                        + userHandle);
5452            } else if (userHandle < 0) {
5453                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5454                        + Debug.getCallers(3));
5455            }
5456        }
5457    }
5458
5459    private BasePermission findPermissionTreeLP(String permName) {
5460        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5461            if (permName.startsWith(bp.name) &&
5462                    permName.length() > bp.name.length() &&
5463                    permName.charAt(bp.name.length()) == '.') {
5464                return bp;
5465            }
5466        }
5467        return null;
5468    }
5469
5470    private BasePermission checkPermissionTreeLP(String permName) {
5471        if (permName != null) {
5472            BasePermission bp = findPermissionTreeLP(permName);
5473            if (bp != null) {
5474                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5475                    return bp;
5476                }
5477                throw new SecurityException("Calling uid "
5478                        + Binder.getCallingUid()
5479                        + " is not allowed to add to permission tree "
5480                        + bp.name + " owned by uid " + bp.uid);
5481            }
5482        }
5483        throw new SecurityException("No permission tree found for " + permName);
5484    }
5485
5486    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5487        if (s1 == null) {
5488            return s2 == null;
5489        }
5490        if (s2 == null) {
5491            return false;
5492        }
5493        if (s1.getClass() != s2.getClass()) {
5494            return false;
5495        }
5496        return s1.equals(s2);
5497    }
5498
5499    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5500        if (pi1.icon != pi2.icon) return false;
5501        if (pi1.logo != pi2.logo) return false;
5502        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5503        if (!compareStrings(pi1.name, pi2.name)) return false;
5504        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5505        // We'll take care of setting this one.
5506        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5507        // These are not currently stored in settings.
5508        //if (!compareStrings(pi1.group, pi2.group)) return false;
5509        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5510        //if (pi1.labelRes != pi2.labelRes) return false;
5511        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5512        return true;
5513    }
5514
5515    int permissionInfoFootprint(PermissionInfo info) {
5516        int size = info.name.length();
5517        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5518        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5519        return size;
5520    }
5521
5522    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5523        int size = 0;
5524        for (BasePermission perm : mSettings.mPermissions.values()) {
5525            if (perm.uid == tree.uid) {
5526                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5527            }
5528        }
5529        return size;
5530    }
5531
5532    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5533        // We calculate the max size of permissions defined by this uid and throw
5534        // if that plus the size of 'info' would exceed our stated maximum.
5535        if (tree.uid != Process.SYSTEM_UID) {
5536            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5537            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5538                throw new SecurityException("Permission tree size cap exceeded");
5539            }
5540        }
5541    }
5542
5543    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5544        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5545            throw new SecurityException("Instant apps can't add permissions");
5546        }
5547        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5548            throw new SecurityException("Label must be specified in permission");
5549        }
5550        BasePermission tree = checkPermissionTreeLP(info.name);
5551        BasePermission bp = mSettings.mPermissions.get(info.name);
5552        boolean added = bp == null;
5553        boolean changed = true;
5554        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5555        if (added) {
5556            enforcePermissionCapLocked(info, tree);
5557            bp = new BasePermission(info.name, tree.sourcePackage,
5558                    BasePermission.TYPE_DYNAMIC);
5559        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5560            throw new SecurityException(
5561                    "Not allowed to modify non-dynamic permission "
5562                    + info.name);
5563        } else {
5564            if (bp.protectionLevel == fixedLevel
5565                    && bp.perm.owner.equals(tree.perm.owner)
5566                    && bp.uid == tree.uid
5567                    && comparePermissionInfos(bp.perm.info, info)) {
5568                changed = false;
5569            }
5570        }
5571        bp.protectionLevel = fixedLevel;
5572        info = new PermissionInfo(info);
5573        info.protectionLevel = fixedLevel;
5574        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5575        bp.perm.info.packageName = tree.perm.info.packageName;
5576        bp.uid = tree.uid;
5577        if (added) {
5578            mSettings.mPermissions.put(info.name, bp);
5579        }
5580        if (changed) {
5581            if (!async) {
5582                mSettings.writeLPr();
5583            } else {
5584                scheduleWriteSettingsLocked();
5585            }
5586        }
5587        return added;
5588    }
5589
5590    @Override
5591    public boolean addPermission(PermissionInfo info) {
5592        synchronized (mPackages) {
5593            return addPermissionLocked(info, false);
5594        }
5595    }
5596
5597    @Override
5598    public boolean addPermissionAsync(PermissionInfo info) {
5599        synchronized (mPackages) {
5600            return addPermissionLocked(info, true);
5601        }
5602    }
5603
5604    @Override
5605    public void removePermission(String name) {
5606        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5607            throw new SecurityException("Instant applications don't have access to this method");
5608        }
5609        synchronized (mPackages) {
5610            checkPermissionTreeLP(name);
5611            BasePermission bp = mSettings.mPermissions.get(name);
5612            if (bp != null) {
5613                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5614                    throw new SecurityException(
5615                            "Not allowed to modify non-dynamic permission "
5616                            + name);
5617                }
5618                mSettings.mPermissions.remove(name);
5619                mSettings.writeLPr();
5620            }
5621        }
5622    }
5623
5624    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5625            PackageParser.Package pkg, BasePermission bp) {
5626        int index = pkg.requestedPermissions.indexOf(bp.name);
5627        if (index == -1) {
5628            throw new SecurityException("Package " + pkg.packageName
5629                    + " has not requested permission " + bp.name);
5630        }
5631        if (!bp.isRuntime() && !bp.isDevelopment()) {
5632            throw new SecurityException("Permission " + bp.name
5633                    + " is not a changeable permission type");
5634        }
5635    }
5636
5637    @Override
5638    public void grantRuntimePermission(String packageName, String name, final int userId) {
5639        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5640    }
5641
5642    private void grantRuntimePermission(String packageName, String name, final int userId,
5643            boolean overridePolicy) {
5644        if (!sUserManager.exists(userId)) {
5645            Log.e(TAG, "No such user:" + userId);
5646            return;
5647        }
5648        final int callingUid = Binder.getCallingUid();
5649
5650        mContext.enforceCallingOrSelfPermission(
5651                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5652                "grantRuntimePermission");
5653
5654        enforceCrossUserPermission(callingUid, userId,
5655                true /* requireFullPermission */, true /* checkShell */,
5656                "grantRuntimePermission");
5657
5658        final int uid;
5659        final PackageSetting ps;
5660
5661        synchronized (mPackages) {
5662            final PackageParser.Package pkg = mPackages.get(packageName);
5663            if (pkg == null) {
5664                throw new IllegalArgumentException("Unknown package: " + packageName);
5665            }
5666            final BasePermission bp = mSettings.mPermissions.get(name);
5667            if (bp == null) {
5668                throw new IllegalArgumentException("Unknown permission: " + name);
5669            }
5670            ps = (PackageSetting) pkg.mExtras;
5671            if (ps == null
5672                    || filterAppAccessLPr(ps, callingUid, userId)) {
5673                throw new IllegalArgumentException("Unknown package: " + packageName);
5674            }
5675
5676            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5677
5678            // If a permission review is required for legacy apps we represent
5679            // their permissions as always granted runtime ones since we need
5680            // to keep the review required permission flag per user while an
5681            // install permission's state is shared across all users.
5682            if (mPermissionReviewRequired
5683                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5684                    && bp.isRuntime()) {
5685                return;
5686            }
5687
5688            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5689
5690            final PermissionsState permissionsState = ps.getPermissionsState();
5691
5692            final int flags = permissionsState.getPermissionFlags(name, userId);
5693            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5694                throw new SecurityException("Cannot grant system fixed permission "
5695                        + name + " for package " + packageName);
5696            }
5697            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5698                throw new SecurityException("Cannot grant policy fixed permission "
5699                        + name + " for package " + packageName);
5700            }
5701
5702            if (bp.isDevelopment()) {
5703                // Development permissions must be handled specially, since they are not
5704                // normal runtime permissions.  For now they apply to all users.
5705                if (permissionsState.grantInstallPermission(bp) !=
5706                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5707                    scheduleWriteSettingsLocked();
5708                }
5709                return;
5710            }
5711
5712            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5713                throw new SecurityException("Cannot grant non-ephemeral permission"
5714                        + name + " for package " + packageName);
5715            }
5716
5717            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5718                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5719                return;
5720            }
5721
5722            final int result = permissionsState.grantRuntimePermission(bp, userId);
5723            switch (result) {
5724                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5725                    return;
5726                }
5727
5728                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5729                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5730                    mHandler.post(new Runnable() {
5731                        @Override
5732                        public void run() {
5733                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5734                        }
5735                    });
5736                }
5737                break;
5738            }
5739
5740            if (bp.isRuntime()) {
5741                logPermissionGranted(mContext, name, packageName);
5742            }
5743
5744            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5745
5746            // Not critical if that is lost - app has to request again.
5747            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5748        }
5749
5750        // Only need to do this if user is initialized. Otherwise it's a new user
5751        // and there are no processes running as the user yet and there's no need
5752        // to make an expensive call to remount processes for the changed permissions.
5753        if (READ_EXTERNAL_STORAGE.equals(name)
5754                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5755            final long token = Binder.clearCallingIdentity();
5756            try {
5757                if (sUserManager.isInitialized(userId)) {
5758                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5759                            StorageManagerInternal.class);
5760                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5761                }
5762            } finally {
5763                Binder.restoreCallingIdentity(token);
5764            }
5765        }
5766    }
5767
5768    @Override
5769    public void revokeRuntimePermission(String packageName, String name, int userId) {
5770        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5771    }
5772
5773    private void revokeRuntimePermission(String packageName, String name, int userId,
5774            boolean overridePolicy) {
5775        if (!sUserManager.exists(userId)) {
5776            Log.e(TAG, "No such user:" + userId);
5777            return;
5778        }
5779
5780        mContext.enforceCallingOrSelfPermission(
5781                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5782                "revokeRuntimePermission");
5783
5784        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5785                true /* requireFullPermission */, true /* checkShell */,
5786                "revokeRuntimePermission");
5787
5788        final int appId;
5789
5790        synchronized (mPackages) {
5791            final PackageParser.Package pkg = mPackages.get(packageName);
5792            if (pkg == null) {
5793                throw new IllegalArgumentException("Unknown package: " + packageName);
5794            }
5795            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5796            if (ps == null
5797                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5798                throw new IllegalArgumentException("Unknown package: " + packageName);
5799            }
5800            final BasePermission bp = mSettings.mPermissions.get(name);
5801            if (bp == null) {
5802                throw new IllegalArgumentException("Unknown permission: " + name);
5803            }
5804
5805            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5806
5807            // If a permission review is required for legacy apps we represent
5808            // their permissions as always granted runtime ones since we need
5809            // to keep the review required permission flag per user while an
5810            // install permission's state is shared across all users.
5811            if (mPermissionReviewRequired
5812                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5813                    && bp.isRuntime()) {
5814                return;
5815            }
5816
5817            final PermissionsState permissionsState = ps.getPermissionsState();
5818
5819            final int flags = permissionsState.getPermissionFlags(name, userId);
5820            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5821                throw new SecurityException("Cannot revoke system fixed permission "
5822                        + name + " for package " + packageName);
5823            }
5824            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5825                throw new SecurityException("Cannot revoke policy fixed permission "
5826                        + name + " for package " + packageName);
5827            }
5828
5829            if (bp.isDevelopment()) {
5830                // Development permissions must be handled specially, since they are not
5831                // normal runtime permissions.  For now they apply to all users.
5832                if (permissionsState.revokeInstallPermission(bp) !=
5833                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5834                    scheduleWriteSettingsLocked();
5835                }
5836                return;
5837            }
5838
5839            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5840                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5841                return;
5842            }
5843
5844            if (bp.isRuntime()) {
5845                logPermissionRevoked(mContext, name, packageName);
5846            }
5847
5848            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5849
5850            // Critical, after this call app should never have the permission.
5851            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5852
5853            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5854        }
5855
5856        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5857    }
5858
5859    /**
5860     * Get the first event id for the permission.
5861     *
5862     * <p>There are four events for each permission: <ul>
5863     *     <li>Request permission: first id + 0</li>
5864     *     <li>Grant permission: first id + 1</li>
5865     *     <li>Request for permission denied: first id + 2</li>
5866     *     <li>Revoke permission: first id + 3</li>
5867     * </ul></p>
5868     *
5869     * @param name name of the permission
5870     *
5871     * @return The first event id for the permission
5872     */
5873    private static int getBaseEventId(@NonNull String name) {
5874        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5875
5876        if (eventIdIndex == -1) {
5877            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5878                    || Build.IS_USER) {
5879                Log.i(TAG, "Unknown permission " + name);
5880
5881                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5882            } else {
5883                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5884                //
5885                // Also update
5886                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5887                // - metrics_constants.proto
5888                throw new IllegalStateException("Unknown permission " + name);
5889            }
5890        }
5891
5892        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5893    }
5894
5895    /**
5896     * Log that a permission was revoked.
5897     *
5898     * @param context Context of the caller
5899     * @param name name of the permission
5900     * @param packageName package permission if for
5901     */
5902    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5903            @NonNull String packageName) {
5904        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5905    }
5906
5907    /**
5908     * Log that a permission request was granted.
5909     *
5910     * @param context Context of the caller
5911     * @param name name of the permission
5912     * @param packageName package permission if for
5913     */
5914    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5915            @NonNull String packageName) {
5916        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5917    }
5918
5919    @Override
5920    public void resetRuntimePermissions() {
5921        mContext.enforceCallingOrSelfPermission(
5922                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5923                "revokeRuntimePermission");
5924
5925        int callingUid = Binder.getCallingUid();
5926        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5927            mContext.enforceCallingOrSelfPermission(
5928                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5929                    "resetRuntimePermissions");
5930        }
5931
5932        synchronized (mPackages) {
5933            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5934            for (int userId : UserManagerService.getInstance().getUserIds()) {
5935                final int packageCount = mPackages.size();
5936                for (int i = 0; i < packageCount; i++) {
5937                    PackageParser.Package pkg = mPackages.valueAt(i);
5938                    if (!(pkg.mExtras instanceof PackageSetting)) {
5939                        continue;
5940                    }
5941                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5942                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5943                }
5944            }
5945        }
5946    }
5947
5948    @Override
5949    public int getPermissionFlags(String name, String packageName, int userId) {
5950        if (!sUserManager.exists(userId)) {
5951            return 0;
5952        }
5953
5954        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5955
5956        final int callingUid = Binder.getCallingUid();
5957        enforceCrossUserPermission(callingUid, userId,
5958                true /* requireFullPermission */, false /* checkShell */,
5959                "getPermissionFlags");
5960
5961        synchronized (mPackages) {
5962            final PackageParser.Package pkg = mPackages.get(packageName);
5963            if (pkg == null) {
5964                return 0;
5965            }
5966            final BasePermission bp = mSettings.mPermissions.get(name);
5967            if (bp == null) {
5968                return 0;
5969            }
5970            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5971            if (ps == null
5972                    || filterAppAccessLPr(ps, callingUid, userId)) {
5973                return 0;
5974            }
5975            PermissionsState permissionsState = ps.getPermissionsState();
5976            return permissionsState.getPermissionFlags(name, userId);
5977        }
5978    }
5979
5980    @Override
5981    public void updatePermissionFlags(String name, String packageName, int flagMask,
5982            int flagValues, int userId) {
5983        if (!sUserManager.exists(userId)) {
5984            return;
5985        }
5986
5987        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5988
5989        final int callingUid = Binder.getCallingUid();
5990        enforceCrossUserPermission(callingUid, userId,
5991                true /* requireFullPermission */, true /* checkShell */,
5992                "updatePermissionFlags");
5993
5994        // Only the system can change these flags and nothing else.
5995        if (getCallingUid() != Process.SYSTEM_UID) {
5996            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5997            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5998            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5999            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
6000            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
6001        }
6002
6003        synchronized (mPackages) {
6004            final PackageParser.Package pkg = mPackages.get(packageName);
6005            if (pkg == null) {
6006                throw new IllegalArgumentException("Unknown package: " + packageName);
6007            }
6008            final PackageSetting ps = (PackageSetting) pkg.mExtras;
6009            if (ps == null
6010                    || filterAppAccessLPr(ps, callingUid, userId)) {
6011                throw new IllegalArgumentException("Unknown package: " + packageName);
6012            }
6013
6014            final BasePermission bp = mSettings.mPermissions.get(name);
6015            if (bp == null) {
6016                throw new IllegalArgumentException("Unknown permission: " + name);
6017            }
6018
6019            PermissionsState permissionsState = ps.getPermissionsState();
6020
6021            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
6022
6023            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
6024                // Install and runtime permissions are stored in different places,
6025                // so figure out what permission changed and persist the change.
6026                if (permissionsState.getInstallPermissionState(name) != null) {
6027                    scheduleWriteSettingsLocked();
6028                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
6029                        || hadState) {
6030                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6031                }
6032            }
6033        }
6034    }
6035
6036    /**
6037     * Update the permission flags for all packages and runtime permissions of a user in order
6038     * to allow device or profile owner to remove POLICY_FIXED.
6039     */
6040    @Override
6041    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
6042        if (!sUserManager.exists(userId)) {
6043            return;
6044        }
6045
6046        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
6047
6048        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6049                true /* requireFullPermission */, true /* checkShell */,
6050                "updatePermissionFlagsForAllApps");
6051
6052        // Only the system can change system fixed flags.
6053        if (getCallingUid() != Process.SYSTEM_UID) {
6054            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6055            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6056        }
6057
6058        synchronized (mPackages) {
6059            boolean changed = false;
6060            final int packageCount = mPackages.size();
6061            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6062                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6063                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6064                if (ps == null) {
6065                    continue;
6066                }
6067                PermissionsState permissionsState = ps.getPermissionsState();
6068                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6069                        userId, flagMask, flagValues);
6070            }
6071            if (changed) {
6072                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6073            }
6074        }
6075    }
6076
6077    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6078        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6079                != PackageManager.PERMISSION_GRANTED
6080            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6081                != PackageManager.PERMISSION_GRANTED) {
6082            throw new SecurityException(message + " requires "
6083                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6084                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6085        }
6086    }
6087
6088    @Override
6089    public boolean shouldShowRequestPermissionRationale(String permissionName,
6090            String packageName, int userId) {
6091        if (UserHandle.getCallingUserId() != userId) {
6092            mContext.enforceCallingPermission(
6093                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6094                    "canShowRequestPermissionRationale for user " + userId);
6095        }
6096
6097        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6098        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6099            return false;
6100        }
6101
6102        if (checkPermission(permissionName, packageName, userId)
6103                == PackageManager.PERMISSION_GRANTED) {
6104            return false;
6105        }
6106
6107        final int flags;
6108
6109        final long identity = Binder.clearCallingIdentity();
6110        try {
6111            flags = getPermissionFlags(permissionName,
6112                    packageName, userId);
6113        } finally {
6114            Binder.restoreCallingIdentity(identity);
6115        }
6116
6117        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6118                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6119                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6120
6121        if ((flags & fixedFlags) != 0) {
6122            return false;
6123        }
6124
6125        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6126    }
6127
6128    @Override
6129    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6130        mContext.enforceCallingOrSelfPermission(
6131                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6132                "addOnPermissionsChangeListener");
6133
6134        synchronized (mPackages) {
6135            mOnPermissionChangeListeners.addListenerLocked(listener);
6136        }
6137    }
6138
6139    @Override
6140    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6141        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6142            throw new SecurityException("Instant applications don't have access to this method");
6143        }
6144        synchronized (mPackages) {
6145            mOnPermissionChangeListeners.removeListenerLocked(listener);
6146        }
6147    }
6148
6149    @Override
6150    public boolean isProtectedBroadcast(String actionName) {
6151        // allow instant applications
6152        synchronized (mProtectedBroadcasts) {
6153            if (mProtectedBroadcasts.contains(actionName)) {
6154                return true;
6155            } else if (actionName != null) {
6156                // TODO: remove these terrible hacks
6157                if (actionName.startsWith("android.net.netmon.lingerExpired")
6158                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6159                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6160                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6161                    return true;
6162                }
6163            }
6164        }
6165        return false;
6166    }
6167
6168    @Override
6169    public int checkSignatures(String pkg1, String pkg2) {
6170        synchronized (mPackages) {
6171            final PackageParser.Package p1 = mPackages.get(pkg1);
6172            final PackageParser.Package p2 = mPackages.get(pkg2);
6173            if (p1 == null || p1.mExtras == null
6174                    || p2 == null || p2.mExtras == null) {
6175                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6176            }
6177            final int callingUid = Binder.getCallingUid();
6178            final int callingUserId = UserHandle.getUserId(callingUid);
6179            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6180            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6181            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6182                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6183                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6184            }
6185            return compareSignatures(p1.mSignatures, p2.mSignatures);
6186        }
6187    }
6188
6189    @Override
6190    public int checkUidSignatures(int uid1, int uid2) {
6191        final int callingUid = Binder.getCallingUid();
6192        final int callingUserId = UserHandle.getUserId(callingUid);
6193        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6194        // Map to base uids.
6195        uid1 = UserHandle.getAppId(uid1);
6196        uid2 = UserHandle.getAppId(uid2);
6197        // reader
6198        synchronized (mPackages) {
6199            Signature[] s1;
6200            Signature[] s2;
6201            Object obj = mSettings.getUserIdLPr(uid1);
6202            if (obj != null) {
6203                if (obj instanceof SharedUserSetting) {
6204                    if (isCallerInstantApp) {
6205                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6206                    }
6207                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6208                } else if (obj instanceof PackageSetting) {
6209                    final PackageSetting ps = (PackageSetting) obj;
6210                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6211                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6212                    }
6213                    s1 = ps.signatures.mSignatures;
6214                } else {
6215                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6216                }
6217            } else {
6218                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6219            }
6220            obj = mSettings.getUserIdLPr(uid2);
6221            if (obj != null) {
6222                if (obj instanceof SharedUserSetting) {
6223                    if (isCallerInstantApp) {
6224                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6225                    }
6226                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6227                } else if (obj instanceof PackageSetting) {
6228                    final PackageSetting ps = (PackageSetting) obj;
6229                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6230                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6231                    }
6232                    s2 = ps.signatures.mSignatures;
6233                } else {
6234                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6235                }
6236            } else {
6237                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6238            }
6239            return compareSignatures(s1, s2);
6240        }
6241    }
6242
6243    /**
6244     * This method should typically only be used when granting or revoking
6245     * permissions, since the app may immediately restart after this call.
6246     * <p>
6247     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6248     * guard your work against the app being relaunched.
6249     */
6250    private void killUid(int appId, int userId, String reason) {
6251        final long identity = Binder.clearCallingIdentity();
6252        try {
6253            IActivityManager am = ActivityManager.getService();
6254            if (am != null) {
6255                try {
6256                    am.killUid(appId, userId, reason);
6257                } catch (RemoteException e) {
6258                    /* ignore - same process */
6259                }
6260            }
6261        } finally {
6262            Binder.restoreCallingIdentity(identity);
6263        }
6264    }
6265
6266    /**
6267     * Compares two sets of signatures. Returns:
6268     * <br />
6269     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6270     * <br />
6271     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6272     * <br />
6273     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6274     * <br />
6275     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6276     * <br />
6277     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6278     */
6279    static int compareSignatures(Signature[] s1, Signature[] s2) {
6280        if (s1 == null) {
6281            return s2 == null
6282                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6283                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6284        }
6285
6286        if (s2 == null) {
6287            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6288        }
6289
6290        if (s1.length != s2.length) {
6291            return PackageManager.SIGNATURE_NO_MATCH;
6292        }
6293
6294        // Since both signature sets are of size 1, we can compare without HashSets.
6295        if (s1.length == 1) {
6296            return s1[0].equals(s2[0]) ?
6297                    PackageManager.SIGNATURE_MATCH :
6298                    PackageManager.SIGNATURE_NO_MATCH;
6299        }
6300
6301        ArraySet<Signature> set1 = new ArraySet<Signature>();
6302        for (Signature sig : s1) {
6303            set1.add(sig);
6304        }
6305        ArraySet<Signature> set2 = new ArraySet<Signature>();
6306        for (Signature sig : s2) {
6307            set2.add(sig);
6308        }
6309        // Make sure s2 contains all signatures in s1.
6310        if (set1.equals(set2)) {
6311            return PackageManager.SIGNATURE_MATCH;
6312        }
6313        return PackageManager.SIGNATURE_NO_MATCH;
6314    }
6315
6316    /**
6317     * If the database version for this type of package (internal storage or
6318     * external storage) is less than the version where package signatures
6319     * were updated, return true.
6320     */
6321    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6322        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6323        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6324    }
6325
6326    /**
6327     * Used for backward compatibility to make sure any packages with
6328     * certificate chains get upgraded to the new style. {@code existingSigs}
6329     * will be in the old format (since they were stored on disk from before the
6330     * system upgrade) and {@code scannedSigs} will be in the newer format.
6331     */
6332    private int compareSignaturesCompat(PackageSignatures existingSigs,
6333            PackageParser.Package scannedPkg) {
6334        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6335            return PackageManager.SIGNATURE_NO_MATCH;
6336        }
6337
6338        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6339        for (Signature sig : existingSigs.mSignatures) {
6340            existingSet.add(sig);
6341        }
6342        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6343        for (Signature sig : scannedPkg.mSignatures) {
6344            try {
6345                Signature[] chainSignatures = sig.getChainSignatures();
6346                for (Signature chainSig : chainSignatures) {
6347                    scannedCompatSet.add(chainSig);
6348                }
6349            } catch (CertificateEncodingException e) {
6350                scannedCompatSet.add(sig);
6351            }
6352        }
6353        /*
6354         * Make sure the expanded scanned set contains all signatures in the
6355         * existing one.
6356         */
6357        if (scannedCompatSet.equals(existingSet)) {
6358            // Migrate the old signatures to the new scheme.
6359            existingSigs.assignSignatures(scannedPkg.mSignatures);
6360            // The new KeySets will be re-added later in the scanning process.
6361            synchronized (mPackages) {
6362                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6363            }
6364            return PackageManager.SIGNATURE_MATCH;
6365        }
6366        return PackageManager.SIGNATURE_NO_MATCH;
6367    }
6368
6369    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6370        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6371        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6372    }
6373
6374    private int compareSignaturesRecover(PackageSignatures existingSigs,
6375            PackageParser.Package scannedPkg) {
6376        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6377            return PackageManager.SIGNATURE_NO_MATCH;
6378        }
6379
6380        String msg = null;
6381        try {
6382            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6383                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6384                        + scannedPkg.packageName);
6385                return PackageManager.SIGNATURE_MATCH;
6386            }
6387        } catch (CertificateException e) {
6388            msg = e.getMessage();
6389        }
6390
6391        logCriticalInfo(Log.INFO,
6392                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6393        return PackageManager.SIGNATURE_NO_MATCH;
6394    }
6395
6396    @Override
6397    public List<String> getAllPackages() {
6398        final int callingUid = Binder.getCallingUid();
6399        final int callingUserId = UserHandle.getUserId(callingUid);
6400        synchronized (mPackages) {
6401            if (canViewInstantApps(callingUid, callingUserId)) {
6402                return new ArrayList<String>(mPackages.keySet());
6403            }
6404            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6405            final List<String> result = new ArrayList<>();
6406            if (instantAppPkgName != null) {
6407                // caller is an instant application; filter unexposed applications
6408                for (PackageParser.Package pkg : mPackages.values()) {
6409                    if (!pkg.visibleToInstantApps) {
6410                        continue;
6411                    }
6412                    result.add(pkg.packageName);
6413                }
6414            } else {
6415                // caller is a normal application; filter instant applications
6416                for (PackageParser.Package pkg : mPackages.values()) {
6417                    final PackageSetting ps =
6418                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6419                    if (ps != null
6420                            && ps.getInstantApp(callingUserId)
6421                            && !mInstantAppRegistry.isInstantAccessGranted(
6422                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6423                        continue;
6424                    }
6425                    result.add(pkg.packageName);
6426                }
6427            }
6428            return result;
6429        }
6430    }
6431
6432    @Override
6433    public String[] getPackagesForUid(int uid) {
6434        final int callingUid = Binder.getCallingUid();
6435        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6436        final int userId = UserHandle.getUserId(uid);
6437        uid = UserHandle.getAppId(uid);
6438        // reader
6439        synchronized (mPackages) {
6440            Object obj = mSettings.getUserIdLPr(uid);
6441            if (obj instanceof SharedUserSetting) {
6442                if (isCallerInstantApp) {
6443                    return null;
6444                }
6445                final SharedUserSetting sus = (SharedUserSetting) obj;
6446                final int N = sus.packages.size();
6447                String[] res = new String[N];
6448                final Iterator<PackageSetting> it = sus.packages.iterator();
6449                int i = 0;
6450                while (it.hasNext()) {
6451                    PackageSetting ps = it.next();
6452                    if (ps.getInstalled(userId)) {
6453                        res[i++] = ps.name;
6454                    } else {
6455                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6456                    }
6457                }
6458                return res;
6459            } else if (obj instanceof PackageSetting) {
6460                final PackageSetting ps = (PackageSetting) obj;
6461                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6462                    return new String[]{ps.name};
6463                }
6464            }
6465        }
6466        return null;
6467    }
6468
6469    @Override
6470    public String getNameForUid(int uid) {
6471        final int callingUid = Binder.getCallingUid();
6472        if (getInstantAppPackageName(callingUid) != null) {
6473            return null;
6474        }
6475        synchronized (mPackages) {
6476            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6477            if (obj instanceof SharedUserSetting) {
6478                final SharedUserSetting sus = (SharedUserSetting) obj;
6479                return sus.name + ":" + sus.userId;
6480            } else if (obj instanceof PackageSetting) {
6481                final PackageSetting ps = (PackageSetting) obj;
6482                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6483                    return null;
6484                }
6485                return ps.name;
6486            }
6487            return null;
6488        }
6489    }
6490
6491    @Override
6492    public String[] getNamesForUids(int[] uids) {
6493        if (uids == null || uids.length == 0) {
6494            return null;
6495        }
6496        final int callingUid = Binder.getCallingUid();
6497        if (getInstantAppPackageName(callingUid) != null) {
6498            return null;
6499        }
6500        final String[] names = new String[uids.length];
6501        synchronized (mPackages) {
6502            for (int i = uids.length - 1; i >= 0; i--) {
6503                final int uid = uids[i];
6504                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6505                if (obj instanceof SharedUserSetting) {
6506                    final SharedUserSetting sus = (SharedUserSetting) obj;
6507                    names[i] = "shared:" + sus.name;
6508                } else if (obj instanceof PackageSetting) {
6509                    final PackageSetting ps = (PackageSetting) obj;
6510                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6511                        names[i] = null;
6512                    } else {
6513                        names[i] = ps.name;
6514                    }
6515                } else {
6516                    names[i] = null;
6517                }
6518            }
6519        }
6520        return names;
6521    }
6522
6523    @Override
6524    public int getUidForSharedUser(String sharedUserName) {
6525        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6526            return -1;
6527        }
6528        if (sharedUserName == null) {
6529            return -1;
6530        }
6531        // reader
6532        synchronized (mPackages) {
6533            SharedUserSetting suid;
6534            try {
6535                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6536                if (suid != null) {
6537                    return suid.userId;
6538                }
6539            } catch (PackageManagerException ignore) {
6540                // can't happen, but, still need to catch it
6541            }
6542            return -1;
6543        }
6544    }
6545
6546    @Override
6547    public int getFlagsForUid(int uid) {
6548        final int callingUid = Binder.getCallingUid();
6549        if (getInstantAppPackageName(callingUid) != null) {
6550            return 0;
6551        }
6552        synchronized (mPackages) {
6553            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6554            if (obj instanceof SharedUserSetting) {
6555                final SharedUserSetting sus = (SharedUserSetting) obj;
6556                return sus.pkgFlags;
6557            } else if (obj instanceof PackageSetting) {
6558                final PackageSetting ps = (PackageSetting) obj;
6559                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6560                    return 0;
6561                }
6562                return ps.pkgFlags;
6563            }
6564        }
6565        return 0;
6566    }
6567
6568    @Override
6569    public int getPrivateFlagsForUid(int uid) {
6570        final int callingUid = Binder.getCallingUid();
6571        if (getInstantAppPackageName(callingUid) != null) {
6572            return 0;
6573        }
6574        synchronized (mPackages) {
6575            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6576            if (obj instanceof SharedUserSetting) {
6577                final SharedUserSetting sus = (SharedUserSetting) obj;
6578                return sus.pkgPrivateFlags;
6579            } else if (obj instanceof PackageSetting) {
6580                final PackageSetting ps = (PackageSetting) obj;
6581                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6582                    return 0;
6583                }
6584                return ps.pkgPrivateFlags;
6585            }
6586        }
6587        return 0;
6588    }
6589
6590    @Override
6591    public boolean isUidPrivileged(int uid) {
6592        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6593            return false;
6594        }
6595        uid = UserHandle.getAppId(uid);
6596        // reader
6597        synchronized (mPackages) {
6598            Object obj = mSettings.getUserIdLPr(uid);
6599            if (obj instanceof SharedUserSetting) {
6600                final SharedUserSetting sus = (SharedUserSetting) obj;
6601                final Iterator<PackageSetting> it = sus.packages.iterator();
6602                while (it.hasNext()) {
6603                    if (it.next().isPrivileged()) {
6604                        return true;
6605                    }
6606                }
6607            } else if (obj instanceof PackageSetting) {
6608                final PackageSetting ps = (PackageSetting) obj;
6609                return ps.isPrivileged();
6610            }
6611        }
6612        return false;
6613    }
6614
6615    @Override
6616    public String[] getAppOpPermissionPackages(String permissionName) {
6617        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6618            return null;
6619        }
6620        synchronized (mPackages) {
6621            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6622            if (pkgs == null) {
6623                return null;
6624            }
6625            return pkgs.toArray(new String[pkgs.size()]);
6626        }
6627    }
6628
6629    @Override
6630    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6631            int flags, int userId) {
6632        return resolveIntentInternal(
6633                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6634    }
6635
6636    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6637            int flags, int userId, boolean resolveForStart) {
6638        try {
6639            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6640
6641            if (!sUserManager.exists(userId)) return null;
6642            final int callingUid = Binder.getCallingUid();
6643            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6644            enforceCrossUserPermission(callingUid, userId,
6645                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6646
6647            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6648            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6649                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6650            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6651
6652            final ResolveInfo bestChoice =
6653                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6654            return bestChoice;
6655        } finally {
6656            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6657        }
6658    }
6659
6660    @Override
6661    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6662        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6663            throw new SecurityException(
6664                    "findPersistentPreferredActivity can only be run by the system");
6665        }
6666        if (!sUserManager.exists(userId)) {
6667            return null;
6668        }
6669        final int callingUid = Binder.getCallingUid();
6670        intent = updateIntentForResolve(intent);
6671        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6672        final int flags = updateFlagsForResolve(
6673                0, userId, intent, callingUid, false /*includeInstantApps*/);
6674        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6675                userId);
6676        synchronized (mPackages) {
6677            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6678                    userId);
6679        }
6680    }
6681
6682    @Override
6683    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6684            IntentFilter filter, int match, ComponentName activity) {
6685        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6686            return;
6687        }
6688        final int userId = UserHandle.getCallingUserId();
6689        if (DEBUG_PREFERRED) {
6690            Log.v(TAG, "setLastChosenActivity intent=" + intent
6691                + " resolvedType=" + resolvedType
6692                + " flags=" + flags
6693                + " filter=" + filter
6694                + " match=" + match
6695                + " activity=" + activity);
6696            filter.dump(new PrintStreamPrinter(System.out), "    ");
6697        }
6698        intent.setComponent(null);
6699        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6700                userId);
6701        // Find any earlier preferred or last chosen entries and nuke them
6702        findPreferredActivity(intent, resolvedType,
6703                flags, query, 0, false, true, false, userId);
6704        // Add the new activity as the last chosen for this filter
6705        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6706                "Setting last chosen");
6707    }
6708
6709    @Override
6710    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6711        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6712            return null;
6713        }
6714        final int userId = UserHandle.getCallingUserId();
6715        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6716        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6717                userId);
6718        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6719                false, false, false, userId);
6720    }
6721
6722    /**
6723     * Returns whether or not instant apps have been disabled remotely.
6724     */
6725    private boolean isEphemeralDisabled() {
6726        return mEphemeralAppsDisabled;
6727    }
6728
6729    private boolean isInstantAppAllowed(
6730            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6731            boolean skipPackageCheck) {
6732        if (mInstantAppResolverConnection == null) {
6733            return false;
6734        }
6735        if (mInstantAppInstallerActivity == null) {
6736            return false;
6737        }
6738        if (intent.getComponent() != null) {
6739            return false;
6740        }
6741        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6742            return false;
6743        }
6744        if (!skipPackageCheck && intent.getPackage() != null) {
6745            return false;
6746        }
6747        final boolean isWebUri = hasWebURI(intent);
6748        if (!isWebUri || intent.getData().getHost() == null) {
6749            return false;
6750        }
6751        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6752        // Or if there's already an ephemeral app installed that handles the action
6753        synchronized (mPackages) {
6754            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6755            for (int n = 0; n < count; n++) {
6756                final ResolveInfo info = resolvedActivities.get(n);
6757                final String packageName = info.activityInfo.packageName;
6758                final PackageSetting ps = mSettings.mPackages.get(packageName);
6759                if (ps != null) {
6760                    // only check domain verification status if the app is not a browser
6761                    if (!info.handleAllWebDataURI) {
6762                        // Try to get the status from User settings first
6763                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6764                        final int status = (int) (packedStatus >> 32);
6765                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6766                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6767                            if (DEBUG_EPHEMERAL) {
6768                                Slog.v(TAG, "DENY instant app;"
6769                                    + " pkg: " + packageName + ", status: " + status);
6770                            }
6771                            return false;
6772                        }
6773                    }
6774                    if (ps.getInstantApp(userId)) {
6775                        if (DEBUG_EPHEMERAL) {
6776                            Slog.v(TAG, "DENY instant app installed;"
6777                                    + " pkg: " + packageName);
6778                        }
6779                        return false;
6780                    }
6781                }
6782            }
6783        }
6784        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6785        return true;
6786    }
6787
6788    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6789            Intent origIntent, String resolvedType, String callingPackage,
6790            Bundle verificationBundle, int userId) {
6791        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6792                new InstantAppRequest(responseObj, origIntent, resolvedType,
6793                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6794        mHandler.sendMessage(msg);
6795    }
6796
6797    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6798            int flags, List<ResolveInfo> query, int userId) {
6799        if (query != null) {
6800            final int N = query.size();
6801            if (N == 1) {
6802                return query.get(0);
6803            } else if (N > 1) {
6804                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6805                // If there is more than one activity with the same priority,
6806                // then let the user decide between them.
6807                ResolveInfo r0 = query.get(0);
6808                ResolveInfo r1 = query.get(1);
6809                if (DEBUG_INTENT_MATCHING || debug) {
6810                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6811                            + r1.activityInfo.name + "=" + r1.priority);
6812                }
6813                // If the first activity has a higher priority, or a different
6814                // default, then it is always desirable to pick it.
6815                if (r0.priority != r1.priority
6816                        || r0.preferredOrder != r1.preferredOrder
6817                        || r0.isDefault != r1.isDefault) {
6818                    return query.get(0);
6819                }
6820                // If we have saved a preference for a preferred activity for
6821                // this Intent, use that.
6822                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6823                        flags, query, r0.priority, true, false, debug, userId);
6824                if (ri != null) {
6825                    return ri;
6826                }
6827                // If we have an ephemeral app, use it
6828                for (int i = 0; i < N; i++) {
6829                    ri = query.get(i);
6830                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6831                        final String packageName = ri.activityInfo.packageName;
6832                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6833                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6834                        final int status = (int)(packedStatus >> 32);
6835                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6836                            return ri;
6837                        }
6838                    }
6839                }
6840                ri = new ResolveInfo(mResolveInfo);
6841                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6842                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6843                // If all of the options come from the same package, show the application's
6844                // label and icon instead of the generic resolver's.
6845                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6846                // and then throw away the ResolveInfo itself, meaning that the caller loses
6847                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6848                // a fallback for this case; we only set the target package's resources on
6849                // the ResolveInfo, not the ActivityInfo.
6850                final String intentPackage = intent.getPackage();
6851                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6852                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6853                    ri.resolvePackageName = intentPackage;
6854                    if (userNeedsBadging(userId)) {
6855                        ri.noResourceId = true;
6856                    } else {
6857                        ri.icon = appi.icon;
6858                    }
6859                    ri.iconResourceId = appi.icon;
6860                    ri.labelRes = appi.labelRes;
6861                }
6862                ri.activityInfo.applicationInfo = new ApplicationInfo(
6863                        ri.activityInfo.applicationInfo);
6864                if (userId != 0) {
6865                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6866                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6867                }
6868                // Make sure that the resolver is displayable in car mode
6869                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6870                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6871                return ri;
6872            }
6873        }
6874        return null;
6875    }
6876
6877    /**
6878     * Return true if the given list is not empty and all of its contents have
6879     * an activityInfo with the given package name.
6880     */
6881    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6882        if (ArrayUtils.isEmpty(list)) {
6883            return false;
6884        }
6885        for (int i = 0, N = list.size(); i < N; i++) {
6886            final ResolveInfo ri = list.get(i);
6887            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6888            if (ai == null || !packageName.equals(ai.packageName)) {
6889                return false;
6890            }
6891        }
6892        return true;
6893    }
6894
6895    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6896            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6897        final int N = query.size();
6898        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6899                .get(userId);
6900        // Get the list of persistent preferred activities that handle the intent
6901        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6902        List<PersistentPreferredActivity> pprefs = ppir != null
6903                ? ppir.queryIntent(intent, resolvedType,
6904                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6905                        userId)
6906                : null;
6907        if (pprefs != null && pprefs.size() > 0) {
6908            final int M = pprefs.size();
6909            for (int i=0; i<M; i++) {
6910                final PersistentPreferredActivity ppa = pprefs.get(i);
6911                if (DEBUG_PREFERRED || debug) {
6912                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6913                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6914                            + "\n  component=" + ppa.mComponent);
6915                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6916                }
6917                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6918                        flags | MATCH_DISABLED_COMPONENTS, userId);
6919                if (DEBUG_PREFERRED || debug) {
6920                    Slog.v(TAG, "Found persistent preferred activity:");
6921                    if (ai != null) {
6922                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6923                    } else {
6924                        Slog.v(TAG, "  null");
6925                    }
6926                }
6927                if (ai == null) {
6928                    // This previously registered persistent preferred activity
6929                    // component is no longer known. Ignore it and do NOT remove it.
6930                    continue;
6931                }
6932                for (int j=0; j<N; j++) {
6933                    final ResolveInfo ri = query.get(j);
6934                    if (!ri.activityInfo.applicationInfo.packageName
6935                            .equals(ai.applicationInfo.packageName)) {
6936                        continue;
6937                    }
6938                    if (!ri.activityInfo.name.equals(ai.name)) {
6939                        continue;
6940                    }
6941                    //  Found a persistent preference that can handle the intent.
6942                    if (DEBUG_PREFERRED || debug) {
6943                        Slog.v(TAG, "Returning persistent preferred activity: " +
6944                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6945                    }
6946                    return ri;
6947                }
6948            }
6949        }
6950        return null;
6951    }
6952
6953    // TODO: handle preferred activities missing while user has amnesia
6954    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6955            List<ResolveInfo> query, int priority, boolean always,
6956            boolean removeMatches, boolean debug, int userId) {
6957        if (!sUserManager.exists(userId)) return null;
6958        final int callingUid = Binder.getCallingUid();
6959        flags = updateFlagsForResolve(
6960                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6961        intent = updateIntentForResolve(intent);
6962        // writer
6963        synchronized (mPackages) {
6964            // Try to find a matching persistent preferred activity.
6965            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6966                    debug, userId);
6967
6968            // If a persistent preferred activity matched, use it.
6969            if (pri != null) {
6970                return pri;
6971            }
6972
6973            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6974            // Get the list of preferred activities that handle the intent
6975            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6976            List<PreferredActivity> prefs = pir != null
6977                    ? pir.queryIntent(intent, resolvedType,
6978                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6979                            userId)
6980                    : null;
6981            if (prefs != null && prefs.size() > 0) {
6982                boolean changed = false;
6983                try {
6984                    // First figure out how good the original match set is.
6985                    // We will only allow preferred activities that came
6986                    // from the same match quality.
6987                    int match = 0;
6988
6989                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6990
6991                    final int N = query.size();
6992                    for (int j=0; j<N; j++) {
6993                        final ResolveInfo ri = query.get(j);
6994                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6995                                + ": 0x" + Integer.toHexString(match));
6996                        if (ri.match > match) {
6997                            match = ri.match;
6998                        }
6999                    }
7000
7001                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
7002                            + Integer.toHexString(match));
7003
7004                    match &= IntentFilter.MATCH_CATEGORY_MASK;
7005                    final int M = prefs.size();
7006                    for (int i=0; i<M; i++) {
7007                        final PreferredActivity pa = prefs.get(i);
7008                        if (DEBUG_PREFERRED || debug) {
7009                            Slog.v(TAG, "Checking PreferredActivity ds="
7010                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
7011                                    + "\n  component=" + pa.mPref.mComponent);
7012                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7013                        }
7014                        if (pa.mPref.mMatch != match) {
7015                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
7016                                    + Integer.toHexString(pa.mPref.mMatch));
7017                            continue;
7018                        }
7019                        // If it's not an "always" type preferred activity and that's what we're
7020                        // looking for, skip it.
7021                        if (always && !pa.mPref.mAlways) {
7022                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
7023                            continue;
7024                        }
7025                        final ActivityInfo ai = getActivityInfo(
7026                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
7027                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
7028                                userId);
7029                        if (DEBUG_PREFERRED || debug) {
7030                            Slog.v(TAG, "Found preferred activity:");
7031                            if (ai != null) {
7032                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7033                            } else {
7034                                Slog.v(TAG, "  null");
7035                            }
7036                        }
7037                        if (ai == null) {
7038                            // This previously registered preferred activity
7039                            // component is no longer known.  Most likely an update
7040                            // to the app was installed and in the new version this
7041                            // component no longer exists.  Clean it up by removing
7042                            // it from the preferred activities list, and skip it.
7043                            Slog.w(TAG, "Removing dangling preferred activity: "
7044                                    + pa.mPref.mComponent);
7045                            pir.removeFilter(pa);
7046                            changed = true;
7047                            continue;
7048                        }
7049                        for (int j=0; j<N; j++) {
7050                            final ResolveInfo ri = query.get(j);
7051                            if (!ri.activityInfo.applicationInfo.packageName
7052                                    .equals(ai.applicationInfo.packageName)) {
7053                                continue;
7054                            }
7055                            if (!ri.activityInfo.name.equals(ai.name)) {
7056                                continue;
7057                            }
7058
7059                            if (removeMatches) {
7060                                pir.removeFilter(pa);
7061                                changed = true;
7062                                if (DEBUG_PREFERRED) {
7063                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7064                                }
7065                                break;
7066                            }
7067
7068                            // Okay we found a previously set preferred or last chosen app.
7069                            // If the result set is different from when this
7070                            // was created, and is not a subset of the preferred set, we need to
7071                            // clear it and re-ask the user their preference, if we're looking for
7072                            // an "always" type entry.
7073                            if (always && !pa.mPref.sameSet(query)) {
7074                                if (pa.mPref.isSuperset(query)) {
7075                                    // some components of the set are no longer present in
7076                                    // the query, but the preferred activity can still be reused
7077                                    if (DEBUG_PREFERRED) {
7078                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
7079                                                + " still valid as only non-preferred components"
7080                                                + " were removed for " + intent + " type "
7081                                                + resolvedType);
7082                                    }
7083                                    // remove obsolete components and re-add the up-to-date filter
7084                                    PreferredActivity freshPa = new PreferredActivity(pa,
7085                                            pa.mPref.mMatch,
7086                                            pa.mPref.discardObsoleteComponents(query),
7087                                            pa.mPref.mComponent,
7088                                            pa.mPref.mAlways);
7089                                    pir.removeFilter(pa);
7090                                    pir.addFilter(freshPa);
7091                                    changed = true;
7092                                } else {
7093                                    Slog.i(TAG,
7094                                            "Result set changed, dropping preferred activity for "
7095                                                    + intent + " type " + resolvedType);
7096                                    if (DEBUG_PREFERRED) {
7097                                        Slog.v(TAG, "Removing preferred activity since set changed "
7098                                                + pa.mPref.mComponent);
7099                                    }
7100                                    pir.removeFilter(pa);
7101                                    // Re-add the filter as a "last chosen" entry (!always)
7102                                    PreferredActivity lastChosen = new PreferredActivity(
7103                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7104                                    pir.addFilter(lastChosen);
7105                                    changed = true;
7106                                    return null;
7107                                }
7108                            }
7109
7110                            // Yay! Either the set matched or we're looking for the last chosen
7111                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7112                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7113                            return ri;
7114                        }
7115                    }
7116                } finally {
7117                    if (changed) {
7118                        if (DEBUG_PREFERRED) {
7119                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7120                        }
7121                        scheduleWritePackageRestrictionsLocked(userId);
7122                    }
7123                }
7124            }
7125        }
7126        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7127        return null;
7128    }
7129
7130    /*
7131     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7132     */
7133    @Override
7134    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7135            int targetUserId) {
7136        mContext.enforceCallingOrSelfPermission(
7137                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7138        List<CrossProfileIntentFilter> matches =
7139                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7140        if (matches != null) {
7141            int size = matches.size();
7142            for (int i = 0; i < size; i++) {
7143                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7144            }
7145        }
7146        if (hasWebURI(intent)) {
7147            // cross-profile app linking works only towards the parent.
7148            final int callingUid = Binder.getCallingUid();
7149            final UserInfo parent = getProfileParent(sourceUserId);
7150            synchronized(mPackages) {
7151                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7152                        false /*includeInstantApps*/);
7153                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7154                        intent, resolvedType, flags, sourceUserId, parent.id);
7155                return xpDomainInfo != null;
7156            }
7157        }
7158        return false;
7159    }
7160
7161    private UserInfo getProfileParent(int userId) {
7162        final long identity = Binder.clearCallingIdentity();
7163        try {
7164            return sUserManager.getProfileParent(userId);
7165        } finally {
7166            Binder.restoreCallingIdentity(identity);
7167        }
7168    }
7169
7170    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7171            String resolvedType, int userId) {
7172        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7173        if (resolver != null) {
7174            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7175        }
7176        return null;
7177    }
7178
7179    @Override
7180    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7181            String resolvedType, int flags, int userId) {
7182        try {
7183            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7184
7185            return new ParceledListSlice<>(
7186                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7187        } finally {
7188            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7189        }
7190    }
7191
7192    /**
7193     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7194     * instant, returns {@code null}.
7195     */
7196    private String getInstantAppPackageName(int callingUid) {
7197        synchronized (mPackages) {
7198            // If the caller is an isolated app use the owner's uid for the lookup.
7199            if (Process.isIsolated(callingUid)) {
7200                callingUid = mIsolatedOwners.get(callingUid);
7201            }
7202            final int appId = UserHandle.getAppId(callingUid);
7203            final Object obj = mSettings.getUserIdLPr(appId);
7204            if (obj instanceof PackageSetting) {
7205                final PackageSetting ps = (PackageSetting) obj;
7206                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7207                return isInstantApp ? ps.pkg.packageName : null;
7208            }
7209        }
7210        return null;
7211    }
7212
7213    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7214            String resolvedType, int flags, int userId) {
7215        return queryIntentActivitiesInternal(
7216                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7217                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7218    }
7219
7220    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7221            String resolvedType, int flags, int filterCallingUid, int userId,
7222            boolean resolveForStart, boolean allowDynamicSplits) {
7223        if (!sUserManager.exists(userId)) return Collections.emptyList();
7224        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7225        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7226                false /* requireFullPermission */, false /* checkShell */,
7227                "query intent activities");
7228        final String pkgName = intent.getPackage();
7229        ComponentName comp = intent.getComponent();
7230        if (comp == null) {
7231            if (intent.getSelector() != null) {
7232                intent = intent.getSelector();
7233                comp = intent.getComponent();
7234            }
7235        }
7236
7237        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7238                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7239        if (comp != null) {
7240            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7241            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7242            if (ai != null) {
7243                // When specifying an explicit component, we prevent the activity from being
7244                // used when either 1) the calling package is normal and the activity is within
7245                // an ephemeral application or 2) the calling package is ephemeral and the
7246                // activity is not visible to ephemeral applications.
7247                final boolean matchInstantApp =
7248                        (flags & PackageManager.MATCH_INSTANT) != 0;
7249                final boolean matchVisibleToInstantAppOnly =
7250                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7251                final boolean matchExplicitlyVisibleOnly =
7252                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7253                final boolean isCallerInstantApp =
7254                        instantAppPkgName != null;
7255                final boolean isTargetSameInstantApp =
7256                        comp.getPackageName().equals(instantAppPkgName);
7257                final boolean isTargetInstantApp =
7258                        (ai.applicationInfo.privateFlags
7259                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7260                final boolean isTargetVisibleToInstantApp =
7261                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7262                final boolean isTargetExplicitlyVisibleToInstantApp =
7263                        isTargetVisibleToInstantApp
7264                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7265                final boolean isTargetHiddenFromInstantApp =
7266                        !isTargetVisibleToInstantApp
7267                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7268                final boolean blockResolution =
7269                        !isTargetSameInstantApp
7270                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7271                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7272                                        && isTargetHiddenFromInstantApp));
7273                if (!blockResolution) {
7274                    final ResolveInfo ri = new ResolveInfo();
7275                    ri.activityInfo = ai;
7276                    list.add(ri);
7277                }
7278            }
7279            return applyPostResolutionFilter(
7280                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7281        }
7282
7283        // reader
7284        boolean sortResult = false;
7285        boolean addEphemeral = false;
7286        List<ResolveInfo> result;
7287        final boolean ephemeralDisabled = isEphemeralDisabled();
7288        synchronized (mPackages) {
7289            if (pkgName == null) {
7290                List<CrossProfileIntentFilter> matchingFilters =
7291                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7292                // Check for results that need to skip the current profile.
7293                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7294                        resolvedType, flags, userId);
7295                if (xpResolveInfo != null) {
7296                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7297                    xpResult.add(xpResolveInfo);
7298                    return applyPostResolutionFilter(
7299                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7300                            allowDynamicSplits, filterCallingUid, userId);
7301                }
7302
7303                // Check for results in the current profile.
7304                result = filterIfNotSystemUser(mActivities.queryIntent(
7305                        intent, resolvedType, flags, userId), userId);
7306                addEphemeral = !ephemeralDisabled
7307                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7308                // Check for cross profile results.
7309                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7310                xpResolveInfo = queryCrossProfileIntents(
7311                        matchingFilters, intent, resolvedType, flags, userId,
7312                        hasNonNegativePriorityResult);
7313                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7314                    boolean isVisibleToUser = filterIfNotSystemUser(
7315                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7316                    if (isVisibleToUser) {
7317                        result.add(xpResolveInfo);
7318                        sortResult = true;
7319                    }
7320                }
7321                if (hasWebURI(intent)) {
7322                    CrossProfileDomainInfo xpDomainInfo = null;
7323                    final UserInfo parent = getProfileParent(userId);
7324                    if (parent != null) {
7325                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7326                                flags, userId, parent.id);
7327                    }
7328                    if (xpDomainInfo != null) {
7329                        if (xpResolveInfo != null) {
7330                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7331                            // in the result.
7332                            result.remove(xpResolveInfo);
7333                        }
7334                        if (result.size() == 0 && !addEphemeral) {
7335                            // No result in current profile, but found candidate in parent user.
7336                            // And we are not going to add emphemeral app, so we can return the
7337                            // result straight away.
7338                            result.add(xpDomainInfo.resolveInfo);
7339                            return applyPostResolutionFilter(result, instantAppPkgName,
7340                                    allowDynamicSplits, filterCallingUid, userId);
7341                        }
7342                    } else if (result.size() <= 1 && !addEphemeral) {
7343                        // No result in parent user and <= 1 result in current profile, and we
7344                        // are not going to add emphemeral app, so we can return the result without
7345                        // further processing.
7346                        return applyPostResolutionFilter(result, instantAppPkgName,
7347                                allowDynamicSplits, filterCallingUid, userId);
7348                    }
7349                    // We have more than one candidate (combining results from current and parent
7350                    // profile), so we need filtering and sorting.
7351                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7352                            intent, flags, result, xpDomainInfo, userId);
7353                    sortResult = true;
7354                }
7355            } else {
7356                final PackageParser.Package pkg = mPackages.get(pkgName);
7357                result = null;
7358                if (pkg != null) {
7359                    result = filterIfNotSystemUser(
7360                            mActivities.queryIntentForPackage(
7361                                    intent, resolvedType, flags, pkg.activities, userId),
7362                            userId);
7363                }
7364                if (result == null || result.size() == 0) {
7365                    // the caller wants to resolve for a particular package; however, there
7366                    // were no installed results, so, try to find an ephemeral result
7367                    addEphemeral = !ephemeralDisabled
7368                            && isInstantAppAllowed(
7369                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7370                    if (result == null) {
7371                        result = new ArrayList<>();
7372                    }
7373                }
7374            }
7375        }
7376        if (addEphemeral) {
7377            result = maybeAddInstantAppInstaller(
7378                    result, intent, resolvedType, flags, userId, resolveForStart);
7379        }
7380        if (sortResult) {
7381            Collections.sort(result, mResolvePrioritySorter);
7382        }
7383        return applyPostResolutionFilter(
7384                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7385    }
7386
7387    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7388            String resolvedType, int flags, int userId, boolean resolveForStart) {
7389        // first, check to see if we've got an instant app already installed
7390        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7391        ResolveInfo localInstantApp = null;
7392        boolean blockResolution = false;
7393        if (!alreadyResolvedLocally) {
7394            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7395                    flags
7396                        | PackageManager.GET_RESOLVED_FILTER
7397                        | PackageManager.MATCH_INSTANT
7398                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7399                    userId);
7400            for (int i = instantApps.size() - 1; i >= 0; --i) {
7401                final ResolveInfo info = instantApps.get(i);
7402                final String packageName = info.activityInfo.packageName;
7403                final PackageSetting ps = mSettings.mPackages.get(packageName);
7404                if (ps.getInstantApp(userId)) {
7405                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7406                    final int status = (int)(packedStatus >> 32);
7407                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7408                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7409                        // there's a local instant application installed, but, the user has
7410                        // chosen to never use it; skip resolution and don't acknowledge
7411                        // an instant application is even available
7412                        if (DEBUG_EPHEMERAL) {
7413                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7414                        }
7415                        blockResolution = true;
7416                        break;
7417                    } else {
7418                        // we have a locally installed instant application; skip resolution
7419                        // but acknowledge there's an instant application available
7420                        if (DEBUG_EPHEMERAL) {
7421                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7422                        }
7423                        localInstantApp = info;
7424                        break;
7425                    }
7426                }
7427            }
7428        }
7429        // no app installed, let's see if one's available
7430        AuxiliaryResolveInfo auxiliaryResponse = null;
7431        if (!blockResolution) {
7432            if (localInstantApp == null) {
7433                // we don't have an instant app locally, resolve externally
7434                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7435                final InstantAppRequest requestObject = new InstantAppRequest(
7436                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7437                        null /*callingPackage*/, userId, null /*verificationBundle*/,
7438                        resolveForStart);
7439                auxiliaryResponse =
7440                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7441                                mContext, mInstantAppResolverConnection, requestObject);
7442                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7443            } else {
7444                // we have an instant application locally, but, we can't admit that since
7445                // callers shouldn't be able to determine prior browsing. create a dummy
7446                // auxiliary response so the downstream code behaves as if there's an
7447                // instant application available externally. when it comes time to start
7448                // the instant application, we'll do the right thing.
7449                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7450                auxiliaryResponse = new AuxiliaryResolveInfo(
7451                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7452                        ai.versionCode, null /*failureIntent*/);
7453            }
7454        }
7455        if (auxiliaryResponse != null) {
7456            if (DEBUG_EPHEMERAL) {
7457                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7458            }
7459            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7460            final PackageSetting ps =
7461                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7462            if (ps != null) {
7463                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7464                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7465                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7466                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7467                // make sure this resolver is the default
7468                ephemeralInstaller.isDefault = true;
7469                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7470                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7471                // add a non-generic filter
7472                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7473                ephemeralInstaller.filter.addDataPath(
7474                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7475                ephemeralInstaller.isInstantAppAvailable = true;
7476                result.add(ephemeralInstaller);
7477            }
7478        }
7479        return result;
7480    }
7481
7482    private static class CrossProfileDomainInfo {
7483        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7484        ResolveInfo resolveInfo;
7485        /* Best domain verification status of the activities found in the other profile */
7486        int bestDomainVerificationStatus;
7487    }
7488
7489    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7490            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7491        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7492                sourceUserId)) {
7493            return null;
7494        }
7495        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7496                resolvedType, flags, parentUserId);
7497
7498        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7499            return null;
7500        }
7501        CrossProfileDomainInfo result = null;
7502        int size = resultTargetUser.size();
7503        for (int i = 0; i < size; i++) {
7504            ResolveInfo riTargetUser = resultTargetUser.get(i);
7505            // Intent filter verification is only for filters that specify a host. So don't return
7506            // those that handle all web uris.
7507            if (riTargetUser.handleAllWebDataURI) {
7508                continue;
7509            }
7510            String packageName = riTargetUser.activityInfo.packageName;
7511            PackageSetting ps = mSettings.mPackages.get(packageName);
7512            if (ps == null) {
7513                continue;
7514            }
7515            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7516            int status = (int)(verificationState >> 32);
7517            if (result == null) {
7518                result = new CrossProfileDomainInfo();
7519                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7520                        sourceUserId, parentUserId);
7521                result.bestDomainVerificationStatus = status;
7522            } else {
7523                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7524                        result.bestDomainVerificationStatus);
7525            }
7526        }
7527        // Don't consider matches with status NEVER across profiles.
7528        if (result != null && result.bestDomainVerificationStatus
7529                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7530            return null;
7531        }
7532        return result;
7533    }
7534
7535    /**
7536     * Verification statuses are ordered from the worse to the best, except for
7537     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7538     */
7539    private int bestDomainVerificationStatus(int status1, int status2) {
7540        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7541            return status2;
7542        }
7543        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7544            return status1;
7545        }
7546        return (int) MathUtils.max(status1, status2);
7547    }
7548
7549    private boolean isUserEnabled(int userId) {
7550        long callingId = Binder.clearCallingIdentity();
7551        try {
7552            UserInfo userInfo = sUserManager.getUserInfo(userId);
7553            return userInfo != null && userInfo.isEnabled();
7554        } finally {
7555            Binder.restoreCallingIdentity(callingId);
7556        }
7557    }
7558
7559    /**
7560     * Filter out activities with systemUserOnly flag set, when current user is not System.
7561     *
7562     * @return filtered list
7563     */
7564    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7565        if (userId == UserHandle.USER_SYSTEM) {
7566            return resolveInfos;
7567        }
7568        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7569            ResolveInfo info = resolveInfos.get(i);
7570            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7571                resolveInfos.remove(i);
7572            }
7573        }
7574        return resolveInfos;
7575    }
7576
7577    /**
7578     * Filters out ephemeral activities.
7579     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7580     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7581     *
7582     * @param resolveInfos The pre-filtered list of resolved activities
7583     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7584     *          is performed.
7585     * @return A filtered list of resolved activities.
7586     */
7587    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7588            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7589        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7590            final ResolveInfo info = resolveInfos.get(i);
7591            // allow activities that are defined in the provided package
7592            if (allowDynamicSplits
7593                    && info.activityInfo.splitName != null
7594                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7595                            info.activityInfo.splitName)) {
7596                // requested activity is defined in a split that hasn't been installed yet.
7597                // add the installer to the resolve list
7598                if (DEBUG_INSTALL) {
7599                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7600                }
7601                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7602                final ComponentName installFailureActivity = findInstallFailureActivity(
7603                        info.activityInfo.packageName,  filterCallingUid, userId);
7604                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7605                        info.activityInfo.packageName, info.activityInfo.splitName,
7606                        installFailureActivity,
7607                        info.activityInfo.applicationInfo.versionCode,
7608                        null /*failureIntent*/);
7609                // make sure this resolver is the default
7610                installerInfo.isDefault = true;
7611                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7612                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7613                // add a non-generic filter
7614                installerInfo.filter = new IntentFilter();
7615                // load resources from the correct package
7616                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7617                resolveInfos.set(i, installerInfo);
7618                continue;
7619            }
7620            // caller is a full app, don't need to apply any other filtering
7621            if (ephemeralPkgName == null) {
7622                continue;
7623            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7624                // caller is same app; don't need to apply any other filtering
7625                continue;
7626            }
7627            // allow activities that have been explicitly exposed to ephemeral apps
7628            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7629            if (!isEphemeralApp
7630                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7631                continue;
7632            }
7633            resolveInfos.remove(i);
7634        }
7635        return resolveInfos;
7636    }
7637
7638    /**
7639     * Returns the activity component that can handle install failures.
7640     * <p>By default, the instant application installer handles failures. However, an
7641     * application may want to handle failures on its own. Applications do this by
7642     * creating an activity with an intent filter that handles the action
7643     * {@link Intent#ACTION_INSTALL_FAILURE}.
7644     */
7645    private @Nullable ComponentName findInstallFailureActivity(
7646            String packageName, int filterCallingUid, int userId) {
7647        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7648        failureActivityIntent.setPackage(packageName);
7649        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7650        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7651                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7652                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7653        final int NR = result.size();
7654        if (NR > 0) {
7655            for (int i = 0; i < NR; i++) {
7656                final ResolveInfo info = result.get(i);
7657                if (info.activityInfo.splitName != null) {
7658                    continue;
7659                }
7660                return new ComponentName(packageName, info.activityInfo.name);
7661            }
7662        }
7663        return null;
7664    }
7665
7666    /**
7667     * @param resolveInfos list of resolve infos in descending priority order
7668     * @return if the list contains a resolve info with non-negative priority
7669     */
7670    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7671        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7672    }
7673
7674    private static boolean hasWebURI(Intent intent) {
7675        if (intent.getData() == null) {
7676            return false;
7677        }
7678        final String scheme = intent.getScheme();
7679        if (TextUtils.isEmpty(scheme)) {
7680            return false;
7681        }
7682        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7683    }
7684
7685    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7686            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7687            int userId) {
7688        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7689
7690        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7691            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7692                    candidates.size());
7693        }
7694
7695        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7696        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7697        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7698        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7699        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7700        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7701
7702        synchronized (mPackages) {
7703            final int count = candidates.size();
7704            // First, try to use linked apps. Partition the candidates into four lists:
7705            // one for the final results, one for the "do not use ever", one for "undefined status"
7706            // and finally one for "browser app type".
7707            for (int n=0; n<count; n++) {
7708                ResolveInfo info = candidates.get(n);
7709                String packageName = info.activityInfo.packageName;
7710                PackageSetting ps = mSettings.mPackages.get(packageName);
7711                if (ps != null) {
7712                    // Add to the special match all list (Browser use case)
7713                    if (info.handleAllWebDataURI) {
7714                        matchAllList.add(info);
7715                        continue;
7716                    }
7717                    // Try to get the status from User settings first
7718                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7719                    int status = (int)(packedStatus >> 32);
7720                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7721                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7722                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7723                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7724                                    + " : linkgen=" + linkGeneration);
7725                        }
7726                        // Use link-enabled generation as preferredOrder, i.e.
7727                        // prefer newly-enabled over earlier-enabled.
7728                        info.preferredOrder = linkGeneration;
7729                        alwaysList.add(info);
7730                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7731                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7732                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7733                        }
7734                        neverList.add(info);
7735                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7736                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7737                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7738                        }
7739                        alwaysAskList.add(info);
7740                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7741                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7742                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7743                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7744                        }
7745                        undefinedList.add(info);
7746                    }
7747                }
7748            }
7749
7750            // We'll want to include browser possibilities in a few cases
7751            boolean includeBrowser = false;
7752
7753            // First try to add the "always" resolution(s) for the current user, if any
7754            if (alwaysList.size() > 0) {
7755                result.addAll(alwaysList);
7756            } else {
7757                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7758                result.addAll(undefinedList);
7759                // Maybe add one for the other profile.
7760                if (xpDomainInfo != null && (
7761                        xpDomainInfo.bestDomainVerificationStatus
7762                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7763                    result.add(xpDomainInfo.resolveInfo);
7764                }
7765                includeBrowser = true;
7766            }
7767
7768            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7769            // If there were 'always' entries their preferred order has been set, so we also
7770            // back that off to make the alternatives equivalent
7771            if (alwaysAskList.size() > 0) {
7772                for (ResolveInfo i : result) {
7773                    i.preferredOrder = 0;
7774                }
7775                result.addAll(alwaysAskList);
7776                includeBrowser = true;
7777            }
7778
7779            if (includeBrowser) {
7780                // Also add browsers (all of them or only the default one)
7781                if (DEBUG_DOMAIN_VERIFICATION) {
7782                    Slog.v(TAG, "   ...including browsers in candidate set");
7783                }
7784                if ((matchFlags & MATCH_ALL) != 0) {
7785                    result.addAll(matchAllList);
7786                } else {
7787                    // Browser/generic handling case.  If there's a default browser, go straight
7788                    // to that (but only if there is no other higher-priority match).
7789                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7790                    int maxMatchPrio = 0;
7791                    ResolveInfo defaultBrowserMatch = null;
7792                    final int numCandidates = matchAllList.size();
7793                    for (int n = 0; n < numCandidates; n++) {
7794                        ResolveInfo info = matchAllList.get(n);
7795                        // track the highest overall match priority...
7796                        if (info.priority > maxMatchPrio) {
7797                            maxMatchPrio = info.priority;
7798                        }
7799                        // ...and the highest-priority default browser match
7800                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7801                            if (defaultBrowserMatch == null
7802                                    || (defaultBrowserMatch.priority < info.priority)) {
7803                                if (debug) {
7804                                    Slog.v(TAG, "Considering default browser match " + info);
7805                                }
7806                                defaultBrowserMatch = info;
7807                            }
7808                        }
7809                    }
7810                    if (defaultBrowserMatch != null
7811                            && defaultBrowserMatch.priority >= maxMatchPrio
7812                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7813                    {
7814                        if (debug) {
7815                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7816                        }
7817                        result.add(defaultBrowserMatch);
7818                    } else {
7819                        result.addAll(matchAllList);
7820                    }
7821                }
7822
7823                // If there is nothing selected, add all candidates and remove the ones that the user
7824                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7825                if (result.size() == 0) {
7826                    result.addAll(candidates);
7827                    result.removeAll(neverList);
7828                }
7829            }
7830        }
7831        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7832            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7833                    result.size());
7834            for (ResolveInfo info : result) {
7835                Slog.v(TAG, "  + " + info.activityInfo);
7836            }
7837        }
7838        return result;
7839    }
7840
7841    // Returns a packed value as a long:
7842    //
7843    // high 'int'-sized word: link status: undefined/ask/never/always.
7844    // low 'int'-sized word: relative priority among 'always' results.
7845    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7846        long result = ps.getDomainVerificationStatusForUser(userId);
7847        // if none available, get the master status
7848        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7849            if (ps.getIntentFilterVerificationInfo() != null) {
7850                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7851            }
7852        }
7853        return result;
7854    }
7855
7856    private ResolveInfo querySkipCurrentProfileIntents(
7857            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7858            int flags, int sourceUserId) {
7859        if (matchingFilters != null) {
7860            int size = matchingFilters.size();
7861            for (int i = 0; i < size; i ++) {
7862                CrossProfileIntentFilter filter = matchingFilters.get(i);
7863                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7864                    // Checking if there are activities in the target user that can handle the
7865                    // intent.
7866                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7867                            resolvedType, flags, sourceUserId);
7868                    if (resolveInfo != null) {
7869                        return resolveInfo;
7870                    }
7871                }
7872            }
7873        }
7874        return null;
7875    }
7876
7877    // Return matching ResolveInfo in target user if any.
7878    private ResolveInfo queryCrossProfileIntents(
7879            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7880            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7881        if (matchingFilters != null) {
7882            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7883            // match the same intent. For performance reasons, it is better not to
7884            // run queryIntent twice for the same userId
7885            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7886            int size = matchingFilters.size();
7887            for (int i = 0; i < size; i++) {
7888                CrossProfileIntentFilter filter = matchingFilters.get(i);
7889                int targetUserId = filter.getTargetUserId();
7890                boolean skipCurrentProfile =
7891                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7892                boolean skipCurrentProfileIfNoMatchFound =
7893                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7894                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7895                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7896                    // Checking if there are activities in the target user that can handle the
7897                    // intent.
7898                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7899                            resolvedType, flags, sourceUserId);
7900                    if (resolveInfo != null) return resolveInfo;
7901                    alreadyTriedUserIds.put(targetUserId, true);
7902                }
7903            }
7904        }
7905        return null;
7906    }
7907
7908    /**
7909     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7910     * will forward the intent to the filter's target user.
7911     * Otherwise, returns null.
7912     */
7913    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7914            String resolvedType, int flags, int sourceUserId) {
7915        int targetUserId = filter.getTargetUserId();
7916        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7917                resolvedType, flags, targetUserId);
7918        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7919            // If all the matches in the target profile are suspended, return null.
7920            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7921                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7922                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7923                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7924                            targetUserId);
7925                }
7926            }
7927        }
7928        return null;
7929    }
7930
7931    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7932            int sourceUserId, int targetUserId) {
7933        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7934        long ident = Binder.clearCallingIdentity();
7935        boolean targetIsProfile;
7936        try {
7937            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7938        } finally {
7939            Binder.restoreCallingIdentity(ident);
7940        }
7941        String className;
7942        if (targetIsProfile) {
7943            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7944        } else {
7945            className = FORWARD_INTENT_TO_PARENT;
7946        }
7947        ComponentName forwardingActivityComponentName = new ComponentName(
7948                mAndroidApplication.packageName, className);
7949        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7950                sourceUserId);
7951        if (!targetIsProfile) {
7952            forwardingActivityInfo.showUserIcon = targetUserId;
7953            forwardingResolveInfo.noResourceId = true;
7954        }
7955        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7956        forwardingResolveInfo.priority = 0;
7957        forwardingResolveInfo.preferredOrder = 0;
7958        forwardingResolveInfo.match = 0;
7959        forwardingResolveInfo.isDefault = true;
7960        forwardingResolveInfo.filter = filter;
7961        forwardingResolveInfo.targetUserId = targetUserId;
7962        return forwardingResolveInfo;
7963    }
7964
7965    @Override
7966    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7967            Intent[] specifics, String[] specificTypes, Intent intent,
7968            String resolvedType, int flags, int userId) {
7969        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7970                specificTypes, intent, resolvedType, flags, userId));
7971    }
7972
7973    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7974            Intent[] specifics, String[] specificTypes, Intent intent,
7975            String resolvedType, int flags, int userId) {
7976        if (!sUserManager.exists(userId)) return Collections.emptyList();
7977        final int callingUid = Binder.getCallingUid();
7978        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7979                false /*includeInstantApps*/);
7980        enforceCrossUserPermission(callingUid, userId,
7981                false /*requireFullPermission*/, false /*checkShell*/,
7982                "query intent activity options");
7983        final String resultsAction = intent.getAction();
7984
7985        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7986                | PackageManager.GET_RESOLVED_FILTER, userId);
7987
7988        if (DEBUG_INTENT_MATCHING) {
7989            Log.v(TAG, "Query " + intent + ": " + results);
7990        }
7991
7992        int specificsPos = 0;
7993        int N;
7994
7995        // todo: note that the algorithm used here is O(N^2).  This
7996        // isn't a problem in our current environment, but if we start running
7997        // into situations where we have more than 5 or 10 matches then this
7998        // should probably be changed to something smarter...
7999
8000        // First we go through and resolve each of the specific items
8001        // that were supplied, taking care of removing any corresponding
8002        // duplicate items in the generic resolve list.
8003        if (specifics != null) {
8004            for (int i=0; i<specifics.length; i++) {
8005                final Intent sintent = specifics[i];
8006                if (sintent == null) {
8007                    continue;
8008                }
8009
8010                if (DEBUG_INTENT_MATCHING) {
8011                    Log.v(TAG, "Specific #" + i + ": " + sintent);
8012                }
8013
8014                String action = sintent.getAction();
8015                if (resultsAction != null && resultsAction.equals(action)) {
8016                    // If this action was explicitly requested, then don't
8017                    // remove things that have it.
8018                    action = null;
8019                }
8020
8021                ResolveInfo ri = null;
8022                ActivityInfo ai = null;
8023
8024                ComponentName comp = sintent.getComponent();
8025                if (comp == null) {
8026                    ri = resolveIntent(
8027                        sintent,
8028                        specificTypes != null ? specificTypes[i] : null,
8029                            flags, userId);
8030                    if (ri == null) {
8031                        continue;
8032                    }
8033                    if (ri == mResolveInfo) {
8034                        // ACK!  Must do something better with this.
8035                    }
8036                    ai = ri.activityInfo;
8037                    comp = new ComponentName(ai.applicationInfo.packageName,
8038                            ai.name);
8039                } else {
8040                    ai = getActivityInfo(comp, flags, userId);
8041                    if (ai == null) {
8042                        continue;
8043                    }
8044                }
8045
8046                // Look for any generic query activities that are duplicates
8047                // of this specific one, and remove them from the results.
8048                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
8049                N = results.size();
8050                int j;
8051                for (j=specificsPos; j<N; j++) {
8052                    ResolveInfo sri = results.get(j);
8053                    if ((sri.activityInfo.name.equals(comp.getClassName())
8054                            && sri.activityInfo.applicationInfo.packageName.equals(
8055                                    comp.getPackageName()))
8056                        || (action != null && sri.filter.matchAction(action))) {
8057                        results.remove(j);
8058                        if (DEBUG_INTENT_MATCHING) Log.v(
8059                            TAG, "Removing duplicate item from " + j
8060                            + " due to specific " + specificsPos);
8061                        if (ri == null) {
8062                            ri = sri;
8063                        }
8064                        j--;
8065                        N--;
8066                    }
8067                }
8068
8069                // Add this specific item to its proper place.
8070                if (ri == null) {
8071                    ri = new ResolveInfo();
8072                    ri.activityInfo = ai;
8073                }
8074                results.add(specificsPos, ri);
8075                ri.specificIndex = i;
8076                specificsPos++;
8077            }
8078        }
8079
8080        // Now we go through the remaining generic results and remove any
8081        // duplicate actions that are found here.
8082        N = results.size();
8083        for (int i=specificsPos; i<N-1; i++) {
8084            final ResolveInfo rii = results.get(i);
8085            if (rii.filter == null) {
8086                continue;
8087            }
8088
8089            // Iterate over all of the actions of this result's intent
8090            // filter...  typically this should be just one.
8091            final Iterator<String> it = rii.filter.actionsIterator();
8092            if (it == null) {
8093                continue;
8094            }
8095            while (it.hasNext()) {
8096                final String action = it.next();
8097                if (resultsAction != null && resultsAction.equals(action)) {
8098                    // If this action was explicitly requested, then don't
8099                    // remove things that have it.
8100                    continue;
8101                }
8102                for (int j=i+1; j<N; j++) {
8103                    final ResolveInfo rij = results.get(j);
8104                    if (rij.filter != null && rij.filter.hasAction(action)) {
8105                        results.remove(j);
8106                        if (DEBUG_INTENT_MATCHING) Log.v(
8107                            TAG, "Removing duplicate item from " + j
8108                            + " due to action " + action + " at " + i);
8109                        j--;
8110                        N--;
8111                    }
8112                }
8113            }
8114
8115            // If the caller didn't request filter information, drop it now
8116            // so we don't have to marshall/unmarshall it.
8117            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8118                rii.filter = null;
8119            }
8120        }
8121
8122        // Filter out the caller activity if so requested.
8123        if (caller != null) {
8124            N = results.size();
8125            for (int i=0; i<N; i++) {
8126                ActivityInfo ainfo = results.get(i).activityInfo;
8127                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8128                        && caller.getClassName().equals(ainfo.name)) {
8129                    results.remove(i);
8130                    break;
8131                }
8132            }
8133        }
8134
8135        // If the caller didn't request filter information,
8136        // drop them now so we don't have to
8137        // marshall/unmarshall it.
8138        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8139            N = results.size();
8140            for (int i=0; i<N; i++) {
8141                results.get(i).filter = null;
8142            }
8143        }
8144
8145        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8146        return results;
8147    }
8148
8149    @Override
8150    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8151            String resolvedType, int flags, int userId) {
8152        return new ParceledListSlice<>(
8153                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8154                        false /*allowDynamicSplits*/));
8155    }
8156
8157    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8158            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8159        if (!sUserManager.exists(userId)) return Collections.emptyList();
8160        final int callingUid = Binder.getCallingUid();
8161        enforceCrossUserPermission(callingUid, userId,
8162                false /*requireFullPermission*/, false /*checkShell*/,
8163                "query intent receivers");
8164        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8165        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8166                false /*includeInstantApps*/);
8167        ComponentName comp = intent.getComponent();
8168        if (comp == null) {
8169            if (intent.getSelector() != null) {
8170                intent = intent.getSelector();
8171                comp = intent.getComponent();
8172            }
8173        }
8174        if (comp != null) {
8175            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8176            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8177            if (ai != null) {
8178                // When specifying an explicit component, we prevent the activity from being
8179                // used when either 1) the calling package is normal and the activity is within
8180                // an instant application or 2) the calling package is ephemeral and the
8181                // activity is not visible to instant applications.
8182                final boolean matchInstantApp =
8183                        (flags & PackageManager.MATCH_INSTANT) != 0;
8184                final boolean matchVisibleToInstantAppOnly =
8185                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8186                final boolean matchExplicitlyVisibleOnly =
8187                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8188                final boolean isCallerInstantApp =
8189                        instantAppPkgName != null;
8190                final boolean isTargetSameInstantApp =
8191                        comp.getPackageName().equals(instantAppPkgName);
8192                final boolean isTargetInstantApp =
8193                        (ai.applicationInfo.privateFlags
8194                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8195                final boolean isTargetVisibleToInstantApp =
8196                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8197                final boolean isTargetExplicitlyVisibleToInstantApp =
8198                        isTargetVisibleToInstantApp
8199                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8200                final boolean isTargetHiddenFromInstantApp =
8201                        !isTargetVisibleToInstantApp
8202                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8203                final boolean blockResolution =
8204                        !isTargetSameInstantApp
8205                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8206                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8207                                        && isTargetHiddenFromInstantApp));
8208                if (!blockResolution) {
8209                    ResolveInfo ri = new ResolveInfo();
8210                    ri.activityInfo = ai;
8211                    list.add(ri);
8212                }
8213            }
8214            return applyPostResolutionFilter(
8215                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8216        }
8217
8218        // reader
8219        synchronized (mPackages) {
8220            String pkgName = intent.getPackage();
8221            if (pkgName == null) {
8222                final List<ResolveInfo> result =
8223                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8224                return applyPostResolutionFilter(
8225                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8226            }
8227            final PackageParser.Package pkg = mPackages.get(pkgName);
8228            if (pkg != null) {
8229                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8230                        intent, resolvedType, flags, pkg.receivers, userId);
8231                return applyPostResolutionFilter(
8232                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8233            }
8234            return Collections.emptyList();
8235        }
8236    }
8237
8238    @Override
8239    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8240        final int callingUid = Binder.getCallingUid();
8241        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8242    }
8243
8244    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8245            int userId, int callingUid) {
8246        if (!sUserManager.exists(userId)) return null;
8247        flags = updateFlagsForResolve(
8248                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8249        List<ResolveInfo> query = queryIntentServicesInternal(
8250                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8251        if (query != null) {
8252            if (query.size() >= 1) {
8253                // If there is more than one service with the same priority,
8254                // just arbitrarily pick the first one.
8255                return query.get(0);
8256            }
8257        }
8258        return null;
8259    }
8260
8261    @Override
8262    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8263            String resolvedType, int flags, int userId) {
8264        final int callingUid = Binder.getCallingUid();
8265        return new ParceledListSlice<>(queryIntentServicesInternal(
8266                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8267    }
8268
8269    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8270            String resolvedType, int flags, int userId, int callingUid,
8271            boolean includeInstantApps) {
8272        if (!sUserManager.exists(userId)) return Collections.emptyList();
8273        enforceCrossUserPermission(callingUid, userId,
8274                false /*requireFullPermission*/, false /*checkShell*/,
8275                "query intent receivers");
8276        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8277        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8278        ComponentName comp = intent.getComponent();
8279        if (comp == null) {
8280            if (intent.getSelector() != null) {
8281                intent = intent.getSelector();
8282                comp = intent.getComponent();
8283            }
8284        }
8285        if (comp != null) {
8286            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8287            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8288            if (si != null) {
8289                // When specifying an explicit component, we prevent the service from being
8290                // used when either 1) the service is in an instant application and the
8291                // caller is not the same instant application or 2) the calling package is
8292                // ephemeral and the activity is not visible to ephemeral applications.
8293                final boolean matchInstantApp =
8294                        (flags & PackageManager.MATCH_INSTANT) != 0;
8295                final boolean matchVisibleToInstantAppOnly =
8296                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8297                final boolean isCallerInstantApp =
8298                        instantAppPkgName != null;
8299                final boolean isTargetSameInstantApp =
8300                        comp.getPackageName().equals(instantAppPkgName);
8301                final boolean isTargetInstantApp =
8302                        (si.applicationInfo.privateFlags
8303                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8304                final boolean isTargetHiddenFromInstantApp =
8305                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8306                final boolean blockResolution =
8307                        !isTargetSameInstantApp
8308                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8309                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8310                                        && isTargetHiddenFromInstantApp));
8311                if (!blockResolution) {
8312                    final ResolveInfo ri = new ResolveInfo();
8313                    ri.serviceInfo = si;
8314                    list.add(ri);
8315                }
8316            }
8317            return list;
8318        }
8319
8320        // reader
8321        synchronized (mPackages) {
8322            String pkgName = intent.getPackage();
8323            if (pkgName == null) {
8324                return applyPostServiceResolutionFilter(
8325                        mServices.queryIntent(intent, resolvedType, flags, userId),
8326                        instantAppPkgName);
8327            }
8328            final PackageParser.Package pkg = mPackages.get(pkgName);
8329            if (pkg != null) {
8330                return applyPostServiceResolutionFilter(
8331                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8332                                userId),
8333                        instantAppPkgName);
8334            }
8335            return Collections.emptyList();
8336        }
8337    }
8338
8339    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8340            String instantAppPkgName) {
8341        if (instantAppPkgName == null) {
8342            return resolveInfos;
8343        }
8344        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8345            final ResolveInfo info = resolveInfos.get(i);
8346            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8347            // allow services that are defined in the provided package
8348            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8349                if (info.serviceInfo.splitName != null
8350                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8351                                info.serviceInfo.splitName)) {
8352                    // requested service is defined in a split that hasn't been installed yet.
8353                    // add the installer to the resolve list
8354                    if (DEBUG_EPHEMERAL) {
8355                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8356                    }
8357                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8358                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8359                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8360                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8361                            null /*failureIntent*/);
8362                    // make sure this resolver is the default
8363                    installerInfo.isDefault = true;
8364                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8365                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8366                    // add a non-generic filter
8367                    installerInfo.filter = new IntentFilter();
8368                    // load resources from the correct package
8369                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8370                    resolveInfos.set(i, installerInfo);
8371                }
8372                continue;
8373            }
8374            // allow services that have been explicitly exposed to ephemeral apps
8375            if (!isEphemeralApp
8376                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8377                continue;
8378            }
8379            resolveInfos.remove(i);
8380        }
8381        return resolveInfos;
8382    }
8383
8384    @Override
8385    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8386            String resolvedType, int flags, int userId) {
8387        return new ParceledListSlice<>(
8388                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8389    }
8390
8391    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8392            Intent intent, String resolvedType, int flags, int userId) {
8393        if (!sUserManager.exists(userId)) return Collections.emptyList();
8394        final int callingUid = Binder.getCallingUid();
8395        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8396        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8397                false /*includeInstantApps*/);
8398        ComponentName comp = intent.getComponent();
8399        if (comp == null) {
8400            if (intent.getSelector() != null) {
8401                intent = intent.getSelector();
8402                comp = intent.getComponent();
8403            }
8404        }
8405        if (comp != null) {
8406            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8407            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8408            if (pi != null) {
8409                // When specifying an explicit component, we prevent the provider from being
8410                // used when either 1) the provider is in an instant application and the
8411                // caller is not the same instant application or 2) the calling package is an
8412                // instant application and the provider is not visible to instant applications.
8413                final boolean matchInstantApp =
8414                        (flags & PackageManager.MATCH_INSTANT) != 0;
8415                final boolean matchVisibleToInstantAppOnly =
8416                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8417                final boolean isCallerInstantApp =
8418                        instantAppPkgName != null;
8419                final boolean isTargetSameInstantApp =
8420                        comp.getPackageName().equals(instantAppPkgName);
8421                final boolean isTargetInstantApp =
8422                        (pi.applicationInfo.privateFlags
8423                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8424                final boolean isTargetHiddenFromInstantApp =
8425                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8426                final boolean blockResolution =
8427                        !isTargetSameInstantApp
8428                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8429                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8430                                        && isTargetHiddenFromInstantApp));
8431                if (!blockResolution) {
8432                    final ResolveInfo ri = new ResolveInfo();
8433                    ri.providerInfo = pi;
8434                    list.add(ri);
8435                }
8436            }
8437            return list;
8438        }
8439
8440        // reader
8441        synchronized (mPackages) {
8442            String pkgName = intent.getPackage();
8443            if (pkgName == null) {
8444                return applyPostContentProviderResolutionFilter(
8445                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8446                        instantAppPkgName);
8447            }
8448            final PackageParser.Package pkg = mPackages.get(pkgName);
8449            if (pkg != null) {
8450                return applyPostContentProviderResolutionFilter(
8451                        mProviders.queryIntentForPackage(
8452                        intent, resolvedType, flags, pkg.providers, userId),
8453                        instantAppPkgName);
8454            }
8455            return Collections.emptyList();
8456        }
8457    }
8458
8459    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8460            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8461        if (instantAppPkgName == null) {
8462            return resolveInfos;
8463        }
8464        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8465            final ResolveInfo info = resolveInfos.get(i);
8466            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8467            // allow providers that are defined in the provided package
8468            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8469                if (info.providerInfo.splitName != null
8470                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8471                                info.providerInfo.splitName)) {
8472                    // requested provider is defined in a split that hasn't been installed yet.
8473                    // add the installer to the resolve list
8474                    if (DEBUG_EPHEMERAL) {
8475                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8476                    }
8477                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8478                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8479                            info.providerInfo.packageName, info.providerInfo.splitName,
8480                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8481                            null /*failureIntent*/);
8482                    // make sure this resolver is the default
8483                    installerInfo.isDefault = true;
8484                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8485                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8486                    // add a non-generic filter
8487                    installerInfo.filter = new IntentFilter();
8488                    // load resources from the correct package
8489                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8490                    resolveInfos.set(i, installerInfo);
8491                }
8492                continue;
8493            }
8494            // allow providers that have been explicitly exposed to instant applications
8495            if (!isEphemeralApp
8496                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8497                continue;
8498            }
8499            resolveInfos.remove(i);
8500        }
8501        return resolveInfos;
8502    }
8503
8504    @Override
8505    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8506        final int callingUid = Binder.getCallingUid();
8507        if (getInstantAppPackageName(callingUid) != null) {
8508            return ParceledListSlice.emptyList();
8509        }
8510        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8511        flags = updateFlagsForPackage(flags, userId, null);
8512        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8513        enforceCrossUserPermission(callingUid, userId,
8514                true /* requireFullPermission */, false /* checkShell */,
8515                "get installed packages");
8516
8517        // writer
8518        synchronized (mPackages) {
8519            ArrayList<PackageInfo> list;
8520            if (listUninstalled) {
8521                list = new ArrayList<>(mSettings.mPackages.size());
8522                for (PackageSetting ps : mSettings.mPackages.values()) {
8523                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8524                        continue;
8525                    }
8526                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8527                        continue;
8528                    }
8529                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8530                    if (pi != null) {
8531                        list.add(pi);
8532                    }
8533                }
8534            } else {
8535                list = new ArrayList<>(mPackages.size());
8536                for (PackageParser.Package p : mPackages.values()) {
8537                    final PackageSetting ps = (PackageSetting) p.mExtras;
8538                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8539                        continue;
8540                    }
8541                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8542                        continue;
8543                    }
8544                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8545                            p.mExtras, flags, userId);
8546                    if (pi != null) {
8547                        list.add(pi);
8548                    }
8549                }
8550            }
8551
8552            return new ParceledListSlice<>(list);
8553        }
8554    }
8555
8556    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8557            String[] permissions, boolean[] tmp, int flags, int userId) {
8558        int numMatch = 0;
8559        final PermissionsState permissionsState = ps.getPermissionsState();
8560        for (int i=0; i<permissions.length; i++) {
8561            final String permission = permissions[i];
8562            if (permissionsState.hasPermission(permission, userId)) {
8563                tmp[i] = true;
8564                numMatch++;
8565            } else {
8566                tmp[i] = false;
8567            }
8568        }
8569        if (numMatch == 0) {
8570            return;
8571        }
8572        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8573
8574        // The above might return null in cases of uninstalled apps or install-state
8575        // skew across users/profiles.
8576        if (pi != null) {
8577            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8578                if (numMatch == permissions.length) {
8579                    pi.requestedPermissions = permissions;
8580                } else {
8581                    pi.requestedPermissions = new String[numMatch];
8582                    numMatch = 0;
8583                    for (int i=0; i<permissions.length; i++) {
8584                        if (tmp[i]) {
8585                            pi.requestedPermissions[numMatch] = permissions[i];
8586                            numMatch++;
8587                        }
8588                    }
8589                }
8590            }
8591            list.add(pi);
8592        }
8593    }
8594
8595    @Override
8596    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8597            String[] permissions, int flags, int userId) {
8598        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8599        flags = updateFlagsForPackage(flags, userId, permissions);
8600        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8601                true /* requireFullPermission */, false /* checkShell */,
8602                "get packages holding permissions");
8603        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8604
8605        // writer
8606        synchronized (mPackages) {
8607            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8608            boolean[] tmpBools = new boolean[permissions.length];
8609            if (listUninstalled) {
8610                for (PackageSetting ps : mSettings.mPackages.values()) {
8611                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8612                            userId);
8613                }
8614            } else {
8615                for (PackageParser.Package pkg : mPackages.values()) {
8616                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8617                    if (ps != null) {
8618                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8619                                userId);
8620                    }
8621                }
8622            }
8623
8624            return new ParceledListSlice<PackageInfo>(list);
8625        }
8626    }
8627
8628    @Override
8629    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8630        final int callingUid = Binder.getCallingUid();
8631        if (getInstantAppPackageName(callingUid) != null) {
8632            return ParceledListSlice.emptyList();
8633        }
8634        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8635        flags = updateFlagsForApplication(flags, userId, null);
8636        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8637
8638        // writer
8639        synchronized (mPackages) {
8640            ArrayList<ApplicationInfo> list;
8641            if (listUninstalled) {
8642                list = new ArrayList<>(mSettings.mPackages.size());
8643                for (PackageSetting ps : mSettings.mPackages.values()) {
8644                    ApplicationInfo ai;
8645                    int effectiveFlags = flags;
8646                    if (ps.isSystem()) {
8647                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8648                    }
8649                    if (ps.pkg != null) {
8650                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8651                            continue;
8652                        }
8653                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8654                            continue;
8655                        }
8656                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8657                                ps.readUserState(userId), userId);
8658                        if (ai != null) {
8659                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8660                        }
8661                    } else {
8662                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8663                        // and already converts to externally visible package name
8664                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8665                                callingUid, effectiveFlags, userId);
8666                    }
8667                    if (ai != null) {
8668                        list.add(ai);
8669                    }
8670                }
8671            } else {
8672                list = new ArrayList<>(mPackages.size());
8673                for (PackageParser.Package p : mPackages.values()) {
8674                    if (p.mExtras != null) {
8675                        PackageSetting ps = (PackageSetting) p.mExtras;
8676                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8677                            continue;
8678                        }
8679                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8680                            continue;
8681                        }
8682                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8683                                ps.readUserState(userId), userId);
8684                        if (ai != null) {
8685                            ai.packageName = resolveExternalPackageNameLPr(p);
8686                            list.add(ai);
8687                        }
8688                    }
8689                }
8690            }
8691
8692            return new ParceledListSlice<>(list);
8693        }
8694    }
8695
8696    @Override
8697    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8698        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8699            return null;
8700        }
8701        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8702            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8703                    "getEphemeralApplications");
8704        }
8705        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8706                true /* requireFullPermission */, false /* checkShell */,
8707                "getEphemeralApplications");
8708        synchronized (mPackages) {
8709            List<InstantAppInfo> instantApps = mInstantAppRegistry
8710                    .getInstantAppsLPr(userId);
8711            if (instantApps != null) {
8712                return new ParceledListSlice<>(instantApps);
8713            }
8714        }
8715        return null;
8716    }
8717
8718    @Override
8719    public boolean isInstantApp(String packageName, int userId) {
8720        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8721                true /* requireFullPermission */, false /* checkShell */,
8722                "isInstantApp");
8723        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8724            return false;
8725        }
8726
8727        synchronized (mPackages) {
8728            int callingUid = Binder.getCallingUid();
8729            if (Process.isIsolated(callingUid)) {
8730                callingUid = mIsolatedOwners.get(callingUid);
8731            }
8732            final PackageSetting ps = mSettings.mPackages.get(packageName);
8733            PackageParser.Package pkg = mPackages.get(packageName);
8734            final boolean returnAllowed =
8735                    ps != null
8736                    && (isCallerSameApp(packageName, callingUid)
8737                            || canViewInstantApps(callingUid, userId)
8738                            || mInstantAppRegistry.isInstantAccessGranted(
8739                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8740            if (returnAllowed) {
8741                return ps.getInstantApp(userId);
8742            }
8743        }
8744        return false;
8745    }
8746
8747    @Override
8748    public byte[] getInstantAppCookie(String packageName, int userId) {
8749        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8750            return null;
8751        }
8752
8753        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8754                true /* requireFullPermission */, false /* checkShell */,
8755                "getInstantAppCookie");
8756        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8757            return null;
8758        }
8759        synchronized (mPackages) {
8760            return mInstantAppRegistry.getInstantAppCookieLPw(
8761                    packageName, userId);
8762        }
8763    }
8764
8765    @Override
8766    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8767        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8768            return true;
8769        }
8770
8771        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8772                true /* requireFullPermission */, true /* checkShell */,
8773                "setInstantAppCookie");
8774        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8775            return false;
8776        }
8777        synchronized (mPackages) {
8778            return mInstantAppRegistry.setInstantAppCookieLPw(
8779                    packageName, cookie, userId);
8780        }
8781    }
8782
8783    @Override
8784    public Bitmap getInstantAppIcon(String packageName, int userId) {
8785        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8786            return null;
8787        }
8788
8789        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8790            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8791                    "getInstantAppIcon");
8792        }
8793        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8794                true /* requireFullPermission */, false /* checkShell */,
8795                "getInstantAppIcon");
8796
8797        synchronized (mPackages) {
8798            return mInstantAppRegistry.getInstantAppIconLPw(
8799                    packageName, userId);
8800        }
8801    }
8802
8803    private boolean isCallerSameApp(String packageName, int uid) {
8804        PackageParser.Package pkg = mPackages.get(packageName);
8805        return pkg != null
8806                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8807    }
8808
8809    @Override
8810    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8811        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8812            return ParceledListSlice.emptyList();
8813        }
8814        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8815    }
8816
8817    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8818        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8819
8820        // reader
8821        synchronized (mPackages) {
8822            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8823            final int userId = UserHandle.getCallingUserId();
8824            while (i.hasNext()) {
8825                final PackageParser.Package p = i.next();
8826                if (p.applicationInfo == null) continue;
8827
8828                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8829                        && !p.applicationInfo.isDirectBootAware();
8830                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8831                        && p.applicationInfo.isDirectBootAware();
8832
8833                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8834                        && (!mSafeMode || isSystemApp(p))
8835                        && (matchesUnaware || matchesAware)) {
8836                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8837                    if (ps != null) {
8838                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8839                                ps.readUserState(userId), userId);
8840                        if (ai != null) {
8841                            finalList.add(ai);
8842                        }
8843                    }
8844                }
8845            }
8846        }
8847
8848        return finalList;
8849    }
8850
8851    @Override
8852    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8853        if (!sUserManager.exists(userId)) return null;
8854        flags = updateFlagsForComponent(flags, userId, name);
8855        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8856        // reader
8857        synchronized (mPackages) {
8858            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8859            PackageSetting ps = provider != null
8860                    ? mSettings.mPackages.get(provider.owner.packageName)
8861                    : null;
8862            if (ps != null) {
8863                final boolean isInstantApp = ps.getInstantApp(userId);
8864                // normal application; filter out instant application provider
8865                if (instantAppPkgName == null && isInstantApp) {
8866                    return null;
8867                }
8868                // instant application; filter out other instant applications
8869                if (instantAppPkgName != null
8870                        && isInstantApp
8871                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8872                    return null;
8873                }
8874                // instant application; filter out non-exposed provider
8875                if (instantAppPkgName != null
8876                        && !isInstantApp
8877                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8878                    return null;
8879                }
8880                // provider not enabled
8881                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8882                    return null;
8883                }
8884                return PackageParser.generateProviderInfo(
8885                        provider, flags, ps.readUserState(userId), userId);
8886            }
8887            return null;
8888        }
8889    }
8890
8891    /**
8892     * @deprecated
8893     */
8894    @Deprecated
8895    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8896        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8897            return;
8898        }
8899        // reader
8900        synchronized (mPackages) {
8901            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8902                    .entrySet().iterator();
8903            final int userId = UserHandle.getCallingUserId();
8904            while (i.hasNext()) {
8905                Map.Entry<String, PackageParser.Provider> entry = i.next();
8906                PackageParser.Provider p = entry.getValue();
8907                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8908
8909                if (ps != null && p.syncable
8910                        && (!mSafeMode || (p.info.applicationInfo.flags
8911                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8912                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8913                            ps.readUserState(userId), userId);
8914                    if (info != null) {
8915                        outNames.add(entry.getKey());
8916                        outInfo.add(info);
8917                    }
8918                }
8919            }
8920        }
8921    }
8922
8923    @Override
8924    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8925            int uid, int flags, String metaDataKey) {
8926        final int callingUid = Binder.getCallingUid();
8927        final int userId = processName != null ? UserHandle.getUserId(uid)
8928                : UserHandle.getCallingUserId();
8929        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8930        flags = updateFlagsForComponent(flags, userId, processName);
8931        ArrayList<ProviderInfo> finalList = null;
8932        // reader
8933        synchronized (mPackages) {
8934            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8935            while (i.hasNext()) {
8936                final PackageParser.Provider p = i.next();
8937                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8938                if (ps != null && p.info.authority != null
8939                        && (processName == null
8940                                || (p.info.processName.equals(processName)
8941                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8942                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8943
8944                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8945                    // parameter.
8946                    if (metaDataKey != null
8947                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8948                        continue;
8949                    }
8950                    final ComponentName component =
8951                            new ComponentName(p.info.packageName, p.info.name);
8952                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8953                        continue;
8954                    }
8955                    if (finalList == null) {
8956                        finalList = new ArrayList<ProviderInfo>(3);
8957                    }
8958                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8959                            ps.readUserState(userId), userId);
8960                    if (info != null) {
8961                        finalList.add(info);
8962                    }
8963                }
8964            }
8965        }
8966
8967        if (finalList != null) {
8968            Collections.sort(finalList, mProviderInitOrderSorter);
8969            return new ParceledListSlice<ProviderInfo>(finalList);
8970        }
8971
8972        return ParceledListSlice.emptyList();
8973    }
8974
8975    @Override
8976    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8977        // reader
8978        synchronized (mPackages) {
8979            final int callingUid = Binder.getCallingUid();
8980            final int callingUserId = UserHandle.getUserId(callingUid);
8981            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8982            if (ps == null) return null;
8983            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8984                return null;
8985            }
8986            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8987            return PackageParser.generateInstrumentationInfo(i, flags);
8988        }
8989    }
8990
8991    @Override
8992    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8993            String targetPackage, int flags) {
8994        final int callingUid = Binder.getCallingUid();
8995        final int callingUserId = UserHandle.getUserId(callingUid);
8996        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8997        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8998            return ParceledListSlice.emptyList();
8999        }
9000        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
9001    }
9002
9003    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
9004            int flags) {
9005        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
9006
9007        // reader
9008        synchronized (mPackages) {
9009            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
9010            while (i.hasNext()) {
9011                final PackageParser.Instrumentation p = i.next();
9012                if (targetPackage == null
9013                        || targetPackage.equals(p.info.targetPackage)) {
9014                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
9015                            flags);
9016                    if (ii != null) {
9017                        finalList.add(ii);
9018                    }
9019                }
9020            }
9021        }
9022
9023        return finalList;
9024    }
9025
9026    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
9027        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
9028        try {
9029            scanDirLI(dir, parseFlags, scanFlags, currentTime);
9030        } finally {
9031            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9032        }
9033    }
9034
9035    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
9036        final File[] files = dir.listFiles();
9037        if (ArrayUtils.isEmpty(files)) {
9038            Log.d(TAG, "No files in app dir " + dir);
9039            return;
9040        }
9041
9042        if (DEBUG_PACKAGE_SCANNING) {
9043            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
9044                    + " flags=0x" + Integer.toHexString(parseFlags));
9045        }
9046        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
9047                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
9048                mParallelPackageParserCallback);
9049
9050        // Submit files for parsing in parallel
9051        int fileCount = 0;
9052        for (File file : files) {
9053            final boolean isPackage = (isApkFile(file) || file.isDirectory())
9054                    && !PackageInstallerService.isStageName(file.getName());
9055            if (!isPackage) {
9056                // Ignore entries which are not packages
9057                continue;
9058            }
9059            parallelPackageParser.submit(file, parseFlags);
9060            fileCount++;
9061        }
9062
9063        // Process results one by one
9064        for (; fileCount > 0; fileCount--) {
9065            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
9066            Throwable throwable = parseResult.throwable;
9067            int errorCode = PackageManager.INSTALL_SUCCEEDED;
9068
9069            if (throwable == null) {
9070                // Static shared libraries have synthetic package names
9071                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
9072                    renameStaticSharedLibraryPackage(parseResult.pkg);
9073                }
9074                try {
9075                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
9076                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
9077                                currentTime, null);
9078                    }
9079                } catch (PackageManagerException e) {
9080                    errorCode = e.error;
9081                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
9082                }
9083            } else if (throwable instanceof PackageParser.PackageParserException) {
9084                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9085                        throwable;
9086                errorCode = e.error;
9087                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9088            } else {
9089                throw new IllegalStateException("Unexpected exception occurred while parsing "
9090                        + parseResult.scanFile, throwable);
9091            }
9092
9093            // Delete invalid userdata apps
9094            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
9095                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
9096                logCriticalInfo(Log.WARN,
9097                        "Deleting invalid package at " + parseResult.scanFile);
9098                removeCodePathLI(parseResult.scanFile);
9099            }
9100        }
9101        parallelPackageParser.close();
9102    }
9103
9104    private static File getSettingsProblemFile() {
9105        File dataDir = Environment.getDataDirectory();
9106        File systemDir = new File(dataDir, "system");
9107        File fname = new File(systemDir, "uiderrors.txt");
9108        return fname;
9109    }
9110
9111    static void reportSettingsProblem(int priority, String msg) {
9112        logCriticalInfo(priority, msg);
9113    }
9114
9115    public static void logCriticalInfo(int priority, String msg) {
9116        Slog.println(priority, TAG, msg);
9117        EventLogTags.writePmCriticalInfo(msg);
9118        try {
9119            File fname = getSettingsProblemFile();
9120            FileOutputStream out = new FileOutputStream(fname, true);
9121            PrintWriter pw = new FastPrintWriter(out);
9122            SimpleDateFormat formatter = new SimpleDateFormat();
9123            String dateString = formatter.format(new Date(System.currentTimeMillis()));
9124            pw.println(dateString + ": " + msg);
9125            pw.close();
9126            FileUtils.setPermissions(
9127                    fname.toString(),
9128                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9129                    -1, -1);
9130        } catch (java.io.IOException e) {
9131        }
9132    }
9133
9134    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9135        if (srcFile.isDirectory()) {
9136            final File baseFile = new File(pkg.baseCodePath);
9137            long maxModifiedTime = baseFile.lastModified();
9138            if (pkg.splitCodePaths != null) {
9139                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9140                    final File splitFile = new File(pkg.splitCodePaths[i]);
9141                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9142                }
9143            }
9144            return maxModifiedTime;
9145        }
9146        return srcFile.lastModified();
9147    }
9148
9149    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9150            final int policyFlags) throws PackageManagerException {
9151        // When upgrading from pre-N MR1, verify the package time stamp using the package
9152        // directory and not the APK file.
9153        final long lastModifiedTime = mIsPreNMR1Upgrade
9154                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9155        if (ps != null
9156                && ps.codePath.equals(srcFile)
9157                && ps.timeStamp == lastModifiedTime
9158                && !isCompatSignatureUpdateNeeded(pkg)
9159                && !isRecoverSignatureUpdateNeeded(pkg)) {
9160            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9161            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9162            ArraySet<PublicKey> signingKs;
9163            synchronized (mPackages) {
9164                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9165            }
9166            if (ps.signatures.mSignatures != null
9167                    && ps.signatures.mSignatures.length != 0
9168                    && signingKs != null) {
9169                // Optimization: reuse the existing cached certificates
9170                // if the package appears to be unchanged.
9171                pkg.mSignatures = ps.signatures.mSignatures;
9172                pkg.mSigningKeys = signingKs;
9173                return;
9174            }
9175
9176            Slog.w(TAG, "PackageSetting for " + ps.name
9177                    + " is missing signatures.  Collecting certs again to recover them.");
9178        } else {
9179            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9180        }
9181
9182        try {
9183            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9184            PackageParser.collectCertificates(pkg, policyFlags);
9185        } catch (PackageParserException e) {
9186            throw PackageManagerException.from(e);
9187        } finally {
9188            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9189        }
9190    }
9191
9192    /**
9193     *  Traces a package scan.
9194     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9195     */
9196    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9197            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9198        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9199        try {
9200            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9201        } finally {
9202            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9203        }
9204    }
9205
9206    /**
9207     *  Scans a package and returns the newly parsed package.
9208     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9209     */
9210    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9211            long currentTime, UserHandle user) throws PackageManagerException {
9212        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9213        PackageParser pp = new PackageParser();
9214        pp.setSeparateProcesses(mSeparateProcesses);
9215        pp.setOnlyCoreApps(mOnlyCore);
9216        pp.setDisplayMetrics(mMetrics);
9217        pp.setCallback(mPackageParserCallback);
9218
9219        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9220            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9221        }
9222
9223        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9224        final PackageParser.Package pkg;
9225        try {
9226            pkg = pp.parsePackage(scanFile, parseFlags);
9227        } catch (PackageParserException e) {
9228            throw PackageManagerException.from(e);
9229        } finally {
9230            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9231        }
9232
9233        // Static shared libraries have synthetic package names
9234        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9235            renameStaticSharedLibraryPackage(pkg);
9236        }
9237
9238        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9239    }
9240
9241    /**
9242     *  Scans a package and returns the newly parsed package.
9243     *  @throws PackageManagerException on a parse error.
9244     */
9245    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9246            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9247            throws PackageManagerException {
9248        // If the package has children and this is the first dive in the function
9249        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9250        // packages (parent and children) would be successfully scanned before the
9251        // actual scan since scanning mutates internal state and we want to atomically
9252        // install the package and its children.
9253        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9254            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9255                scanFlags |= SCAN_CHECK_ONLY;
9256            }
9257        } else {
9258            scanFlags &= ~SCAN_CHECK_ONLY;
9259        }
9260
9261        // Scan the parent
9262        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9263                scanFlags, currentTime, user);
9264
9265        // Scan the children
9266        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9267        for (int i = 0; i < childCount; i++) {
9268            PackageParser.Package childPackage = pkg.childPackages.get(i);
9269            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9270                    currentTime, user);
9271        }
9272
9273
9274        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9275            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9276        }
9277
9278        return scannedPkg;
9279    }
9280
9281    /**
9282     *  Scans a package and returns the newly parsed package.
9283     *  @throws PackageManagerException on a parse error.
9284     */
9285    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9286            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9287            throws PackageManagerException {
9288        PackageSetting ps = null;
9289        PackageSetting updatedPkg;
9290        // reader
9291        synchronized (mPackages) {
9292            // Look to see if we already know about this package.
9293            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9294            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9295                // This package has been renamed to its original name.  Let's
9296                // use that.
9297                ps = mSettings.getPackageLPr(oldName);
9298            }
9299            // If there was no original package, see one for the real package name.
9300            if (ps == null) {
9301                ps = mSettings.getPackageLPr(pkg.packageName);
9302            }
9303            // Check to see if this package could be hiding/updating a system
9304            // package.  Must look for it either under the original or real
9305            // package name depending on our state.
9306            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9307            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9308
9309            // If this is a package we don't know about on the system partition, we
9310            // may need to remove disabled child packages on the system partition
9311            // or may need to not add child packages if the parent apk is updated
9312            // on the data partition and no longer defines this child package.
9313            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9314                // If this is a parent package for an updated system app and this system
9315                // app got an OTA update which no longer defines some of the child packages
9316                // we have to prune them from the disabled system packages.
9317                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9318                if (disabledPs != null) {
9319                    final int scannedChildCount = (pkg.childPackages != null)
9320                            ? pkg.childPackages.size() : 0;
9321                    final int disabledChildCount = disabledPs.childPackageNames != null
9322                            ? disabledPs.childPackageNames.size() : 0;
9323                    for (int i = 0; i < disabledChildCount; i++) {
9324                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9325                        boolean disabledPackageAvailable = false;
9326                        for (int j = 0; j < scannedChildCount; j++) {
9327                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9328                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9329                                disabledPackageAvailable = true;
9330                                break;
9331                            }
9332                         }
9333                         if (!disabledPackageAvailable) {
9334                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9335                         }
9336                    }
9337                }
9338            }
9339        }
9340
9341        final boolean isUpdatedPkg = updatedPkg != null;
9342        final boolean isUpdatedSystemPkg = isUpdatedPkg
9343                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9344        boolean isUpdatedPkgBetter = false;
9345        // First check if this is a system package that may involve an update
9346        if (isUpdatedSystemPkg) {
9347            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9348            // it needs to drop FLAG_PRIVILEGED.
9349            if (locationIsPrivileged(scanFile)) {
9350                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9351            } else {
9352                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9353            }
9354
9355            if (ps != null && !ps.codePath.equals(scanFile)) {
9356                // The path has changed from what was last scanned...  check the
9357                // version of the new path against what we have stored to determine
9358                // what to do.
9359                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9360                if (pkg.mVersionCode <= ps.versionCode) {
9361                    // The system package has been updated and the code path does not match
9362                    // Ignore entry. Skip it.
9363                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9364                            + " ignored: updated version " + ps.versionCode
9365                            + " better than this " + pkg.mVersionCode);
9366                    if (!updatedPkg.codePath.equals(scanFile)) {
9367                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9368                                + ps.name + " changing from " + updatedPkg.codePathString
9369                                + " to " + scanFile);
9370                        updatedPkg.codePath = scanFile;
9371                        updatedPkg.codePathString = scanFile.toString();
9372                        updatedPkg.resourcePath = scanFile;
9373                        updatedPkg.resourcePathString = scanFile.toString();
9374                    }
9375                    updatedPkg.pkg = pkg;
9376                    updatedPkg.versionCode = pkg.mVersionCode;
9377
9378                    // Update the disabled system child packages to point to the package too.
9379                    final int childCount = updatedPkg.childPackageNames != null
9380                            ? updatedPkg.childPackageNames.size() : 0;
9381                    for (int i = 0; i < childCount; i++) {
9382                        String childPackageName = updatedPkg.childPackageNames.get(i);
9383                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9384                                childPackageName);
9385                        if (updatedChildPkg != null) {
9386                            updatedChildPkg.pkg = pkg;
9387                            updatedChildPkg.versionCode = pkg.mVersionCode;
9388                        }
9389                    }
9390                } else {
9391                    // The current app on the system partition is better than
9392                    // what we have updated to on the data partition; switch
9393                    // back to the system partition version.
9394                    // At this point, its safely assumed that package installation for
9395                    // apps in system partition will go through. If not there won't be a working
9396                    // version of the app
9397                    // writer
9398                    synchronized (mPackages) {
9399                        // Just remove the loaded entries from package lists.
9400                        mPackages.remove(ps.name);
9401                    }
9402
9403                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9404                            + " reverting from " + ps.codePathString
9405                            + ": new version " + pkg.mVersionCode
9406                            + " better than installed " + ps.versionCode);
9407
9408                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9409                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9410                    synchronized (mInstallLock) {
9411                        args.cleanUpResourcesLI();
9412                    }
9413                    synchronized (mPackages) {
9414                        mSettings.enableSystemPackageLPw(ps.name);
9415                    }
9416                    isUpdatedPkgBetter = true;
9417                }
9418            }
9419        }
9420
9421        String resourcePath = null;
9422        String baseResourcePath = null;
9423        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9424            if (ps != null && ps.resourcePathString != null) {
9425                resourcePath = ps.resourcePathString;
9426                baseResourcePath = ps.resourcePathString;
9427            } else {
9428                // Should not happen at all. Just log an error.
9429                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9430            }
9431        } else {
9432            resourcePath = pkg.codePath;
9433            baseResourcePath = pkg.baseCodePath;
9434        }
9435
9436        // Set application objects path explicitly.
9437        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9438        pkg.setApplicationInfoCodePath(pkg.codePath);
9439        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9440        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9441        pkg.setApplicationInfoResourcePath(resourcePath);
9442        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9443        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9444
9445        // throw an exception if we have an update to a system application, but, it's not more
9446        // recent than the package we've already scanned
9447        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9448            // Set CPU Abis to application info.
9449            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9450                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
9451                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
9452            } else {
9453                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
9454                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
9455            }
9456
9457            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9458                    + scanFile + " ignored: updated version " + ps.versionCode
9459                    + " better than this " + pkg.mVersionCode);
9460        }
9461
9462        if (isUpdatedPkg) {
9463            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9464            // initially
9465            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9466
9467            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9468            // flag set initially
9469            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9470                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9471            }
9472        }
9473
9474        // Verify certificates against what was last scanned
9475        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9476
9477        /*
9478         * A new system app appeared, but we already had a non-system one of the
9479         * same name installed earlier.
9480         */
9481        boolean shouldHideSystemApp = false;
9482        if (!isUpdatedPkg && ps != null
9483                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9484            /*
9485             * Check to make sure the signatures match first. If they don't,
9486             * wipe the installed application and its data.
9487             */
9488            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9489                    != PackageManager.SIGNATURE_MATCH) {
9490                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9491                        + " signatures don't match existing userdata copy; removing");
9492                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9493                        "scanPackageInternalLI")) {
9494                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9495                }
9496                ps = null;
9497            } else {
9498                /*
9499                 * If the newly-added system app is an older version than the
9500                 * already installed version, hide it. It will be scanned later
9501                 * and re-added like an update.
9502                 */
9503                if (pkg.mVersionCode <= ps.versionCode) {
9504                    shouldHideSystemApp = true;
9505                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9506                            + " but new version " + pkg.mVersionCode + " better than installed "
9507                            + ps.versionCode + "; hiding system");
9508                } else {
9509                    /*
9510                     * The newly found system app is a newer version that the
9511                     * one previously installed. Simply remove the
9512                     * already-installed application and replace it with our own
9513                     * while keeping the application data.
9514                     */
9515                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9516                            + " reverting from " + ps.codePathString + ": new version "
9517                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9518                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9519                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9520                    synchronized (mInstallLock) {
9521                        args.cleanUpResourcesLI();
9522                    }
9523                }
9524            }
9525        }
9526
9527        // The apk is forward locked (not public) if its code and resources
9528        // are kept in different files. (except for app in either system or
9529        // vendor path).
9530        // TODO grab this value from PackageSettings
9531        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9532            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9533                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9534            }
9535        }
9536
9537        final int userId = ((user == null) ? 0 : user.getIdentifier());
9538        if (ps != null && ps.getInstantApp(userId)) {
9539            scanFlags |= SCAN_AS_INSTANT_APP;
9540        }
9541        if (ps != null && ps.getVirtulalPreload(userId)) {
9542            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9543        }
9544
9545        // Note that we invoke the following method only if we are about to unpack an application
9546        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9547                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9548
9549        /*
9550         * If the system app should be overridden by a previously installed
9551         * data, hide the system app now and let the /data/app scan pick it up
9552         * again.
9553         */
9554        if (shouldHideSystemApp) {
9555            synchronized (mPackages) {
9556                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9557            }
9558        }
9559
9560        return scannedPkg;
9561    }
9562
9563    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9564        // Derive the new package synthetic package name
9565        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9566                + pkg.staticSharedLibVersion);
9567    }
9568
9569    private static String fixProcessName(String defProcessName,
9570            String processName) {
9571        if (processName == null) {
9572            return defProcessName;
9573        }
9574        return processName;
9575    }
9576
9577    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9578            throws PackageManagerException {
9579        if (pkgSetting.signatures.mSignatures != null) {
9580            // Already existing package. Make sure signatures match
9581            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9582                    == PackageManager.SIGNATURE_MATCH;
9583            if (!match) {
9584                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9585                        == PackageManager.SIGNATURE_MATCH;
9586            }
9587            if (!match) {
9588                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9589                        == PackageManager.SIGNATURE_MATCH;
9590            }
9591            if (!match) {
9592                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9593                        + pkg.packageName + " signatures do not match the "
9594                        + "previously installed version; ignoring!");
9595            }
9596        }
9597
9598        // Check for shared user signatures
9599        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9600            // Already existing package. Make sure signatures match
9601            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9602                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9603            if (!match) {
9604                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9605                        == PackageManager.SIGNATURE_MATCH;
9606            }
9607            if (!match) {
9608                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9609                        == PackageManager.SIGNATURE_MATCH;
9610            }
9611            if (!match) {
9612                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9613                        "Package " + pkg.packageName
9614                        + " has no signatures that match those in shared user "
9615                        + pkgSetting.sharedUser.name + "; ignoring!");
9616            }
9617        }
9618    }
9619
9620    /**
9621     * Enforces that only the system UID or root's UID can call a method exposed
9622     * via Binder.
9623     *
9624     * @param message used as message if SecurityException is thrown
9625     * @throws SecurityException if the caller is not system or root
9626     */
9627    private static final void enforceSystemOrRoot(String message) {
9628        final int uid = Binder.getCallingUid();
9629        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9630            throw new SecurityException(message);
9631        }
9632    }
9633
9634    @Override
9635    public void performFstrimIfNeeded() {
9636        enforceSystemOrRoot("Only the system can request fstrim");
9637
9638        // Before everything else, see whether we need to fstrim.
9639        try {
9640            IStorageManager sm = PackageHelper.getStorageManager();
9641            if (sm != null) {
9642                boolean doTrim = false;
9643                final long interval = android.provider.Settings.Global.getLong(
9644                        mContext.getContentResolver(),
9645                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9646                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9647                if (interval > 0) {
9648                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9649                    if (timeSinceLast > interval) {
9650                        doTrim = true;
9651                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9652                                + "; running immediately");
9653                    }
9654                }
9655                if (doTrim) {
9656                    final boolean dexOptDialogShown;
9657                    synchronized (mPackages) {
9658                        dexOptDialogShown = mDexOptDialogShown;
9659                    }
9660                    if (!isFirstBoot() && dexOptDialogShown) {
9661                        try {
9662                            ActivityManager.getService().showBootMessage(
9663                                    mContext.getResources().getString(
9664                                            R.string.android_upgrading_fstrim), true);
9665                        } catch (RemoteException e) {
9666                        }
9667                    }
9668                    sm.runMaintenance();
9669                }
9670            } else {
9671                Slog.e(TAG, "storageManager service unavailable!");
9672            }
9673        } catch (RemoteException e) {
9674            // Can't happen; StorageManagerService is local
9675        }
9676    }
9677
9678    @Override
9679    public void updatePackagesIfNeeded() {
9680        enforceSystemOrRoot("Only the system can request package update");
9681
9682        // We need to re-extract after an OTA.
9683        boolean causeUpgrade = isUpgrade();
9684
9685        // First boot or factory reset.
9686        // Note: we also handle devices that are upgrading to N right now as if it is their
9687        //       first boot, as they do not have profile data.
9688        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9689
9690        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9691        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9692
9693        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9694            return;
9695        }
9696
9697        List<PackageParser.Package> pkgs;
9698        synchronized (mPackages) {
9699            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9700        }
9701
9702        final long startTime = System.nanoTime();
9703        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9704                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9705                    false /* bootComplete */);
9706
9707        final int elapsedTimeSeconds =
9708                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9709
9710        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9711        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9712        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9713        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9714        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9715    }
9716
9717    /*
9718     * Return the prebuilt profile path given a package base code path.
9719     */
9720    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9721        return pkg.baseCodePath + ".prof";
9722    }
9723
9724    /**
9725     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9726     * containing statistics about the invocation. The array consists of three elements,
9727     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9728     * and {@code numberOfPackagesFailed}.
9729     */
9730    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9731            final String compilerFilter, boolean bootComplete) {
9732
9733        int numberOfPackagesVisited = 0;
9734        int numberOfPackagesOptimized = 0;
9735        int numberOfPackagesSkipped = 0;
9736        int numberOfPackagesFailed = 0;
9737        final int numberOfPackagesToDexopt = pkgs.size();
9738
9739        for (PackageParser.Package pkg : pkgs) {
9740            numberOfPackagesVisited++;
9741
9742            boolean useProfileForDexopt = false;
9743
9744            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9745                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9746                // that are already compiled.
9747                File profileFile = new File(getPrebuildProfilePath(pkg));
9748                // Copy profile if it exists.
9749                if (profileFile.exists()) {
9750                    try {
9751                        // We could also do this lazily before calling dexopt in
9752                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9753                        // is that we don't have a good way to say "do this only once".
9754                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9755                                pkg.applicationInfo.uid, pkg.packageName)) {
9756                            Log.e(TAG, "Installer failed to copy system profile!");
9757                        } else {
9758                            // Disabled as this causes speed-profile compilation during first boot
9759                            // even if things are already compiled.
9760                            // useProfileForDexopt = true;
9761                        }
9762                    } catch (Exception e) {
9763                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9764                                e);
9765                    }
9766                } else {
9767                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9768                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9769                    // minimize the number off apps being speed-profile compiled during first boot.
9770                    // The other paths will not change the filter.
9771                    if (disabledPs != null && disabledPs.pkg.isStub) {
9772                        // The package is the stub one, remove the stub suffix to get the normal
9773                        // package and APK names.
9774                        String systemProfilePath =
9775                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9776                        profileFile = new File(systemProfilePath);
9777                        // If we have a profile for a compressed APK, copy it to the reference
9778                        // location.
9779                        // Note that copying the profile here will cause it to override the
9780                        // reference profile every OTA even though the existing reference profile
9781                        // may have more data. We can't copy during decompression since the
9782                        // directories are not set up at that point.
9783                        if (profileFile.exists()) {
9784                            try {
9785                                // We could also do this lazily before calling dexopt in
9786                                // PackageDexOptimizer to prevent this happening on first boot. The
9787                                // issue is that we don't have a good way to say "do this only
9788                                // once".
9789                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9790                                        pkg.applicationInfo.uid, pkg.packageName)) {
9791                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9792                                } else {
9793                                    useProfileForDexopt = true;
9794                                }
9795                            } catch (Exception e) {
9796                                Log.e(TAG, "Failed to copy profile " +
9797                                        profileFile.getAbsolutePath() + " ", e);
9798                            }
9799                        }
9800                    }
9801                }
9802            }
9803
9804            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9805                if (DEBUG_DEXOPT) {
9806                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9807                }
9808                numberOfPackagesSkipped++;
9809                continue;
9810            }
9811
9812            if (DEBUG_DEXOPT) {
9813                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9814                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9815            }
9816
9817            if (showDialog) {
9818                try {
9819                    ActivityManager.getService().showBootMessage(
9820                            mContext.getResources().getString(R.string.android_upgrading_apk,
9821                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9822                } catch (RemoteException e) {
9823                }
9824                synchronized (mPackages) {
9825                    mDexOptDialogShown = true;
9826                }
9827            }
9828
9829            String pkgCompilerFilter = compilerFilter;
9830            if (useProfileForDexopt) {
9831                // Use background dexopt mode to try and use the profile. Note that this does not
9832                // guarantee usage of the profile.
9833                pkgCompilerFilter =
9834                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9835                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
9836            }
9837
9838            // checkProfiles is false to avoid merging profiles during boot which
9839            // might interfere with background compilation (b/28612421).
9840            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9841            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9842            // trade-off worth doing to save boot time work.
9843            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9844            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9845                    pkg.packageName,
9846                    pkgCompilerFilter,
9847                    dexoptFlags));
9848
9849            switch (primaryDexOptStaus) {
9850                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9851                    numberOfPackagesOptimized++;
9852                    break;
9853                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9854                    numberOfPackagesSkipped++;
9855                    break;
9856                case PackageDexOptimizer.DEX_OPT_FAILED:
9857                    numberOfPackagesFailed++;
9858                    break;
9859                default:
9860                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9861                    break;
9862            }
9863        }
9864
9865        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9866                numberOfPackagesFailed };
9867    }
9868
9869    @Override
9870    public void notifyPackageUse(String packageName, int reason) {
9871        synchronized (mPackages) {
9872            final int callingUid = Binder.getCallingUid();
9873            final int callingUserId = UserHandle.getUserId(callingUid);
9874            if (getInstantAppPackageName(callingUid) != null) {
9875                if (!isCallerSameApp(packageName, callingUid)) {
9876                    return;
9877                }
9878            } else {
9879                if (isInstantApp(packageName, callingUserId)) {
9880                    return;
9881                }
9882            }
9883            notifyPackageUseLocked(packageName, reason);
9884        }
9885    }
9886
9887    private void notifyPackageUseLocked(String packageName, int reason) {
9888        final PackageParser.Package p = mPackages.get(packageName);
9889        if (p == null) {
9890            return;
9891        }
9892        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9893    }
9894
9895    @Override
9896    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9897            List<String> classPaths, String loaderIsa) {
9898        int userId = UserHandle.getCallingUserId();
9899        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9900        if (ai == null) {
9901            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9902                + loadingPackageName + ", user=" + userId);
9903            return;
9904        }
9905        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9906    }
9907
9908    @Override
9909    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9910            IDexModuleRegisterCallback callback) {
9911        int userId = UserHandle.getCallingUserId();
9912        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9913        DexManager.RegisterDexModuleResult result;
9914        if (ai == null) {
9915            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9916                     " calling user. package=" + packageName + ", user=" + userId);
9917            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9918        } else {
9919            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9920        }
9921
9922        if (callback != null) {
9923            mHandler.post(() -> {
9924                try {
9925                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9926                } catch (RemoteException e) {
9927                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9928                }
9929            });
9930        }
9931    }
9932
9933    /**
9934     * Ask the package manager to perform a dex-opt with the given compiler filter.
9935     *
9936     * Note: exposed only for the shell command to allow moving packages explicitly to a
9937     *       definite state.
9938     */
9939    @Override
9940    public boolean performDexOptMode(String packageName,
9941            boolean checkProfiles, String targetCompilerFilter, boolean force,
9942            boolean bootComplete, String splitName) {
9943        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9944                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9945                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9946        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9947                splitName, flags));
9948    }
9949
9950    /**
9951     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9952     * secondary dex files belonging to the given package.
9953     *
9954     * Note: exposed only for the shell command to allow moving packages explicitly to a
9955     *       definite state.
9956     */
9957    @Override
9958    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9959            boolean force) {
9960        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9961                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9962                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9963                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9964        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9965    }
9966
9967    /*package*/ boolean performDexOpt(DexoptOptions options) {
9968        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9969            return false;
9970        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9971            return false;
9972        }
9973
9974        if (options.isDexoptOnlySecondaryDex()) {
9975            return mDexManager.dexoptSecondaryDex(options);
9976        } else {
9977            int dexoptStatus = performDexOptWithStatus(options);
9978            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9979        }
9980    }
9981
9982    /**
9983     * Perform dexopt on the given package and return one of following result:
9984     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9985     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9986     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9987     */
9988    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9989        return performDexOptTraced(options);
9990    }
9991
9992    private int performDexOptTraced(DexoptOptions options) {
9993        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9994        try {
9995            return performDexOptInternal(options);
9996        } finally {
9997            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9998        }
9999    }
10000
10001    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
10002    // if the package can now be considered up to date for the given filter.
10003    private int performDexOptInternal(DexoptOptions options) {
10004        PackageParser.Package p;
10005        synchronized (mPackages) {
10006            p = mPackages.get(options.getPackageName());
10007            if (p == null) {
10008                // Package could not be found. Report failure.
10009                return PackageDexOptimizer.DEX_OPT_FAILED;
10010            }
10011            mPackageUsage.maybeWriteAsync(mPackages);
10012            mCompilerStats.maybeWriteAsync();
10013        }
10014        long callingId = Binder.clearCallingIdentity();
10015        try {
10016            synchronized (mInstallLock) {
10017                return performDexOptInternalWithDependenciesLI(p, options);
10018            }
10019        } finally {
10020            Binder.restoreCallingIdentity(callingId);
10021        }
10022    }
10023
10024    public ArraySet<String> getOptimizablePackages() {
10025        ArraySet<String> pkgs = new ArraySet<String>();
10026        synchronized (mPackages) {
10027            for (PackageParser.Package p : mPackages.values()) {
10028                if (PackageDexOptimizer.canOptimizePackage(p)) {
10029                    pkgs.add(p.packageName);
10030                }
10031            }
10032        }
10033        return pkgs;
10034    }
10035
10036    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
10037            DexoptOptions options) {
10038        // Select the dex optimizer based on the force parameter.
10039        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
10040        //       allocate an object here.
10041        PackageDexOptimizer pdo = options.isForce()
10042                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
10043                : mPackageDexOptimizer;
10044
10045        // Dexopt all dependencies first. Note: we ignore the return value and march on
10046        // on errors.
10047        // Note that we are going to call performDexOpt on those libraries as many times as
10048        // they are referenced in packages. When we do a batch of performDexOpt (for example
10049        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
10050        // and the first package that uses the library will dexopt it. The
10051        // others will see that the compiled code for the library is up to date.
10052        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
10053        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
10054        if (!deps.isEmpty()) {
10055            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
10056                    options.getCompilerFilter(), options.getSplitName(),
10057                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
10058            for (PackageParser.Package depPackage : deps) {
10059                // TODO: Analyze and investigate if we (should) profile libraries.
10060                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
10061                        getOrCreateCompilerPackageStats(depPackage),
10062                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
10063            }
10064        }
10065        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
10066                getOrCreateCompilerPackageStats(p),
10067                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
10068    }
10069
10070    /**
10071     * Reconcile the information we have about the secondary dex files belonging to
10072     * {@code packagName} and the actual dex files. For all dex files that were
10073     * deleted, update the internal records and delete the generated oat files.
10074     */
10075    @Override
10076    public void reconcileSecondaryDexFiles(String packageName) {
10077        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10078            return;
10079        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
10080            return;
10081        }
10082        mDexManager.reconcileSecondaryDexFiles(packageName);
10083    }
10084
10085    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
10086    // a reference there.
10087    /*package*/ DexManager getDexManager() {
10088        return mDexManager;
10089    }
10090
10091    /**
10092     * Execute the background dexopt job immediately.
10093     */
10094    @Override
10095    public boolean runBackgroundDexoptJob() {
10096        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10097            return false;
10098        }
10099        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
10100    }
10101
10102    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
10103        if (p.usesLibraries != null || p.usesOptionalLibraries != null
10104                || p.usesStaticLibraries != null) {
10105            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
10106            Set<String> collectedNames = new HashSet<>();
10107            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
10108
10109            retValue.remove(p);
10110
10111            return retValue;
10112        } else {
10113            return Collections.emptyList();
10114        }
10115    }
10116
10117    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
10118            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10119        if (!collectedNames.contains(p.packageName)) {
10120            collectedNames.add(p.packageName);
10121            collected.add(p);
10122
10123            if (p.usesLibraries != null) {
10124                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10125                        null, collected, collectedNames);
10126            }
10127            if (p.usesOptionalLibraries != null) {
10128                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10129                        null, collected, collectedNames);
10130            }
10131            if (p.usesStaticLibraries != null) {
10132                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10133                        p.usesStaticLibrariesVersions, collected, collectedNames);
10134            }
10135        }
10136    }
10137
10138    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10139            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10140        final int libNameCount = libs.size();
10141        for (int i = 0; i < libNameCount; i++) {
10142            String libName = libs.get(i);
10143            int version = (versions != null && versions.length == libNameCount)
10144                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10145            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10146            if (libPkg != null) {
10147                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10148            }
10149        }
10150    }
10151
10152    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10153        synchronized (mPackages) {
10154            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10155            if (libEntry != null) {
10156                return mPackages.get(libEntry.apk);
10157            }
10158            return null;
10159        }
10160    }
10161
10162    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10163        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10164        if (versionedLib == null) {
10165            return null;
10166        }
10167        return versionedLib.get(version);
10168    }
10169
10170    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10171        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10172                pkg.staticSharedLibName);
10173        if (versionedLib == null) {
10174            return null;
10175        }
10176        int previousLibVersion = -1;
10177        final int versionCount = versionedLib.size();
10178        for (int i = 0; i < versionCount; i++) {
10179            final int libVersion = versionedLib.keyAt(i);
10180            if (libVersion < pkg.staticSharedLibVersion) {
10181                previousLibVersion = Math.max(previousLibVersion, libVersion);
10182            }
10183        }
10184        if (previousLibVersion >= 0) {
10185            return versionedLib.get(previousLibVersion);
10186        }
10187        return null;
10188    }
10189
10190    public void shutdown() {
10191        mPackageUsage.writeNow(mPackages);
10192        mCompilerStats.writeNow();
10193        mDexManager.writePackageDexUsageNow();
10194    }
10195
10196    @Override
10197    public void dumpProfiles(String packageName) {
10198        PackageParser.Package pkg;
10199        synchronized (mPackages) {
10200            pkg = mPackages.get(packageName);
10201            if (pkg == null) {
10202                throw new IllegalArgumentException("Unknown package: " + packageName);
10203            }
10204        }
10205        /* Only the shell, root, or the app user should be able to dump profiles. */
10206        int callingUid = Binder.getCallingUid();
10207        if (callingUid != Process.SHELL_UID &&
10208            callingUid != Process.ROOT_UID &&
10209            callingUid != pkg.applicationInfo.uid) {
10210            throw new SecurityException("dumpProfiles");
10211        }
10212
10213        synchronized (mInstallLock) {
10214            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10215            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10216            try {
10217                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10218                String codePaths = TextUtils.join(";", allCodePaths);
10219                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10220            } catch (InstallerException e) {
10221                Slog.w(TAG, "Failed to dump profiles", e);
10222            }
10223            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10224        }
10225    }
10226
10227    @Override
10228    public void forceDexOpt(String packageName) {
10229        enforceSystemOrRoot("forceDexOpt");
10230
10231        PackageParser.Package pkg;
10232        synchronized (mPackages) {
10233            pkg = mPackages.get(packageName);
10234            if (pkg == null) {
10235                throw new IllegalArgumentException("Unknown package: " + packageName);
10236            }
10237        }
10238
10239        synchronized (mInstallLock) {
10240            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10241
10242            // Whoever is calling forceDexOpt wants a compiled package.
10243            // Don't use profiles since that may cause compilation to be skipped.
10244            final int res = performDexOptInternalWithDependenciesLI(
10245                    pkg,
10246                    new DexoptOptions(packageName,
10247                            getDefaultCompilerFilter(),
10248                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10249
10250            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10251            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10252                throw new IllegalStateException("Failed to dexopt: " + res);
10253            }
10254        }
10255    }
10256
10257    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10258        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10259            Slog.w(TAG, "Unable to update from " + oldPkg.name
10260                    + " to " + newPkg.packageName
10261                    + ": old package not in system partition");
10262            return false;
10263        } else if (mPackages.get(oldPkg.name) != null) {
10264            Slog.w(TAG, "Unable to update from " + oldPkg.name
10265                    + " to " + newPkg.packageName
10266                    + ": old package still exists");
10267            return false;
10268        }
10269        return true;
10270    }
10271
10272    void removeCodePathLI(File codePath) {
10273        if (codePath.isDirectory()) {
10274            try {
10275                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10276            } catch (InstallerException e) {
10277                Slog.w(TAG, "Failed to remove code path", e);
10278            }
10279        } else {
10280            codePath.delete();
10281        }
10282    }
10283
10284    private int[] resolveUserIds(int userId) {
10285        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10286    }
10287
10288    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10289        if (pkg == null) {
10290            Slog.wtf(TAG, "Package was null!", new Throwable());
10291            return;
10292        }
10293        clearAppDataLeafLIF(pkg, userId, flags);
10294        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10295        for (int i = 0; i < childCount; i++) {
10296            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10297        }
10298    }
10299
10300    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10301        final PackageSetting ps;
10302        synchronized (mPackages) {
10303            ps = mSettings.mPackages.get(pkg.packageName);
10304        }
10305        for (int realUserId : resolveUserIds(userId)) {
10306            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10307            try {
10308                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10309                        ceDataInode);
10310            } catch (InstallerException e) {
10311                Slog.w(TAG, String.valueOf(e));
10312            }
10313        }
10314    }
10315
10316    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10317        if (pkg == null) {
10318            Slog.wtf(TAG, "Package was null!", new Throwable());
10319            return;
10320        }
10321        destroyAppDataLeafLIF(pkg, userId, flags);
10322        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10323        for (int i = 0; i < childCount; i++) {
10324            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10325        }
10326    }
10327
10328    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10329        final PackageSetting ps;
10330        synchronized (mPackages) {
10331            ps = mSettings.mPackages.get(pkg.packageName);
10332        }
10333        for (int realUserId : resolveUserIds(userId)) {
10334            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10335            try {
10336                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10337                        ceDataInode);
10338            } catch (InstallerException e) {
10339                Slog.w(TAG, String.valueOf(e));
10340            }
10341            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10342        }
10343    }
10344
10345    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10346        if (pkg == null) {
10347            Slog.wtf(TAG, "Package was null!", new Throwable());
10348            return;
10349        }
10350        destroyAppProfilesLeafLIF(pkg);
10351        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10352        for (int i = 0; i < childCount; i++) {
10353            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10354        }
10355    }
10356
10357    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10358        try {
10359            mInstaller.destroyAppProfiles(pkg.packageName);
10360        } catch (InstallerException e) {
10361            Slog.w(TAG, String.valueOf(e));
10362        }
10363    }
10364
10365    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10366        if (pkg == null) {
10367            Slog.wtf(TAG, "Package was null!", new Throwable());
10368            return;
10369        }
10370        clearAppProfilesLeafLIF(pkg);
10371        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10372        for (int i = 0; i < childCount; i++) {
10373            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10374        }
10375    }
10376
10377    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10378        try {
10379            mInstaller.clearAppProfiles(pkg.packageName);
10380        } catch (InstallerException e) {
10381            Slog.w(TAG, String.valueOf(e));
10382        }
10383    }
10384
10385    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10386            long lastUpdateTime) {
10387        // Set parent install/update time
10388        PackageSetting ps = (PackageSetting) pkg.mExtras;
10389        if (ps != null) {
10390            ps.firstInstallTime = firstInstallTime;
10391            ps.lastUpdateTime = lastUpdateTime;
10392        }
10393        // Set children install/update time
10394        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10395        for (int i = 0; i < childCount; i++) {
10396            PackageParser.Package childPkg = pkg.childPackages.get(i);
10397            ps = (PackageSetting) childPkg.mExtras;
10398            if (ps != null) {
10399                ps.firstInstallTime = firstInstallTime;
10400                ps.lastUpdateTime = lastUpdateTime;
10401            }
10402        }
10403    }
10404
10405    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
10406            SharedLibraryEntry file,
10407            PackageParser.Package changingLib) {
10408        if (file.path != null) {
10409            usesLibraryFiles.add(file.path);
10410            return;
10411        }
10412        PackageParser.Package p = mPackages.get(file.apk);
10413        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10414            // If we are doing this while in the middle of updating a library apk,
10415            // then we need to make sure to use that new apk for determining the
10416            // dependencies here.  (We haven't yet finished committing the new apk
10417            // to the package manager state.)
10418            if (p == null || p.packageName.equals(changingLib.packageName)) {
10419                p = changingLib;
10420            }
10421        }
10422        if (p != null) {
10423            usesLibraryFiles.addAll(p.getAllCodePaths());
10424            if (p.usesLibraryFiles != null) {
10425                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10426            }
10427        }
10428    }
10429
10430    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10431            PackageParser.Package changingLib) throws PackageManagerException {
10432        if (pkg == null) {
10433            return;
10434        }
10435        // The collection used here must maintain the order of addition (so
10436        // that libraries are searched in the correct order) and must have no
10437        // duplicates.
10438        Set<String> usesLibraryFiles = null;
10439        if (pkg.usesLibraries != null) {
10440            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10441                    null, null, pkg.packageName, changingLib, true,
10442                    pkg.applicationInfo.targetSdkVersion, null);
10443        }
10444        if (pkg.usesStaticLibraries != null) {
10445            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10446                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10447                    pkg.packageName, changingLib, true,
10448                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10449        }
10450        if (pkg.usesOptionalLibraries != null) {
10451            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10452                    null, null, pkg.packageName, changingLib, false,
10453                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10454        }
10455        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10456            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10457        } else {
10458            pkg.usesLibraryFiles = null;
10459        }
10460    }
10461
10462    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10463            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
10464            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10465            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
10466            throws PackageManagerException {
10467        final int libCount = requestedLibraries.size();
10468        for (int i = 0; i < libCount; i++) {
10469            final String libName = requestedLibraries.get(i);
10470            final int libVersion = requiredVersions != null ? requiredVersions[i]
10471                    : SharedLibraryInfo.VERSION_UNDEFINED;
10472            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10473            if (libEntry == null) {
10474                if (required) {
10475                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10476                            "Package " + packageName + " requires unavailable shared library "
10477                                    + libName + "; failing!");
10478                } else if (DEBUG_SHARED_LIBRARIES) {
10479                    Slog.i(TAG, "Package " + packageName
10480                            + " desires unavailable shared library "
10481                            + libName + "; ignoring!");
10482                }
10483            } else {
10484                if (requiredVersions != null && requiredCertDigests != null) {
10485                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10486                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10487                            "Package " + packageName + " requires unavailable static shared"
10488                                    + " library " + libName + " version "
10489                                    + libEntry.info.getVersion() + "; failing!");
10490                    }
10491
10492                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10493                    if (libPkg == null) {
10494                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10495                                "Package " + packageName + " requires unavailable static shared"
10496                                        + " library; failing!");
10497                    }
10498
10499                    final String[] expectedCertDigests = requiredCertDigests[i];
10500                    // For apps targeting O MR1 we require explicit enumeration of all certs.
10501                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
10502                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
10503                            : PackageUtils.computeSignaturesSha256Digests(
10504                                    new Signature[]{libPkg.mSignatures[0]});
10505
10506                    // Take a shortcut if sizes don't match. Note that if an app doesn't
10507                    // target O we don't parse the "additional-certificate" tags similarly
10508                    // how we only consider all certs only for apps targeting O (see above).
10509                    // Therefore, the size check is safe to make.
10510                    if (expectedCertDigests.length != libCertDigests.length) {
10511                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10512                                "Package " + packageName + " requires differently signed" +
10513                                        " static sDexLoadReporter.java:45.19hared library; failing!");
10514                    }
10515
10516                    // Use a predictable order as signature order may vary
10517                    Arrays.sort(libCertDigests);
10518                    Arrays.sort(expectedCertDigests);
10519
10520                    final int certCount = libCertDigests.length;
10521                    for (int j = 0; j < certCount; j++) {
10522                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
10523                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10524                                    "Package " + packageName + " requires differently signed" +
10525                                            " static shared library; failing!");
10526                        }
10527                    }
10528                }
10529
10530                if (outUsedLibraries == null) {
10531                    // Use LinkedHashSet to preserve the order of files added to
10532                    // usesLibraryFiles while eliminating duplicates.
10533                    outUsedLibraries = new LinkedHashSet<>();
10534                }
10535                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10536            }
10537        }
10538        return outUsedLibraries;
10539    }
10540
10541    private static boolean hasString(List<String> list, List<String> which) {
10542        if (list == null) {
10543            return false;
10544        }
10545        for (int i=list.size()-1; i>=0; i--) {
10546            for (int j=which.size()-1; j>=0; j--) {
10547                if (which.get(j).equals(list.get(i))) {
10548                    return true;
10549                }
10550            }
10551        }
10552        return false;
10553    }
10554
10555    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10556            PackageParser.Package changingPkg) {
10557        ArrayList<PackageParser.Package> res = null;
10558        for (PackageParser.Package pkg : mPackages.values()) {
10559            if (changingPkg != null
10560                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10561                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10562                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10563                            changingPkg.staticSharedLibName)) {
10564                return null;
10565            }
10566            if (res == null) {
10567                res = new ArrayList<>();
10568            }
10569            res.add(pkg);
10570            try {
10571                updateSharedLibrariesLPr(pkg, changingPkg);
10572            } catch (PackageManagerException e) {
10573                // If a system app update or an app and a required lib missing we
10574                // delete the package and for updated system apps keep the data as
10575                // it is better for the user to reinstall than to be in an limbo
10576                // state. Also libs disappearing under an app should never happen
10577                // - just in case.
10578                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10579                    final int flags = pkg.isUpdatedSystemApp()
10580                            ? PackageManager.DELETE_KEEP_DATA : 0;
10581                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10582                            flags , null, true, null);
10583                }
10584                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10585            }
10586        }
10587        return res;
10588    }
10589
10590    /**
10591     * Derive the value of the {@code cpuAbiOverride} based on the provided
10592     * value and an optional stored value from the package settings.
10593     */
10594    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10595        String cpuAbiOverride = null;
10596
10597        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10598            cpuAbiOverride = null;
10599        } else if (abiOverride != null) {
10600            cpuAbiOverride = abiOverride;
10601        } else if (settings != null) {
10602            cpuAbiOverride = settings.cpuAbiOverrideString;
10603        }
10604
10605        return cpuAbiOverride;
10606    }
10607
10608    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10609            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10610                    throws PackageManagerException {
10611        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10612        // If the package has children and this is the first dive in the function
10613        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10614        // whether all packages (parent and children) would be successfully scanned
10615        // before the actual scan since scanning mutates internal state and we want
10616        // to atomically install the package and its children.
10617        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10618            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10619                scanFlags |= SCAN_CHECK_ONLY;
10620            }
10621        } else {
10622            scanFlags &= ~SCAN_CHECK_ONLY;
10623        }
10624
10625        final PackageParser.Package scannedPkg;
10626        try {
10627            // Scan the parent
10628            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10629            // Scan the children
10630            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10631            for (int i = 0; i < childCount; i++) {
10632                PackageParser.Package childPkg = pkg.childPackages.get(i);
10633                scanPackageLI(childPkg, policyFlags,
10634                        scanFlags, currentTime, user);
10635            }
10636        } finally {
10637            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10638        }
10639
10640        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10641            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10642        }
10643
10644        return scannedPkg;
10645    }
10646
10647    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10648            int scanFlags, long currentTime, @Nullable UserHandle user)
10649                    throws PackageManagerException {
10650        boolean success = false;
10651        try {
10652            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10653                    currentTime, user);
10654            success = true;
10655            return res;
10656        } finally {
10657            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10658                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10659                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10660                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10661                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10662            }
10663        }
10664    }
10665
10666    /**
10667     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10668     */
10669    private static boolean apkHasCode(String fileName) {
10670        StrictJarFile jarFile = null;
10671        try {
10672            jarFile = new StrictJarFile(fileName,
10673                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10674            return jarFile.findEntry("classes.dex") != null;
10675        } catch (IOException ignore) {
10676        } finally {
10677            try {
10678                if (jarFile != null) {
10679                    jarFile.close();
10680                }
10681            } catch (IOException ignore) {}
10682        }
10683        return false;
10684    }
10685
10686    /**
10687     * Enforces code policy for the package. This ensures that if an APK has
10688     * declared hasCode="true" in its manifest that the APK actually contains
10689     * code.
10690     *
10691     * @throws PackageManagerException If bytecode could not be found when it should exist
10692     */
10693    private static void assertCodePolicy(PackageParser.Package pkg)
10694            throws PackageManagerException {
10695        final boolean shouldHaveCode =
10696                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10697        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10698            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10699                    "Package " + pkg.baseCodePath + " code is missing");
10700        }
10701
10702        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10703            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10704                final boolean splitShouldHaveCode =
10705                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10706                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10707                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10708                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10709                }
10710            }
10711        }
10712    }
10713
10714    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10715            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10716                    throws PackageManagerException {
10717        if (DEBUG_PACKAGE_SCANNING) {
10718            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10719                Log.d(TAG, "Scanning package " + pkg.packageName);
10720        }
10721
10722        applyPolicy(pkg, policyFlags);
10723
10724        assertPackageIsValid(pkg, policyFlags, scanFlags);
10725
10726        if (Build.IS_DEBUGGABLE &&
10727                pkg.isPrivilegedApp() &&
10728                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10729            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10730        }
10731
10732        // Initialize package source and resource directories
10733        final File scanFile = new File(pkg.codePath);
10734        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10735        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10736
10737        SharedUserSetting suid = null;
10738        PackageSetting pkgSetting = null;
10739
10740        // Getting the package setting may have a side-effect, so if we
10741        // are only checking if scan would succeed, stash a copy of the
10742        // old setting to restore at the end.
10743        PackageSetting nonMutatedPs = null;
10744
10745        // We keep references to the derived CPU Abis from settings in oder to reuse
10746        // them in the case where we're not upgrading or booting for the first time.
10747        String primaryCpuAbiFromSettings = null;
10748        String secondaryCpuAbiFromSettings = null;
10749        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10750
10751        // writer
10752        synchronized (mPackages) {
10753            if (pkg.mSharedUserId != null) {
10754                // SIDE EFFECTS; may potentially allocate a new shared user
10755                suid = mSettings.getSharedUserLPw(
10756                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10757                if (DEBUG_PACKAGE_SCANNING) {
10758                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10759                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10760                                + "): packages=" + suid.packages);
10761                }
10762            }
10763
10764            // Check if we are renaming from an original package name.
10765            PackageSetting origPackage = null;
10766            String realName = null;
10767            if (pkg.mOriginalPackages != null) {
10768                // This package may need to be renamed to a previously
10769                // installed name.  Let's check on that...
10770                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10771                if (pkg.mOriginalPackages.contains(renamed)) {
10772                    // This package had originally been installed as the
10773                    // original name, and we have already taken care of
10774                    // transitioning to the new one.  Just update the new
10775                    // one to continue using the old name.
10776                    realName = pkg.mRealPackage;
10777                    if (!pkg.packageName.equals(renamed)) {
10778                        // Callers into this function may have already taken
10779                        // care of renaming the package; only do it here if
10780                        // it is not already done.
10781                        pkg.setPackageName(renamed);
10782                    }
10783                } else {
10784                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10785                        if ((origPackage = mSettings.getPackageLPr(
10786                                pkg.mOriginalPackages.get(i))) != null) {
10787                            // We do have the package already installed under its
10788                            // original name...  should we use it?
10789                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10790                                // New package is not compatible with original.
10791                                origPackage = null;
10792                                continue;
10793                            } else if (origPackage.sharedUser != null) {
10794                                // Make sure uid is compatible between packages.
10795                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10796                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10797                                            + " to " + pkg.packageName + ": old uid "
10798                                            + origPackage.sharedUser.name
10799                                            + " differs from " + pkg.mSharedUserId);
10800                                    origPackage = null;
10801                                    continue;
10802                                }
10803                                // TODO: Add case when shared user id is added [b/28144775]
10804                            } else {
10805                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10806                                        + pkg.packageName + " to old name " + origPackage.name);
10807                            }
10808                            break;
10809                        }
10810                    }
10811                }
10812            }
10813
10814            if (mTransferedPackages.contains(pkg.packageName)) {
10815                Slog.w(TAG, "Package " + pkg.packageName
10816                        + " was transferred to another, but its .apk remains");
10817            }
10818
10819            // See comments in nonMutatedPs declaration
10820            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10821                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10822                if (foundPs != null) {
10823                    nonMutatedPs = new PackageSetting(foundPs);
10824                }
10825            }
10826
10827            if (!needToDeriveAbi) {
10828                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10829                if (foundPs != null) {
10830                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10831                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10832                } else {
10833                    // when re-adding a system package failed after uninstalling updates.
10834                    needToDeriveAbi = true;
10835                }
10836            }
10837
10838            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10839            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10840                PackageManagerService.reportSettingsProblem(Log.WARN,
10841                        "Package " + pkg.packageName + " shared user changed from "
10842                                + (pkgSetting.sharedUser != null
10843                                        ? pkgSetting.sharedUser.name : "<nothing>")
10844                                + " to "
10845                                + (suid != null ? suid.name : "<nothing>")
10846                                + "; replacing with new");
10847                pkgSetting = null;
10848            }
10849            final PackageSetting oldPkgSetting =
10850                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10851            final PackageSetting disabledPkgSetting =
10852                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10853
10854            String[] usesStaticLibraries = null;
10855            if (pkg.usesStaticLibraries != null) {
10856                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10857                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10858            }
10859
10860            if (pkgSetting == null) {
10861                final String parentPackageName = (pkg.parentPackage != null)
10862                        ? pkg.parentPackage.packageName : null;
10863                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10864                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10865                // REMOVE SharedUserSetting from method; update in a separate call
10866                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10867                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10868                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10869                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10870                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10871                        true /*allowInstall*/, instantApp, virtualPreload,
10872                        parentPackageName, pkg.getChildPackageNames(),
10873                        UserManagerService.getInstance(), usesStaticLibraries,
10874                        pkg.usesStaticLibrariesVersions);
10875                // SIDE EFFECTS; updates system state; move elsewhere
10876                if (origPackage != null) {
10877                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10878                }
10879                mSettings.addUserToSettingLPw(pkgSetting);
10880            } else {
10881                // REMOVE SharedUserSetting from method; update in a separate call.
10882                //
10883                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10884                // secondaryCpuAbi are not known at this point so we always update them
10885                // to null here, only to reset them at a later point.
10886                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10887                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10888                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10889                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10890                        UserManagerService.getInstance(), usesStaticLibraries,
10891                        pkg.usesStaticLibrariesVersions);
10892            }
10893            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10894            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10895
10896            // SIDE EFFECTS; modifies system state; move elsewhere
10897            if (pkgSetting.origPackage != null) {
10898                // If we are first transitioning from an original package,
10899                // fix up the new package's name now.  We need to do this after
10900                // looking up the package under its new name, so getPackageLP
10901                // can take care of fiddling things correctly.
10902                pkg.setPackageName(origPackage.name);
10903
10904                // File a report about this.
10905                String msg = "New package " + pkgSetting.realName
10906                        + " renamed to replace old package " + pkgSetting.name;
10907                reportSettingsProblem(Log.WARN, msg);
10908
10909                // Make a note of it.
10910                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10911                    mTransferedPackages.add(origPackage.name);
10912                }
10913
10914                // No longer need to retain this.
10915                pkgSetting.origPackage = null;
10916            }
10917
10918            // SIDE EFFECTS; modifies system state; move elsewhere
10919            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10920                // Make a note of it.
10921                mTransferedPackages.add(pkg.packageName);
10922            }
10923
10924            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10925                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10926            }
10927
10928            if ((scanFlags & SCAN_BOOTING) == 0
10929                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10930                // Check all shared libraries and map to their actual file path.
10931                // We only do this here for apps not on a system dir, because those
10932                // are the only ones that can fail an install due to this.  We
10933                // will take care of the system apps by updating all of their
10934                // library paths after the scan is done. Also during the initial
10935                // scan don't update any libs as we do this wholesale after all
10936                // apps are scanned to avoid dependency based scanning.
10937                updateSharedLibrariesLPr(pkg, null);
10938            }
10939
10940            if (mFoundPolicyFile) {
10941                SELinuxMMAC.assignSeInfoValue(pkg);
10942            }
10943            pkg.applicationInfo.uid = pkgSetting.appId;
10944            pkg.mExtras = pkgSetting;
10945
10946
10947            // Static shared libs have same package with different versions where
10948            // we internally use a synthetic package name to allow multiple versions
10949            // of the same package, therefore we need to compare signatures against
10950            // the package setting for the latest library version.
10951            PackageSetting signatureCheckPs = pkgSetting;
10952            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10953                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10954                if (libraryEntry != null) {
10955                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10956                }
10957            }
10958
10959            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10960                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10961                    // We just determined the app is signed correctly, so bring
10962                    // over the latest parsed certs.
10963                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10964                } else {
10965                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10966                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10967                                "Package " + pkg.packageName + " upgrade keys do not match the "
10968                                + "previously installed version");
10969                    } else {
10970                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10971                        String msg = "System package " + pkg.packageName
10972                                + " signature changed; retaining data.";
10973                        reportSettingsProblem(Log.WARN, msg);
10974                    }
10975                }
10976            } else {
10977                try {
10978                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10979                    verifySignaturesLP(signatureCheckPs, pkg);
10980                    // We just determined the app is signed correctly, so bring
10981                    // over the latest parsed certs.
10982                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10983                } catch (PackageManagerException e) {
10984                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10985                        throw e;
10986                    }
10987                    // The signature has changed, but this package is in the system
10988                    // image...  let's recover!
10989                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10990                    // However...  if this package is part of a shared user, but it
10991                    // doesn't match the signature of the shared user, let's fail.
10992                    // What this means is that you can't change the signatures
10993                    // associated with an overall shared user, which doesn't seem all
10994                    // that unreasonable.
10995                    if (signatureCheckPs.sharedUser != null) {
10996                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10997                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10998                            throw new PackageManagerException(
10999                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
11000                                    "Signature mismatch for shared user: "
11001                                            + pkgSetting.sharedUser);
11002                        }
11003                    }
11004                    // File a report about this.
11005                    String msg = "System package " + pkg.packageName
11006                            + " signature changed; retaining data.";
11007                    reportSettingsProblem(Log.WARN, msg);
11008                }
11009            }
11010
11011            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
11012                // This package wants to adopt ownership of permissions from
11013                // another package.
11014                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
11015                    final String origName = pkg.mAdoptPermissions.get(i);
11016                    final PackageSetting orig = mSettings.getPackageLPr(origName);
11017                    if (orig != null) {
11018                        if (verifyPackageUpdateLPr(orig, pkg)) {
11019                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
11020                                    + pkg.packageName);
11021                            // SIDE EFFECTS; updates permissions system state; move elsewhere
11022                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
11023                        }
11024                    }
11025                }
11026            }
11027        }
11028
11029        pkg.applicationInfo.processName = fixProcessName(
11030                pkg.applicationInfo.packageName,
11031                pkg.applicationInfo.processName);
11032
11033        if (pkg != mPlatformPackage) {
11034            // Get all of our default paths setup
11035            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
11036        }
11037
11038        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
11039
11040        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
11041            if (needToDeriveAbi) {
11042                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
11043                final boolean extractNativeLibs = !pkg.isLibrary();
11044                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
11045                        mAppLib32InstallDir);
11046                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11047
11048                // Some system apps still use directory structure for native libraries
11049                // in which case we might end up not detecting abi solely based on apk
11050                // structure. Try to detect abi based on directory structure.
11051                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
11052                        pkg.applicationInfo.primaryCpuAbi == null) {
11053                    setBundledAppAbisAndRoots(pkg, pkgSetting);
11054                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11055                }
11056            } else {
11057                // This is not a first boot or an upgrade, don't bother deriving the
11058                // ABI during the scan. Instead, trust the value that was stored in the
11059                // package setting.
11060                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
11061                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
11062
11063                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11064
11065                if (DEBUG_ABI_SELECTION) {
11066                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
11067                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
11068                        pkg.applicationInfo.secondaryCpuAbi);
11069                }
11070            }
11071        } else {
11072            if ((scanFlags & SCAN_MOVE) != 0) {
11073                // We haven't run dex-opt for this move (since we've moved the compiled output too)
11074                // but we already have this packages package info in the PackageSetting. We just
11075                // use that and derive the native library path based on the new codepath.
11076                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
11077                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
11078            }
11079
11080            // Set native library paths again. For moves, the path will be updated based on the
11081            // ABIs we've determined above. For non-moves, the path will be updated based on the
11082            // ABIs we determined during compilation, but the path will depend on the final
11083            // package path (after the rename away from the stage path).
11084            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11085        }
11086
11087        // This is a special case for the "system" package, where the ABI is
11088        // dictated by the zygote configuration (and init.rc). We should keep track
11089        // of this ABI so that we can deal with "normal" applications that run under
11090        // the same UID correctly.
11091        if (mPlatformPackage == pkg) {
11092            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
11093                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
11094        }
11095
11096        // If there's a mismatch between the abi-override in the package setting
11097        // and the abiOverride specified for the install. Warn about this because we
11098        // would've already compiled the app without taking the package setting into
11099        // account.
11100        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
11101            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
11102                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
11103                        " for package " + pkg.packageName);
11104            }
11105        }
11106
11107        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11108        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11109        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
11110
11111        // Copy the derived override back to the parsed package, so that we can
11112        // update the package settings accordingly.
11113        pkg.cpuAbiOverride = cpuAbiOverride;
11114
11115        if (DEBUG_ABI_SELECTION) {
11116            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
11117                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
11118                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
11119        }
11120
11121        // Push the derived path down into PackageSettings so we know what to
11122        // clean up at uninstall time.
11123        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
11124
11125        if (DEBUG_ABI_SELECTION) {
11126            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
11127                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
11128                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
11129        }
11130
11131        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
11132        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
11133            // We don't do this here during boot because we can do it all
11134            // at once after scanning all existing packages.
11135            //
11136            // We also do this *before* we perform dexopt on this package, so that
11137            // we can avoid redundant dexopts, and also to make sure we've got the
11138            // code and package path correct.
11139            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
11140        }
11141
11142        if (mFactoryTest && pkg.requestedPermissions.contains(
11143                android.Manifest.permission.FACTORY_TEST)) {
11144            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
11145        }
11146
11147        if (isSystemApp(pkg)) {
11148            pkgSetting.isOrphaned = true;
11149        }
11150
11151        // Take care of first install / last update times.
11152        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
11153        if (currentTime != 0) {
11154            if (pkgSetting.firstInstallTime == 0) {
11155                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
11156            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11157                pkgSetting.lastUpdateTime = currentTime;
11158            }
11159        } else if (pkgSetting.firstInstallTime == 0) {
11160            // We need *something*.  Take time time stamp of the file.
11161            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11162        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11163            if (scanFileTime != pkgSetting.timeStamp) {
11164                // A package on the system image has changed; consider this
11165                // to be an update.
11166                pkgSetting.lastUpdateTime = scanFileTime;
11167            }
11168        }
11169        pkgSetting.setTimeStamp(scanFileTime);
11170
11171        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11172            if (nonMutatedPs != null) {
11173                synchronized (mPackages) {
11174                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11175                }
11176            }
11177        } else {
11178            final int userId = user == null ? 0 : user.getIdentifier();
11179            // Modify state for the given package setting
11180            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11181                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11182            if (pkgSetting.getInstantApp(userId)) {
11183                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11184            }
11185        }
11186        return pkg;
11187    }
11188
11189    /**
11190     * Applies policy to the parsed package based upon the given policy flags.
11191     * Ensures the package is in a good state.
11192     * <p>
11193     * Implementation detail: This method must NOT have any side effect. It would
11194     * ideally be static, but, it requires locks to read system state.
11195     */
11196    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11197        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11198            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11199            if (pkg.applicationInfo.isDirectBootAware()) {
11200                // we're direct boot aware; set for all components
11201                for (PackageParser.Service s : pkg.services) {
11202                    s.info.encryptionAware = s.info.directBootAware = true;
11203                }
11204                for (PackageParser.Provider p : pkg.providers) {
11205                    p.info.encryptionAware = p.info.directBootAware = true;
11206                }
11207                for (PackageParser.Activity a : pkg.activities) {
11208                    a.info.encryptionAware = a.info.directBootAware = true;
11209                }
11210                for (PackageParser.Activity r : pkg.receivers) {
11211                    r.info.encryptionAware = r.info.directBootAware = true;
11212                }
11213            }
11214            if (compressedFileExists(pkg.codePath)) {
11215                pkg.isStub = true;
11216            }
11217        } else {
11218            // Only allow system apps to be flagged as core apps.
11219            pkg.coreApp = false;
11220            // clear flags not applicable to regular apps
11221            pkg.applicationInfo.privateFlags &=
11222                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11223            pkg.applicationInfo.privateFlags &=
11224                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11225        }
11226        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11227
11228        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11229            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11230        }
11231
11232        if (!isSystemApp(pkg)) {
11233            // Only system apps can use these features.
11234            pkg.mOriginalPackages = null;
11235            pkg.mRealPackage = null;
11236            pkg.mAdoptPermissions = null;
11237        }
11238    }
11239
11240    /**
11241     * Asserts the parsed package is valid according to the given policy. If the
11242     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11243     * <p>
11244     * Implementation detail: This method must NOT have any side effects. It would
11245     * ideally be static, but, it requires locks to read system state.
11246     *
11247     * @throws PackageManagerException If the package fails any of the validation checks
11248     */
11249    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11250            throws PackageManagerException {
11251        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11252            assertCodePolicy(pkg);
11253        }
11254
11255        if (pkg.applicationInfo.getCodePath() == null ||
11256                pkg.applicationInfo.getResourcePath() == null) {
11257            // Bail out. The resource and code paths haven't been set.
11258            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11259                    "Code and resource paths haven't been set correctly");
11260        }
11261
11262        // Make sure we're not adding any bogus keyset info
11263        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11264        ksms.assertScannedPackageValid(pkg);
11265
11266        synchronized (mPackages) {
11267            // The special "android" package can only be defined once
11268            if (pkg.packageName.equals("android")) {
11269                if (mAndroidApplication != null) {
11270                    Slog.w(TAG, "*************************************************");
11271                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11272                    Slog.w(TAG, " codePath=" + pkg.codePath);
11273                    Slog.w(TAG, "*************************************************");
11274                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11275                            "Core android package being redefined.  Skipping.");
11276                }
11277            }
11278
11279            // A package name must be unique; don't allow duplicates
11280            if (mPackages.containsKey(pkg.packageName)) {
11281                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11282                        "Application package " + pkg.packageName
11283                        + " already installed.  Skipping duplicate.");
11284            }
11285
11286            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11287                // Static libs have a synthetic package name containing the version
11288                // but we still want the base name to be unique.
11289                if (mPackages.containsKey(pkg.manifestPackageName)) {
11290                    throw new PackageManagerException(
11291                            "Duplicate static shared lib provider package");
11292                }
11293
11294                // Static shared libraries should have at least O target SDK
11295                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11296                    throw new PackageManagerException(
11297                            "Packages declaring static-shared libs must target O SDK or higher");
11298                }
11299
11300                // Package declaring static a shared lib cannot be instant apps
11301                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11302                    throw new PackageManagerException(
11303                            "Packages declaring static-shared libs cannot be instant apps");
11304                }
11305
11306                // Package declaring static a shared lib cannot be renamed since the package
11307                // name is synthetic and apps can't code around package manager internals.
11308                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11309                    throw new PackageManagerException(
11310                            "Packages declaring static-shared libs cannot be renamed");
11311                }
11312
11313                // Package declaring static a shared lib cannot declare child packages
11314                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11315                    throw new PackageManagerException(
11316                            "Packages declaring static-shared libs cannot have child packages");
11317                }
11318
11319                // Package declaring static a shared lib cannot declare dynamic libs
11320                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11321                    throw new PackageManagerException(
11322                            "Packages declaring static-shared libs cannot declare dynamic libs");
11323                }
11324
11325                // Package declaring static a shared lib cannot declare shared users
11326                if (pkg.mSharedUserId != null) {
11327                    throw new PackageManagerException(
11328                            "Packages declaring static-shared libs cannot declare shared users");
11329                }
11330
11331                // Static shared libs cannot declare activities
11332                if (!pkg.activities.isEmpty()) {
11333                    throw new PackageManagerException(
11334                            "Static shared libs cannot declare activities");
11335                }
11336
11337                // Static shared libs cannot declare services
11338                if (!pkg.services.isEmpty()) {
11339                    throw new PackageManagerException(
11340                            "Static shared libs cannot declare services");
11341                }
11342
11343                // Static shared libs cannot declare providers
11344                if (!pkg.providers.isEmpty()) {
11345                    throw new PackageManagerException(
11346                            "Static shared libs cannot declare content providers");
11347                }
11348
11349                // Static shared libs cannot declare receivers
11350                if (!pkg.receivers.isEmpty()) {
11351                    throw new PackageManagerException(
11352                            "Static shared libs cannot declare broadcast receivers");
11353                }
11354
11355                // Static shared libs cannot declare permission groups
11356                if (!pkg.permissionGroups.isEmpty()) {
11357                    throw new PackageManagerException(
11358                            "Static shared libs cannot declare permission groups");
11359                }
11360
11361                // Static shared libs cannot declare permissions
11362                if (!pkg.permissions.isEmpty()) {
11363                    throw new PackageManagerException(
11364                            "Static shared libs cannot declare permissions");
11365                }
11366
11367                // Static shared libs cannot declare protected broadcasts
11368                if (pkg.protectedBroadcasts != null) {
11369                    throw new PackageManagerException(
11370                            "Static shared libs cannot declare protected broadcasts");
11371                }
11372
11373                // Static shared libs cannot be overlay targets
11374                if (pkg.mOverlayTarget != null) {
11375                    throw new PackageManagerException(
11376                            "Static shared libs cannot be overlay targets");
11377                }
11378
11379                // The version codes must be ordered as lib versions
11380                int minVersionCode = Integer.MIN_VALUE;
11381                int maxVersionCode = Integer.MAX_VALUE;
11382
11383                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11384                        pkg.staticSharedLibName);
11385                if (versionedLib != null) {
11386                    final int versionCount = versionedLib.size();
11387                    for (int i = 0; i < versionCount; i++) {
11388                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11389                        final int libVersionCode = libInfo.getDeclaringPackage()
11390                                .getVersionCode();
11391                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11392                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11393                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11394                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11395                        } else {
11396                            minVersionCode = maxVersionCode = libVersionCode;
11397                            break;
11398                        }
11399                    }
11400                }
11401                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11402                    throw new PackageManagerException("Static shared"
11403                            + " lib version codes must be ordered as lib versions");
11404                }
11405            }
11406
11407            // Only privileged apps and updated privileged apps can add child packages.
11408            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11409                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11410                    throw new PackageManagerException("Only privileged apps can add child "
11411                            + "packages. Ignoring package " + pkg.packageName);
11412                }
11413                final int childCount = pkg.childPackages.size();
11414                for (int i = 0; i < childCount; i++) {
11415                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11416                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11417                            childPkg.packageName)) {
11418                        throw new PackageManagerException("Can't override child of "
11419                                + "another disabled app. Ignoring package " + pkg.packageName);
11420                    }
11421                }
11422            }
11423
11424            // If we're only installing presumed-existing packages, require that the
11425            // scanned APK is both already known and at the path previously established
11426            // for it.  Previously unknown packages we pick up normally, but if we have an
11427            // a priori expectation about this package's install presence, enforce it.
11428            // With a singular exception for new system packages. When an OTA contains
11429            // a new system package, we allow the codepath to change from a system location
11430            // to the user-installed location. If we don't allow this change, any newer,
11431            // user-installed version of the application will be ignored.
11432            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11433                if (mExpectingBetter.containsKey(pkg.packageName)) {
11434                    logCriticalInfo(Log.WARN,
11435                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11436                } else {
11437                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11438                    if (known != null) {
11439                        if (DEBUG_PACKAGE_SCANNING) {
11440                            Log.d(TAG, "Examining " + pkg.codePath
11441                                    + " and requiring known paths " + known.codePathString
11442                                    + " & " + known.resourcePathString);
11443                        }
11444                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11445                                || !pkg.applicationInfo.getResourcePath().equals(
11446                                        known.resourcePathString)) {
11447                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11448                                    "Application package " + pkg.packageName
11449                                    + " found at " + pkg.applicationInfo.getCodePath()
11450                                    + " but expected at " + known.codePathString
11451                                    + "; ignoring.");
11452                        }
11453                    } else {
11454                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11455                                "Application package " + pkg.packageName
11456                                + " not found; ignoring.");
11457                    }
11458                }
11459            }
11460
11461            // Verify that this new package doesn't have any content providers
11462            // that conflict with existing packages.  Only do this if the
11463            // package isn't already installed, since we don't want to break
11464            // things that are installed.
11465            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11466                final int N = pkg.providers.size();
11467                int i;
11468                for (i=0; i<N; i++) {
11469                    PackageParser.Provider p = pkg.providers.get(i);
11470                    if (p.info.authority != null) {
11471                        String names[] = p.info.authority.split(";");
11472                        for (int j = 0; j < names.length; j++) {
11473                            if (mProvidersByAuthority.containsKey(names[j])) {
11474                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11475                                final String otherPackageName =
11476                                        ((other != null && other.getComponentName() != null) ?
11477                                                other.getComponentName().getPackageName() : "?");
11478                                throw new PackageManagerException(
11479                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11480                                        "Can't install because provider name " + names[j]
11481                                                + " (in package " + pkg.applicationInfo.packageName
11482                                                + ") is already used by " + otherPackageName);
11483                            }
11484                        }
11485                    }
11486                }
11487            }
11488        }
11489    }
11490
11491    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11492            int type, String declaringPackageName, int declaringVersionCode) {
11493        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11494        if (versionedLib == null) {
11495            versionedLib = new SparseArray<>();
11496            mSharedLibraries.put(name, versionedLib);
11497            if (type == SharedLibraryInfo.TYPE_STATIC) {
11498                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11499            }
11500        } else if (versionedLib.indexOfKey(version) >= 0) {
11501            return false;
11502        }
11503        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11504                version, type, declaringPackageName, declaringVersionCode);
11505        versionedLib.put(version, libEntry);
11506        return true;
11507    }
11508
11509    private boolean removeSharedLibraryLPw(String name, int version) {
11510        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11511        if (versionedLib == null) {
11512            return false;
11513        }
11514        final int libIdx = versionedLib.indexOfKey(version);
11515        if (libIdx < 0) {
11516            return false;
11517        }
11518        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11519        versionedLib.remove(version);
11520        if (versionedLib.size() <= 0) {
11521            mSharedLibraries.remove(name);
11522            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11523                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11524                        .getPackageName());
11525            }
11526        }
11527        return true;
11528    }
11529
11530    /**
11531     * Adds a scanned package to the system. When this method is finished, the package will
11532     * be available for query, resolution, etc...
11533     */
11534    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11535            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11536        final String pkgName = pkg.packageName;
11537        if (mCustomResolverComponentName != null &&
11538                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11539            setUpCustomResolverActivity(pkg);
11540        }
11541
11542        if (pkg.packageName.equals("android")) {
11543            synchronized (mPackages) {
11544                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11545                    // Set up information for our fall-back user intent resolution activity.
11546                    mPlatformPackage = pkg;
11547                    pkg.mVersionCode = mSdkVersion;
11548                    mAndroidApplication = pkg.applicationInfo;
11549                    if (!mResolverReplaced) {
11550                        mResolveActivity.applicationInfo = mAndroidApplication;
11551                        mResolveActivity.name = ResolverActivity.class.getName();
11552                        mResolveActivity.packageName = mAndroidApplication.packageName;
11553                        mResolveActivity.processName = "system:ui";
11554                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11555                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11556                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11557                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11558                        mResolveActivity.exported = true;
11559                        mResolveActivity.enabled = true;
11560                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11561                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11562                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11563                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11564                                | ActivityInfo.CONFIG_ORIENTATION
11565                                | ActivityInfo.CONFIG_KEYBOARD
11566                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11567                        mResolveInfo.activityInfo = mResolveActivity;
11568                        mResolveInfo.priority = 0;
11569                        mResolveInfo.preferredOrder = 0;
11570                        mResolveInfo.match = 0;
11571                        mResolveComponentName = new ComponentName(
11572                                mAndroidApplication.packageName, mResolveActivity.name);
11573                    }
11574                }
11575            }
11576        }
11577
11578        ArrayList<PackageParser.Package> clientLibPkgs = null;
11579        // writer
11580        synchronized (mPackages) {
11581            boolean hasStaticSharedLibs = false;
11582
11583            // Any app can add new static shared libraries
11584            if (pkg.staticSharedLibName != null) {
11585                // Static shared libs don't allow renaming as they have synthetic package
11586                // names to allow install of multiple versions, so use name from manifest.
11587                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11588                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11589                        pkg.manifestPackageName, pkg.mVersionCode)) {
11590                    hasStaticSharedLibs = true;
11591                } else {
11592                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11593                                + pkg.staticSharedLibName + " already exists; skipping");
11594                }
11595                // Static shared libs cannot be updated once installed since they
11596                // use synthetic package name which includes the version code, so
11597                // not need to update other packages's shared lib dependencies.
11598            }
11599
11600            if (!hasStaticSharedLibs
11601                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11602                // Only system apps can add new dynamic shared libraries.
11603                if (pkg.libraryNames != null) {
11604                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11605                        String name = pkg.libraryNames.get(i);
11606                        boolean allowed = false;
11607                        if (pkg.isUpdatedSystemApp()) {
11608                            // New library entries can only be added through the
11609                            // system image.  This is important to get rid of a lot
11610                            // of nasty edge cases: for example if we allowed a non-
11611                            // system update of the app to add a library, then uninstalling
11612                            // the update would make the library go away, and assumptions
11613                            // we made such as through app install filtering would now
11614                            // have allowed apps on the device which aren't compatible
11615                            // with it.  Better to just have the restriction here, be
11616                            // conservative, and create many fewer cases that can negatively
11617                            // impact the user experience.
11618                            final PackageSetting sysPs = mSettings
11619                                    .getDisabledSystemPkgLPr(pkg.packageName);
11620                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11621                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11622                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11623                                        allowed = true;
11624                                        break;
11625                                    }
11626                                }
11627                            }
11628                        } else {
11629                            allowed = true;
11630                        }
11631                        if (allowed) {
11632                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11633                                    SharedLibraryInfo.VERSION_UNDEFINED,
11634                                    SharedLibraryInfo.TYPE_DYNAMIC,
11635                                    pkg.packageName, pkg.mVersionCode)) {
11636                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11637                                        + name + " already exists; skipping");
11638                            }
11639                        } else {
11640                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11641                                    + name + " that is not declared on system image; skipping");
11642                        }
11643                    }
11644
11645                    if ((scanFlags & SCAN_BOOTING) == 0) {
11646                        // If we are not booting, we need to update any applications
11647                        // that are clients of our shared library.  If we are booting,
11648                        // this will all be done once the scan is complete.
11649                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11650                    }
11651                }
11652            }
11653        }
11654
11655        if ((scanFlags & SCAN_BOOTING) != 0) {
11656            // No apps can run during boot scan, so they don't need to be frozen
11657        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11658            // Caller asked to not kill app, so it's probably not frozen
11659        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11660            // Caller asked us to ignore frozen check for some reason; they
11661            // probably didn't know the package name
11662        } else {
11663            // We're doing major surgery on this package, so it better be frozen
11664            // right now to keep it from launching
11665            checkPackageFrozen(pkgName);
11666        }
11667
11668        // Also need to kill any apps that are dependent on the library.
11669        if (clientLibPkgs != null) {
11670            for (int i=0; i<clientLibPkgs.size(); i++) {
11671                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11672                killApplication(clientPkg.applicationInfo.packageName,
11673                        clientPkg.applicationInfo.uid, "update lib");
11674            }
11675        }
11676
11677        // writer
11678        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11679
11680        synchronized (mPackages) {
11681            // We don't expect installation to fail beyond this point
11682
11683            // Add the new setting to mSettings
11684            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11685            // Add the new setting to mPackages
11686            mPackages.put(pkg.applicationInfo.packageName, pkg);
11687            // Make sure we don't accidentally delete its data.
11688            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11689            while (iter.hasNext()) {
11690                PackageCleanItem item = iter.next();
11691                if (pkgName.equals(item.packageName)) {
11692                    iter.remove();
11693                }
11694            }
11695
11696            // Add the package's KeySets to the global KeySetManagerService
11697            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11698            ksms.addScannedPackageLPw(pkg);
11699
11700            int N = pkg.providers.size();
11701            StringBuilder r = null;
11702            int i;
11703            for (i=0; i<N; i++) {
11704                PackageParser.Provider p = pkg.providers.get(i);
11705                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11706                        p.info.processName);
11707                mProviders.addProvider(p);
11708                p.syncable = p.info.isSyncable;
11709                if (p.info.authority != null) {
11710                    String names[] = p.info.authority.split(";");
11711                    p.info.authority = null;
11712                    for (int j = 0; j < names.length; j++) {
11713                        if (j == 1 && p.syncable) {
11714                            // We only want the first authority for a provider to possibly be
11715                            // syncable, so if we already added this provider using a different
11716                            // authority clear the syncable flag. We copy the provider before
11717                            // changing it because the mProviders object contains a reference
11718                            // to a provider that we don't want to change.
11719                            // Only do this for the second authority since the resulting provider
11720                            // object can be the same for all future authorities for this provider.
11721                            p = new PackageParser.Provider(p);
11722                            p.syncable = false;
11723                        }
11724                        if (!mProvidersByAuthority.containsKey(names[j])) {
11725                            mProvidersByAuthority.put(names[j], p);
11726                            if (p.info.authority == null) {
11727                                p.info.authority = names[j];
11728                            } else {
11729                                p.info.authority = p.info.authority + ";" + names[j];
11730                            }
11731                            if (DEBUG_PACKAGE_SCANNING) {
11732                                if (chatty)
11733                                    Log.d(TAG, "Registered content provider: " + names[j]
11734                                            + ", className = " + p.info.name + ", isSyncable = "
11735                                            + p.info.isSyncable);
11736                            }
11737                        } else {
11738                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11739                            Slog.w(TAG, "Skipping provider name " + names[j] +
11740                                    " (in package " + pkg.applicationInfo.packageName +
11741                                    "): name already used by "
11742                                    + ((other != null && other.getComponentName() != null)
11743                                            ? other.getComponentName().getPackageName() : "?"));
11744                        }
11745                    }
11746                }
11747                if (chatty) {
11748                    if (r == null) {
11749                        r = new StringBuilder(256);
11750                    } else {
11751                        r.append(' ');
11752                    }
11753                    r.append(p.info.name);
11754                }
11755            }
11756            if (r != null) {
11757                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11758            }
11759
11760            N = pkg.services.size();
11761            r = null;
11762            for (i=0; i<N; i++) {
11763                PackageParser.Service s = pkg.services.get(i);
11764                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11765                        s.info.processName);
11766                mServices.addService(s);
11767                if (chatty) {
11768                    if (r == null) {
11769                        r = new StringBuilder(256);
11770                    } else {
11771                        r.append(' ');
11772                    }
11773                    r.append(s.info.name);
11774                }
11775            }
11776            if (r != null) {
11777                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11778            }
11779
11780            N = pkg.receivers.size();
11781            r = null;
11782            for (i=0; i<N; i++) {
11783                PackageParser.Activity a = pkg.receivers.get(i);
11784                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11785                        a.info.processName);
11786                mReceivers.addActivity(a, "receiver");
11787                if (chatty) {
11788                    if (r == null) {
11789                        r = new StringBuilder(256);
11790                    } else {
11791                        r.append(' ');
11792                    }
11793                    r.append(a.info.name);
11794                }
11795            }
11796            if (r != null) {
11797                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11798            }
11799
11800            N = pkg.activities.size();
11801            r = null;
11802            for (i=0; i<N; i++) {
11803                PackageParser.Activity a = pkg.activities.get(i);
11804                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11805                        a.info.processName);
11806                mActivities.addActivity(a, "activity");
11807                if (chatty) {
11808                    if (r == null) {
11809                        r = new StringBuilder(256);
11810                    } else {
11811                        r.append(' ');
11812                    }
11813                    r.append(a.info.name);
11814                }
11815            }
11816            if (r != null) {
11817                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11818            }
11819
11820            N = pkg.permissionGroups.size();
11821            r = null;
11822            for (i=0; i<N; i++) {
11823                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11824                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11825                final String curPackageName = cur == null ? null : cur.info.packageName;
11826                // Dont allow ephemeral apps to define new permission groups.
11827                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11828                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11829                            + pg.info.packageName
11830                            + " ignored: instant apps cannot define new permission groups.");
11831                    continue;
11832                }
11833                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11834                if (cur == null || isPackageUpdate) {
11835                    mPermissionGroups.put(pg.info.name, pg);
11836                    if (chatty) {
11837                        if (r == null) {
11838                            r = new StringBuilder(256);
11839                        } else {
11840                            r.append(' ');
11841                        }
11842                        if (isPackageUpdate) {
11843                            r.append("UPD:");
11844                        }
11845                        r.append(pg.info.name);
11846                    }
11847                } else {
11848                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11849                            + pg.info.packageName + " ignored: original from "
11850                            + cur.info.packageName);
11851                    if (chatty) {
11852                        if (r == null) {
11853                            r = new StringBuilder(256);
11854                        } else {
11855                            r.append(' ');
11856                        }
11857                        r.append("DUP:");
11858                        r.append(pg.info.name);
11859                    }
11860                }
11861            }
11862            if (r != null) {
11863                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11864            }
11865
11866            N = pkg.permissions.size();
11867            r = null;
11868            for (i=0; i<N; i++) {
11869                PackageParser.Permission p = pkg.permissions.get(i);
11870
11871                // Dont allow ephemeral apps to define new permissions.
11872                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11873                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11874                            + p.info.packageName
11875                            + " ignored: instant apps cannot define new permissions.");
11876                    continue;
11877                }
11878
11879                // Assume by default that we did not install this permission into the system.
11880                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11881
11882                // Now that permission groups have a special meaning, we ignore permission
11883                // groups for legacy apps to prevent unexpected behavior. In particular,
11884                // permissions for one app being granted to someone just because they happen
11885                // to be in a group defined by another app (before this had no implications).
11886                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11887                    p.group = mPermissionGroups.get(p.info.group);
11888                    // Warn for a permission in an unknown group.
11889                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11890                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11891                                + p.info.packageName + " in an unknown group " + p.info.group);
11892                    }
11893                }
11894
11895                ArrayMap<String, BasePermission> permissionMap =
11896                        p.tree ? mSettings.mPermissionTrees
11897                                : mSettings.mPermissions;
11898                BasePermission bp = permissionMap.get(p.info.name);
11899
11900                // Allow system apps to redefine non-system permissions
11901                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11902                    final boolean currentOwnerIsSystem = (bp.perm != null
11903                            && isSystemApp(bp.perm.owner));
11904                    if (isSystemApp(p.owner)) {
11905                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11906                            // It's a built-in permission and no owner, take ownership now
11907                            bp.packageSetting = pkgSetting;
11908                            bp.perm = p;
11909                            bp.uid = pkg.applicationInfo.uid;
11910                            bp.sourcePackage = p.info.packageName;
11911                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11912                        } else if (!currentOwnerIsSystem) {
11913                            String msg = "New decl " + p.owner + " of permission  "
11914                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11915                            reportSettingsProblem(Log.WARN, msg);
11916                            bp = null;
11917                        }
11918                    }
11919                }
11920
11921                if (bp == null) {
11922                    bp = new BasePermission(p.info.name, p.info.packageName,
11923                            BasePermission.TYPE_NORMAL);
11924                    permissionMap.put(p.info.name, bp);
11925                }
11926
11927                if (bp.perm == null) {
11928                    if (bp.sourcePackage == null
11929                            || bp.sourcePackage.equals(p.info.packageName)) {
11930                        BasePermission tree = findPermissionTreeLP(p.info.name);
11931                        if (tree == null
11932                                || tree.sourcePackage.equals(p.info.packageName)) {
11933                            bp.packageSetting = pkgSetting;
11934                            bp.perm = p;
11935                            bp.uid = pkg.applicationInfo.uid;
11936                            bp.sourcePackage = p.info.packageName;
11937                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11938                            if (chatty) {
11939                                if (r == null) {
11940                                    r = new StringBuilder(256);
11941                                } else {
11942                                    r.append(' ');
11943                                }
11944                                r.append(p.info.name);
11945                            }
11946                        } else {
11947                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11948                                    + p.info.packageName + " ignored: base tree "
11949                                    + tree.name + " is from package "
11950                                    + tree.sourcePackage);
11951                        }
11952                    } else {
11953                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11954                                + p.info.packageName + " ignored: original from "
11955                                + bp.sourcePackage);
11956                    }
11957                } else if (chatty) {
11958                    if (r == null) {
11959                        r = new StringBuilder(256);
11960                    } else {
11961                        r.append(' ');
11962                    }
11963                    r.append("DUP:");
11964                    r.append(p.info.name);
11965                }
11966                if (bp.perm == p) {
11967                    bp.protectionLevel = p.info.protectionLevel;
11968                }
11969            }
11970
11971            if (r != null) {
11972                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11973            }
11974
11975            N = pkg.instrumentation.size();
11976            r = null;
11977            for (i=0; i<N; i++) {
11978                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11979                a.info.packageName = pkg.applicationInfo.packageName;
11980                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11981                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11982                a.info.splitNames = pkg.splitNames;
11983                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11984                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11985                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11986                a.info.dataDir = pkg.applicationInfo.dataDir;
11987                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11988                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11989                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11990                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11991                mInstrumentation.put(a.getComponentName(), a);
11992                if (chatty) {
11993                    if (r == null) {
11994                        r = new StringBuilder(256);
11995                    } else {
11996                        r.append(' ');
11997                    }
11998                    r.append(a.info.name);
11999                }
12000            }
12001            if (r != null) {
12002                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
12003            }
12004
12005            if (pkg.protectedBroadcasts != null) {
12006                N = pkg.protectedBroadcasts.size();
12007                synchronized (mProtectedBroadcasts) {
12008                    for (i = 0; i < N; i++) {
12009                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
12010                    }
12011                }
12012            }
12013        }
12014
12015        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12016    }
12017
12018    /**
12019     * Derive the ABI of a non-system package located at {@code scanFile}. This information
12020     * is derived purely on the basis of the contents of {@code scanFile} and
12021     * {@code cpuAbiOverride}.
12022     *
12023     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
12024     */
12025    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
12026                                 String cpuAbiOverride, boolean extractLibs,
12027                                 File appLib32InstallDir)
12028            throws PackageManagerException {
12029        // Give ourselves some initial paths; we'll come back for another
12030        // pass once we've determined ABI below.
12031        setNativeLibraryPaths(pkg, appLib32InstallDir);
12032
12033        // We would never need to extract libs for forward-locked and external packages,
12034        // since the container service will do it for us. We shouldn't attempt to
12035        // extract libs from system app when it was not updated.
12036        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
12037                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
12038            extractLibs = false;
12039        }
12040
12041        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
12042        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
12043
12044        NativeLibraryHelper.Handle handle = null;
12045        try {
12046            handle = NativeLibraryHelper.Handle.create(pkg);
12047            // TODO(multiArch): This can be null for apps that didn't go through the
12048            // usual installation process. We can calculate it again, like we
12049            // do during install time.
12050            //
12051            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
12052            // unnecessary.
12053            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
12054
12055            // Null out the abis so that they can be recalculated.
12056            pkg.applicationInfo.primaryCpuAbi = null;
12057            pkg.applicationInfo.secondaryCpuAbi = null;
12058            if (isMultiArch(pkg.applicationInfo)) {
12059                // Warn if we've set an abiOverride for multi-lib packages..
12060                // By definition, we need to copy both 32 and 64 bit libraries for
12061                // such packages.
12062                if (pkg.cpuAbiOverride != null
12063                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
12064                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
12065                }
12066
12067                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
12068                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
12069                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
12070                    if (extractLibs) {
12071                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12072                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12073                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
12074                                useIsaSpecificSubdirs);
12075                    } else {
12076                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12077                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
12078                    }
12079                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12080                }
12081
12082                // Shared library native code should be in the APK zip aligned
12083                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
12084                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12085                            "Shared library native lib extraction not supported");
12086                }
12087
12088                maybeThrowExceptionForMultiArchCopy(
12089                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
12090
12091                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
12092                    if (extractLibs) {
12093                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12094                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12095                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
12096                                useIsaSpecificSubdirs);
12097                    } else {
12098                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12099                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
12100                    }
12101                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12102                }
12103
12104                maybeThrowExceptionForMultiArchCopy(
12105                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
12106
12107                if (abi64 >= 0) {
12108                    // Shared library native libs should be in the APK zip aligned
12109                    if (extractLibs && pkg.isLibrary()) {
12110                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12111                                "Shared library native lib extraction not supported");
12112                    }
12113                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
12114                }
12115
12116                if (abi32 >= 0) {
12117                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
12118                    if (abi64 >= 0) {
12119                        if (pkg.use32bitAbi) {
12120                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
12121                            pkg.applicationInfo.primaryCpuAbi = abi;
12122                        } else {
12123                            pkg.applicationInfo.secondaryCpuAbi = abi;
12124                        }
12125                    } else {
12126                        pkg.applicationInfo.primaryCpuAbi = abi;
12127                    }
12128                }
12129            } else {
12130                String[] abiList = (cpuAbiOverride != null) ?
12131                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
12132
12133                // Enable gross and lame hacks for apps that are built with old
12134                // SDK tools. We must scan their APKs for renderscript bitcode and
12135                // not launch them if it's present. Don't bother checking on devices
12136                // that don't have 64 bit support.
12137                boolean needsRenderScriptOverride = false;
12138                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
12139                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
12140                    abiList = Build.SUPPORTED_32_BIT_ABIS;
12141                    needsRenderScriptOverride = true;
12142                }
12143
12144                final int copyRet;
12145                if (extractLibs) {
12146                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12147                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12148                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
12149                } else {
12150                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12151                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
12152                }
12153                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12154
12155                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
12156                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12157                            "Error unpackaging native libs for app, errorCode=" + copyRet);
12158                }
12159
12160                if (copyRet >= 0) {
12161                    // Shared libraries that have native libs must be multi-architecture
12162                    if (pkg.isLibrary()) {
12163                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12164                                "Shared library with native libs must be multiarch");
12165                    }
12166                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12167                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12168                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12169                } else if (needsRenderScriptOverride) {
12170                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
12171                }
12172            }
12173        } catch (IOException ioe) {
12174            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12175        } finally {
12176            IoUtils.closeQuietly(handle);
12177        }
12178
12179        // Now that we've calculated the ABIs and determined if it's an internal app,
12180        // we will go ahead and populate the nativeLibraryPath.
12181        setNativeLibraryPaths(pkg, appLib32InstallDir);
12182    }
12183
12184    /**
12185     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12186     * i.e, so that all packages can be run inside a single process if required.
12187     *
12188     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12189     * this function will either try and make the ABI for all packages in {@code packagesForUser}
12190     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12191     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12192     * updating a package that belongs to a shared user.
12193     *
12194     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12195     * adds unnecessary complexity.
12196     */
12197    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
12198            PackageParser.Package scannedPackage) {
12199        String requiredInstructionSet = null;
12200        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12201            requiredInstructionSet = VMRuntime.getInstructionSet(
12202                     scannedPackage.applicationInfo.primaryCpuAbi);
12203        }
12204
12205        PackageSetting requirer = null;
12206        for (PackageSetting ps : packagesForUser) {
12207            // If packagesForUser contains scannedPackage, we skip it. This will happen
12208            // when scannedPackage is an update of an existing package. Without this check,
12209            // we will never be able to change the ABI of any package belonging to a shared
12210            // user, even if it's compatible with other packages.
12211            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12212                if (ps.primaryCpuAbiString == null) {
12213                    continue;
12214                }
12215
12216                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12217                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12218                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12219                    // this but there's not much we can do.
12220                    String errorMessage = "Instruction set mismatch, "
12221                            + ((requirer == null) ? "[caller]" : requirer)
12222                            + " requires " + requiredInstructionSet + " whereas " + ps
12223                            + " requires " + instructionSet;
12224                    Slog.w(TAG, errorMessage);
12225                }
12226
12227                if (requiredInstructionSet == null) {
12228                    requiredInstructionSet = instructionSet;
12229                    requirer = ps;
12230                }
12231            }
12232        }
12233
12234        if (requiredInstructionSet != null) {
12235            String adjustedAbi;
12236            if (requirer != null) {
12237                // requirer != null implies that either scannedPackage was null or that scannedPackage
12238                // did not require an ABI, in which case we have to adjust scannedPackage to match
12239                // the ABI of the set (which is the same as requirer's ABI)
12240                adjustedAbi = requirer.primaryCpuAbiString;
12241                if (scannedPackage != null) {
12242                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12243                }
12244            } else {
12245                // requirer == null implies that we're updating all ABIs in the set to
12246                // match scannedPackage.
12247                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12248            }
12249
12250            for (PackageSetting ps : packagesForUser) {
12251                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12252                    if (ps.primaryCpuAbiString != null) {
12253                        continue;
12254                    }
12255
12256                    ps.primaryCpuAbiString = adjustedAbi;
12257                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12258                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12259                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12260                        if (DEBUG_ABI_SELECTION) {
12261                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12262                                    + " (requirer="
12263                                    + (requirer != null ? requirer.pkg : "null")
12264                                    + ", scannedPackage="
12265                                    + (scannedPackage != null ? scannedPackage : "null")
12266                                    + ")");
12267                        }
12268                        try {
12269                            mInstaller.rmdex(ps.codePathString,
12270                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12271                        } catch (InstallerException ignored) {
12272                        }
12273                    }
12274                }
12275            }
12276        }
12277    }
12278
12279    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12280        synchronized (mPackages) {
12281            mResolverReplaced = true;
12282            // Set up information for custom user intent resolution activity.
12283            mResolveActivity.applicationInfo = pkg.applicationInfo;
12284            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12285            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12286            mResolveActivity.processName = pkg.applicationInfo.packageName;
12287            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12288            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12289                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12290            mResolveActivity.theme = 0;
12291            mResolveActivity.exported = true;
12292            mResolveActivity.enabled = true;
12293            mResolveInfo.activityInfo = mResolveActivity;
12294            mResolveInfo.priority = 0;
12295            mResolveInfo.preferredOrder = 0;
12296            mResolveInfo.match = 0;
12297            mResolveComponentName = mCustomResolverComponentName;
12298            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12299                    mResolveComponentName);
12300        }
12301    }
12302
12303    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12304        if (installerActivity == null) {
12305            if (DEBUG_EPHEMERAL) {
12306                Slog.d(TAG, "Clear ephemeral installer activity");
12307            }
12308            mInstantAppInstallerActivity = null;
12309            return;
12310        }
12311
12312        if (DEBUG_EPHEMERAL) {
12313            Slog.d(TAG, "Set ephemeral installer activity: "
12314                    + installerActivity.getComponentName());
12315        }
12316        // Set up information for ephemeral installer activity
12317        mInstantAppInstallerActivity = installerActivity;
12318        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12319                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12320        mInstantAppInstallerActivity.exported = true;
12321        mInstantAppInstallerActivity.enabled = true;
12322        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12323        mInstantAppInstallerInfo.priority = 0;
12324        mInstantAppInstallerInfo.preferredOrder = 1;
12325        mInstantAppInstallerInfo.isDefault = true;
12326        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12327                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12328    }
12329
12330    private static String calculateBundledApkRoot(final String codePathString) {
12331        final File codePath = new File(codePathString);
12332        final File codeRoot;
12333        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12334            codeRoot = Environment.getRootDirectory();
12335        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12336            codeRoot = Environment.getOemDirectory();
12337        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12338            codeRoot = Environment.getVendorDirectory();
12339        } else {
12340            // Unrecognized code path; take its top real segment as the apk root:
12341            // e.g. /something/app/blah.apk => /something
12342            try {
12343                File f = codePath.getCanonicalFile();
12344                File parent = f.getParentFile();    // non-null because codePath is a file
12345                File tmp;
12346                while ((tmp = parent.getParentFile()) != null) {
12347                    f = parent;
12348                    parent = tmp;
12349                }
12350                codeRoot = f;
12351                Slog.w(TAG, "Unrecognized code path "
12352                        + codePath + " - using " + codeRoot);
12353            } catch (IOException e) {
12354                // Can't canonicalize the code path -- shenanigans?
12355                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12356                return Environment.getRootDirectory().getPath();
12357            }
12358        }
12359        return codeRoot.getPath();
12360    }
12361
12362    /**
12363     * Derive and set the location of native libraries for the given package,
12364     * which varies depending on where and how the package was installed.
12365     */
12366    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12367        final ApplicationInfo info = pkg.applicationInfo;
12368        final String codePath = pkg.codePath;
12369        final File codeFile = new File(codePath);
12370        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12371        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12372
12373        info.nativeLibraryRootDir = null;
12374        info.nativeLibraryRootRequiresIsa = false;
12375        info.nativeLibraryDir = null;
12376        info.secondaryNativeLibraryDir = null;
12377
12378        if (isApkFile(codeFile)) {
12379            // Monolithic install
12380            if (bundledApp) {
12381                // If "/system/lib64/apkname" exists, assume that is the per-package
12382                // native library directory to use; otherwise use "/system/lib/apkname".
12383                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12384                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12385                        getPrimaryInstructionSet(info));
12386
12387                // This is a bundled system app so choose the path based on the ABI.
12388                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12389                // is just the default path.
12390                final String apkName = deriveCodePathName(codePath);
12391                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12392                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12393                        apkName).getAbsolutePath();
12394
12395                if (info.secondaryCpuAbi != null) {
12396                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12397                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12398                            secondaryLibDir, apkName).getAbsolutePath();
12399                }
12400            } else if (asecApp) {
12401                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12402                        .getAbsolutePath();
12403            } else {
12404                final String apkName = deriveCodePathName(codePath);
12405                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12406                        .getAbsolutePath();
12407            }
12408
12409            info.nativeLibraryRootRequiresIsa = false;
12410            info.nativeLibraryDir = info.nativeLibraryRootDir;
12411        } else {
12412            // Cluster install
12413            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12414            info.nativeLibraryRootRequiresIsa = true;
12415
12416            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12417                    getPrimaryInstructionSet(info)).getAbsolutePath();
12418
12419            if (info.secondaryCpuAbi != null) {
12420                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12421                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12422            }
12423        }
12424    }
12425
12426    /**
12427     * Calculate the abis and roots for a bundled app. These can uniquely
12428     * be determined from the contents of the system partition, i.e whether
12429     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12430     * of this information, and instead assume that the system was built
12431     * sensibly.
12432     */
12433    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12434                                           PackageSetting pkgSetting) {
12435        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12436
12437        // If "/system/lib64/apkname" exists, assume that is the per-package
12438        // native library directory to use; otherwise use "/system/lib/apkname".
12439        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12440        setBundledAppAbi(pkg, apkRoot, apkName);
12441        // pkgSetting might be null during rescan following uninstall of updates
12442        // to a bundled app, so accommodate that possibility.  The settings in
12443        // that case will be established later from the parsed package.
12444        //
12445        // If the settings aren't null, sync them up with what we've just derived.
12446        // note that apkRoot isn't stored in the package settings.
12447        if (pkgSetting != null) {
12448            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12449            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12450        }
12451    }
12452
12453    /**
12454     * Deduces the ABI of a bundled app and sets the relevant fields on the
12455     * parsed pkg object.
12456     *
12457     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12458     *        under which system libraries are installed.
12459     * @param apkName the name of the installed package.
12460     */
12461    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12462        final File codeFile = new File(pkg.codePath);
12463
12464        final boolean has64BitLibs;
12465        final boolean has32BitLibs;
12466        if (isApkFile(codeFile)) {
12467            // Monolithic install
12468            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12469            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12470        } else {
12471            // Cluster install
12472            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12473            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12474                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12475                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12476                has64BitLibs = (new File(rootDir, isa)).exists();
12477            } else {
12478                has64BitLibs = false;
12479            }
12480            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12481                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12482                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12483                has32BitLibs = (new File(rootDir, isa)).exists();
12484            } else {
12485                has32BitLibs = false;
12486            }
12487        }
12488
12489        if (has64BitLibs && !has32BitLibs) {
12490            // The package has 64 bit libs, but not 32 bit libs. Its primary
12491            // ABI should be 64 bit. We can safely assume here that the bundled
12492            // native libraries correspond to the most preferred ABI in the list.
12493
12494            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12495            pkg.applicationInfo.secondaryCpuAbi = null;
12496        } else if (has32BitLibs && !has64BitLibs) {
12497            // The package has 32 bit libs but not 64 bit libs. Its primary
12498            // ABI should be 32 bit.
12499
12500            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12501            pkg.applicationInfo.secondaryCpuAbi = null;
12502        } else if (has32BitLibs && has64BitLibs) {
12503            // The application has both 64 and 32 bit bundled libraries. We check
12504            // here that the app declares multiArch support, and warn if it doesn't.
12505            //
12506            // We will be lenient here and record both ABIs. The primary will be the
12507            // ABI that's higher on the list, i.e, a device that's configured to prefer
12508            // 64 bit apps will see a 64 bit primary ABI,
12509
12510            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12511                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12512            }
12513
12514            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12515                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12516                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12517            } else {
12518                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12519                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12520            }
12521        } else {
12522            pkg.applicationInfo.primaryCpuAbi = null;
12523            pkg.applicationInfo.secondaryCpuAbi = null;
12524        }
12525    }
12526
12527    private void killApplication(String pkgName, int appId, String reason) {
12528        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12529    }
12530
12531    private void killApplication(String pkgName, int appId, int userId, String reason) {
12532        // Request the ActivityManager to kill the process(only for existing packages)
12533        // so that we do not end up in a confused state while the user is still using the older
12534        // version of the application while the new one gets installed.
12535        final long token = Binder.clearCallingIdentity();
12536        try {
12537            IActivityManager am = ActivityManager.getService();
12538            if (am != null) {
12539                try {
12540                    am.killApplication(pkgName, appId, userId, reason);
12541                } catch (RemoteException e) {
12542                }
12543            }
12544        } finally {
12545            Binder.restoreCallingIdentity(token);
12546        }
12547    }
12548
12549    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12550        // Remove the parent package setting
12551        PackageSetting ps = (PackageSetting) pkg.mExtras;
12552        if (ps != null) {
12553            removePackageLI(ps, chatty);
12554        }
12555        // Remove the child package setting
12556        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12557        for (int i = 0; i < childCount; i++) {
12558            PackageParser.Package childPkg = pkg.childPackages.get(i);
12559            ps = (PackageSetting) childPkg.mExtras;
12560            if (ps != null) {
12561                removePackageLI(ps, chatty);
12562            }
12563        }
12564    }
12565
12566    void removePackageLI(PackageSetting ps, boolean chatty) {
12567        if (DEBUG_INSTALL) {
12568            if (chatty)
12569                Log.d(TAG, "Removing package " + ps.name);
12570        }
12571
12572        // writer
12573        synchronized (mPackages) {
12574            mPackages.remove(ps.name);
12575            final PackageParser.Package pkg = ps.pkg;
12576            if (pkg != null) {
12577                cleanPackageDataStructuresLILPw(pkg, chatty);
12578            }
12579        }
12580    }
12581
12582    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12583        if (DEBUG_INSTALL) {
12584            if (chatty)
12585                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12586        }
12587
12588        // writer
12589        synchronized (mPackages) {
12590            // Remove the parent package
12591            mPackages.remove(pkg.applicationInfo.packageName);
12592            cleanPackageDataStructuresLILPw(pkg, chatty);
12593
12594            // Remove the child packages
12595            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12596            for (int i = 0; i < childCount; i++) {
12597                PackageParser.Package childPkg = pkg.childPackages.get(i);
12598                mPackages.remove(childPkg.applicationInfo.packageName);
12599                cleanPackageDataStructuresLILPw(childPkg, chatty);
12600            }
12601        }
12602    }
12603
12604    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12605        int N = pkg.providers.size();
12606        StringBuilder r = null;
12607        int i;
12608        for (i=0; i<N; i++) {
12609            PackageParser.Provider p = pkg.providers.get(i);
12610            mProviders.removeProvider(p);
12611            if (p.info.authority == null) {
12612
12613                /* There was another ContentProvider with this authority when
12614                 * this app was installed so this authority is null,
12615                 * Ignore it as we don't have to unregister the provider.
12616                 */
12617                continue;
12618            }
12619            String names[] = p.info.authority.split(";");
12620            for (int j = 0; j < names.length; j++) {
12621                if (mProvidersByAuthority.get(names[j]) == p) {
12622                    mProvidersByAuthority.remove(names[j]);
12623                    if (DEBUG_REMOVE) {
12624                        if (chatty)
12625                            Log.d(TAG, "Unregistered content provider: " + names[j]
12626                                    + ", className = " + p.info.name + ", isSyncable = "
12627                                    + p.info.isSyncable);
12628                    }
12629                }
12630            }
12631            if (DEBUG_REMOVE && chatty) {
12632                if (r == null) {
12633                    r = new StringBuilder(256);
12634                } else {
12635                    r.append(' ');
12636                }
12637                r.append(p.info.name);
12638            }
12639        }
12640        if (r != null) {
12641            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12642        }
12643
12644        N = pkg.services.size();
12645        r = null;
12646        for (i=0; i<N; i++) {
12647            PackageParser.Service s = pkg.services.get(i);
12648            mServices.removeService(s);
12649            if (chatty) {
12650                if (r == null) {
12651                    r = new StringBuilder(256);
12652                } else {
12653                    r.append(' ');
12654                }
12655                r.append(s.info.name);
12656            }
12657        }
12658        if (r != null) {
12659            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12660        }
12661
12662        N = pkg.receivers.size();
12663        r = null;
12664        for (i=0; i<N; i++) {
12665            PackageParser.Activity a = pkg.receivers.get(i);
12666            mReceivers.removeActivity(a, "receiver");
12667            if (DEBUG_REMOVE && chatty) {
12668                if (r == null) {
12669                    r = new StringBuilder(256);
12670                } else {
12671                    r.append(' ');
12672                }
12673                r.append(a.info.name);
12674            }
12675        }
12676        if (r != null) {
12677            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12678        }
12679
12680        N = pkg.activities.size();
12681        r = null;
12682        for (i=0; i<N; i++) {
12683            PackageParser.Activity a = pkg.activities.get(i);
12684            mActivities.removeActivity(a, "activity");
12685            if (DEBUG_REMOVE && chatty) {
12686                if (r == null) {
12687                    r = new StringBuilder(256);
12688                } else {
12689                    r.append(' ');
12690                }
12691                r.append(a.info.name);
12692            }
12693        }
12694        if (r != null) {
12695            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12696        }
12697
12698        N = pkg.permissions.size();
12699        r = null;
12700        for (i=0; i<N; i++) {
12701            PackageParser.Permission p = pkg.permissions.get(i);
12702            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12703            if (bp == null) {
12704                bp = mSettings.mPermissionTrees.get(p.info.name);
12705            }
12706            if (bp != null && bp.perm == p) {
12707                bp.perm = null;
12708                if (DEBUG_REMOVE && chatty) {
12709                    if (r == null) {
12710                        r = new StringBuilder(256);
12711                    } else {
12712                        r.append(' ');
12713                    }
12714                    r.append(p.info.name);
12715                }
12716            }
12717            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12718                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12719                if (appOpPkgs != null) {
12720                    appOpPkgs.remove(pkg.packageName);
12721                }
12722            }
12723        }
12724        if (r != null) {
12725            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12726        }
12727
12728        N = pkg.requestedPermissions.size();
12729        r = null;
12730        for (i=0; i<N; i++) {
12731            String perm = pkg.requestedPermissions.get(i);
12732            BasePermission bp = mSettings.mPermissions.get(perm);
12733            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12734                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12735                if (appOpPkgs != null) {
12736                    appOpPkgs.remove(pkg.packageName);
12737                    if (appOpPkgs.isEmpty()) {
12738                        mAppOpPermissionPackages.remove(perm);
12739                    }
12740                }
12741            }
12742        }
12743        if (r != null) {
12744            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12745        }
12746
12747        N = pkg.instrumentation.size();
12748        r = null;
12749        for (i=0; i<N; i++) {
12750            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12751            mInstrumentation.remove(a.getComponentName());
12752            if (DEBUG_REMOVE && chatty) {
12753                if (r == null) {
12754                    r = new StringBuilder(256);
12755                } else {
12756                    r.append(' ');
12757                }
12758                r.append(a.info.name);
12759            }
12760        }
12761        if (r != null) {
12762            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12763        }
12764
12765        r = null;
12766        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12767            // Only system apps can hold shared libraries.
12768            if (pkg.libraryNames != null) {
12769                for (i = 0; i < pkg.libraryNames.size(); i++) {
12770                    String name = pkg.libraryNames.get(i);
12771                    if (removeSharedLibraryLPw(name, 0)) {
12772                        if (DEBUG_REMOVE && chatty) {
12773                            if (r == null) {
12774                                r = new StringBuilder(256);
12775                            } else {
12776                                r.append(' ');
12777                            }
12778                            r.append(name);
12779                        }
12780                    }
12781                }
12782            }
12783        }
12784
12785        r = null;
12786
12787        // Any package can hold static shared libraries.
12788        if (pkg.staticSharedLibName != null) {
12789            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12790                if (DEBUG_REMOVE && chatty) {
12791                    if (r == null) {
12792                        r = new StringBuilder(256);
12793                    } else {
12794                        r.append(' ');
12795                    }
12796                    r.append(pkg.staticSharedLibName);
12797                }
12798            }
12799        }
12800
12801        if (r != null) {
12802            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12803        }
12804    }
12805
12806    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12807        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12808            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12809                return true;
12810            }
12811        }
12812        return false;
12813    }
12814
12815    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12816    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12817    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12818
12819    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12820        // Update the parent permissions
12821        updatePermissionsLPw(pkg.packageName, pkg, flags);
12822        // Update the child permissions
12823        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12824        for (int i = 0; i < childCount; i++) {
12825            PackageParser.Package childPkg = pkg.childPackages.get(i);
12826            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12827        }
12828    }
12829
12830    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12831            int flags) {
12832        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12833        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12834    }
12835
12836    private void updatePermissionsLPw(String changingPkg,
12837            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12838        // Make sure there are no dangling permission trees.
12839        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12840        while (it.hasNext()) {
12841            final BasePermission bp = it.next();
12842            if (bp.packageSetting == null) {
12843                // We may not yet have parsed the package, so just see if
12844                // we still know about its settings.
12845                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12846            }
12847            if (bp.packageSetting == null) {
12848                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12849                        + " from package " + bp.sourcePackage);
12850                it.remove();
12851            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12852                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12853                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12854                            + " from package " + bp.sourcePackage);
12855                    flags |= UPDATE_PERMISSIONS_ALL;
12856                    it.remove();
12857                }
12858            }
12859        }
12860
12861        // Make sure all dynamic permissions have been assigned to a package,
12862        // and make sure there are no dangling permissions.
12863        it = mSettings.mPermissions.values().iterator();
12864        while (it.hasNext()) {
12865            final BasePermission bp = it.next();
12866            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12867                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12868                        + bp.name + " pkg=" + bp.sourcePackage
12869                        + " info=" + bp.pendingInfo);
12870                if (bp.packageSetting == null && bp.pendingInfo != null) {
12871                    final BasePermission tree = findPermissionTreeLP(bp.name);
12872                    if (tree != null && tree.perm != null) {
12873                        bp.packageSetting = tree.packageSetting;
12874                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12875                                new PermissionInfo(bp.pendingInfo));
12876                        bp.perm.info.packageName = tree.perm.info.packageName;
12877                        bp.perm.info.name = bp.name;
12878                        bp.uid = tree.uid;
12879                    }
12880                }
12881            }
12882            if (bp.packageSetting == null) {
12883                // We may not yet have parsed the package, so just see if
12884                // we still know about its settings.
12885                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12886            }
12887            if (bp.packageSetting == null) {
12888                Slog.w(TAG, "Removing dangling permission: " + bp.name
12889                        + " from package " + bp.sourcePackage);
12890                it.remove();
12891            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12892                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12893                    Slog.i(TAG, "Removing old permission: " + bp.name
12894                            + " from package " + bp.sourcePackage);
12895                    flags |= UPDATE_PERMISSIONS_ALL;
12896                    it.remove();
12897                }
12898            }
12899        }
12900
12901        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12902        // Now update the permissions for all packages, in particular
12903        // replace the granted permissions of the system packages.
12904        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12905            for (PackageParser.Package pkg : mPackages.values()) {
12906                if (pkg != pkgInfo) {
12907                    // Only replace for packages on requested volume
12908                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12909                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12910                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12911                    grantPermissionsLPw(pkg, replace, changingPkg);
12912                }
12913            }
12914        }
12915
12916        if (pkgInfo != null) {
12917            // Only replace for packages on requested volume
12918            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12919            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12920                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12921            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12922        }
12923        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12924    }
12925
12926    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12927            String packageOfInterest) {
12928        // IMPORTANT: There are two types of permissions: install and runtime.
12929        // Install time permissions are granted when the app is installed to
12930        // all device users and users added in the future. Runtime permissions
12931        // are granted at runtime explicitly to specific users. Normal and signature
12932        // protected permissions are install time permissions. Dangerous permissions
12933        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12934        // otherwise they are runtime permissions. This function does not manage
12935        // runtime permissions except for the case an app targeting Lollipop MR1
12936        // being upgraded to target a newer SDK, in which case dangerous permissions
12937        // are transformed from install time to runtime ones.
12938
12939        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12940        if (ps == null) {
12941            return;
12942        }
12943
12944        PermissionsState permissionsState = ps.getPermissionsState();
12945        PermissionsState origPermissions = permissionsState;
12946
12947        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12948
12949        boolean runtimePermissionsRevoked = false;
12950        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12951
12952        boolean changedInstallPermission = false;
12953
12954        if (replace) {
12955            ps.installPermissionsFixed = false;
12956            if (!ps.isSharedUser()) {
12957                origPermissions = new PermissionsState(permissionsState);
12958                permissionsState.reset();
12959            } else {
12960                // We need to know only about runtime permission changes since the
12961                // calling code always writes the install permissions state but
12962                // the runtime ones are written only if changed. The only cases of
12963                // changed runtime permissions here are promotion of an install to
12964                // runtime and revocation of a runtime from a shared user.
12965                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12966                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12967                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12968                    runtimePermissionsRevoked = true;
12969                }
12970            }
12971        }
12972
12973        permissionsState.setGlobalGids(mGlobalGids);
12974
12975        final int N = pkg.requestedPermissions.size();
12976        for (int i=0; i<N; i++) {
12977            final String name = pkg.requestedPermissions.get(i);
12978            final BasePermission bp = mSettings.mPermissions.get(name);
12979            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12980                    >= Build.VERSION_CODES.M;
12981
12982            if (DEBUG_INSTALL) {
12983                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12984            }
12985
12986            if (bp == null || bp.packageSetting == null) {
12987                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12988                    if (DEBUG_PERMISSIONS) {
12989                        Slog.i(TAG, "Unknown permission " + name
12990                                + " in package " + pkg.packageName);
12991                    }
12992                }
12993                continue;
12994            }
12995
12996
12997            // Limit ephemeral apps to ephemeral allowed permissions.
12998            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12999                if (DEBUG_PERMISSIONS) {
13000                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
13001                            + pkg.packageName);
13002                }
13003                continue;
13004            }
13005
13006            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
13007                if (DEBUG_PERMISSIONS) {
13008                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
13009                            + pkg.packageName);
13010                }
13011                continue;
13012            }
13013
13014            final String perm = bp.name;
13015            boolean allowedSig = false;
13016            int grant = GRANT_DENIED;
13017
13018            // Keep track of app op permissions.
13019            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
13020                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
13021                if (pkgs == null) {
13022                    pkgs = new ArraySet<>();
13023                    mAppOpPermissionPackages.put(bp.name, pkgs);
13024                }
13025                pkgs.add(pkg.packageName);
13026            }
13027
13028            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
13029            switch (level) {
13030                case PermissionInfo.PROTECTION_NORMAL: {
13031                    // For all apps normal permissions are install time ones.
13032                    grant = GRANT_INSTALL;
13033                } break;
13034
13035                case PermissionInfo.PROTECTION_DANGEROUS: {
13036                    // If a permission review is required for legacy apps we represent
13037                    // their permissions as always granted runtime ones since we need
13038                    // to keep the review required permission flag per user while an
13039                    // install permission's state is shared across all users.
13040                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
13041                        // For legacy apps dangerous permissions are install time ones.
13042                        grant = GRANT_INSTALL;
13043                    } else if (origPermissions.hasInstallPermission(bp.name)) {
13044                        // For legacy apps that became modern, install becomes runtime.
13045                        grant = GRANT_UPGRADE;
13046                    } else if (mPromoteSystemApps
13047                            && isSystemApp(ps)
13048                            && mExistingSystemPackages.contains(ps.name)) {
13049                        // For legacy system apps, install becomes runtime.
13050                        // We cannot check hasInstallPermission() for system apps since those
13051                        // permissions were granted implicitly and not persisted pre-M.
13052                        grant = GRANT_UPGRADE;
13053                    } else {
13054                        // For modern apps keep runtime permissions unchanged.
13055                        grant = GRANT_RUNTIME;
13056                    }
13057                } break;
13058
13059                case PermissionInfo.PROTECTION_SIGNATURE: {
13060                    // For all apps signature permissions are install time ones.
13061                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
13062                    if (allowedSig) {
13063                        grant = GRANT_INSTALL;
13064                    }
13065                } break;
13066            }
13067
13068            if (DEBUG_PERMISSIONS) {
13069                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
13070            }
13071
13072            if (grant != GRANT_DENIED) {
13073                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
13074                    // If this is an existing, non-system package, then
13075                    // we can't add any new permissions to it.
13076                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
13077                        // Except...  if this is a permission that was added
13078                        // to the platform (note: need to only do this when
13079                        // updating the platform).
13080                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
13081                            grant = GRANT_DENIED;
13082                        }
13083                    }
13084                }
13085
13086                switch (grant) {
13087                    case GRANT_INSTALL: {
13088                        // Revoke this as runtime permission to handle the case of
13089                        // a runtime permission being downgraded to an install one.
13090                        // Also in permission review mode we keep dangerous permissions
13091                        // for legacy apps
13092                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13093                            if (origPermissions.getRuntimePermissionState(
13094                                    bp.name, userId) != null) {
13095                                // Revoke the runtime permission and clear the flags.
13096                                origPermissions.revokeRuntimePermission(bp, userId);
13097                                origPermissions.updatePermissionFlags(bp, userId,
13098                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
13099                                // If we revoked a permission permission, we have to write.
13100                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13101                                        changedRuntimePermissionUserIds, userId);
13102                            }
13103                        }
13104                        // Grant an install permission.
13105                        if (permissionsState.grantInstallPermission(bp) !=
13106                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
13107                            changedInstallPermission = true;
13108                        }
13109                    } break;
13110
13111                    case GRANT_RUNTIME: {
13112                        // Grant previously granted runtime permissions.
13113                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13114                            PermissionState permissionState = origPermissions
13115                                    .getRuntimePermissionState(bp.name, userId);
13116                            int flags = permissionState != null
13117                                    ? permissionState.getFlags() : 0;
13118                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
13119                                // Don't propagate the permission in a permission review mode if
13120                                // the former was revoked, i.e. marked to not propagate on upgrade.
13121                                // Note that in a permission review mode install permissions are
13122                                // represented as constantly granted runtime ones since we need to
13123                                // keep a per user state associated with the permission. Also the
13124                                // revoke on upgrade flag is no longer applicable and is reset.
13125                                final boolean revokeOnUpgrade = (flags & PackageManager
13126                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
13127                                if (revokeOnUpgrade) {
13128                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13129                                    // Since we changed the flags, we have to write.
13130                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13131                                            changedRuntimePermissionUserIds, userId);
13132                                }
13133                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
13134                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
13135                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
13136                                        // If we cannot put the permission as it was,
13137                                        // we have to write.
13138                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13139                                                changedRuntimePermissionUserIds, userId);
13140                                    }
13141                                }
13142
13143                                // If the app supports runtime permissions no need for a review.
13144                                if (mPermissionReviewRequired
13145                                        && appSupportsRuntimePermissions
13146                                        && (flags & PackageManager
13147                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
13148                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
13149                                    // Since we changed the flags, we have to write.
13150                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13151                                            changedRuntimePermissionUserIds, userId);
13152                                }
13153                            } else if (mPermissionReviewRequired
13154                                    && !appSupportsRuntimePermissions) {
13155                                // For legacy apps that need a permission review, every new
13156                                // runtime permission is granted but it is pending a review.
13157                                // We also need to review only platform defined runtime
13158                                // permissions as these are the only ones the platform knows
13159                                // how to disable the API to simulate revocation as legacy
13160                                // apps don't expect to run with revoked permissions.
13161                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
13162                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
13163                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
13164                                        // We changed the flags, hence have to write.
13165                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13166                                                changedRuntimePermissionUserIds, userId);
13167                                    }
13168                                }
13169                                if (permissionsState.grantRuntimePermission(bp, userId)
13170                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13171                                    // We changed the permission, hence have to write.
13172                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13173                                            changedRuntimePermissionUserIds, userId);
13174                                }
13175                            }
13176                            // Propagate the permission flags.
13177                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
13178                        }
13179                    } break;
13180
13181                    case GRANT_UPGRADE: {
13182                        // Grant runtime permissions for a previously held install permission.
13183                        PermissionState permissionState = origPermissions
13184                                .getInstallPermissionState(bp.name);
13185                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
13186
13187                        if (origPermissions.revokeInstallPermission(bp)
13188                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13189                            // We will be transferring the permission flags, so clear them.
13190                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
13191                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
13192                            changedInstallPermission = true;
13193                        }
13194
13195                        // If the permission is not to be promoted to runtime we ignore it and
13196                        // also its other flags as they are not applicable to install permissions.
13197                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
13198                            for (int userId : currentUserIds) {
13199                                if (permissionsState.grantRuntimePermission(bp, userId) !=
13200                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13201                                    // Transfer the permission flags.
13202                                    permissionsState.updatePermissionFlags(bp, userId,
13203                                            flags, flags);
13204                                    // If we granted the permission, we have to write.
13205                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13206                                            changedRuntimePermissionUserIds, userId);
13207                                }
13208                            }
13209                        }
13210                    } break;
13211
13212                    default: {
13213                        if (packageOfInterest == null
13214                                || packageOfInterest.equals(pkg.packageName)) {
13215                            if (DEBUG_PERMISSIONS) {
13216                                Slog.i(TAG, "Not granting permission " + perm
13217                                        + " to package " + pkg.packageName
13218                                        + " because it was previously installed without");
13219                            }
13220                        }
13221                    } break;
13222                }
13223            } else {
13224                if (permissionsState.revokeInstallPermission(bp) !=
13225                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13226                    // Also drop the permission flags.
13227                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13228                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13229                    changedInstallPermission = true;
13230                    Slog.i(TAG, "Un-granting permission " + perm
13231                            + " from package " + pkg.packageName
13232                            + " (protectionLevel=" + bp.protectionLevel
13233                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13234                            + ")");
13235                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13236                    // Don't print warning for app op permissions, since it is fine for them
13237                    // not to be granted, there is a UI for the user to decide.
13238                    if (DEBUG_PERMISSIONS
13239                            && (packageOfInterest == null
13240                                    || packageOfInterest.equals(pkg.packageName))) {
13241                        Slog.i(TAG, "Not granting permission " + perm
13242                                + " to package " + pkg.packageName
13243                                + " (protectionLevel=" + bp.protectionLevel
13244                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13245                                + ")");
13246                    }
13247                }
13248            }
13249        }
13250
13251        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13252                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13253            // This is the first that we have heard about this package, so the
13254            // permissions we have now selected are fixed until explicitly
13255            // changed.
13256            ps.installPermissionsFixed = true;
13257        }
13258
13259        // Persist the runtime permissions state for users with changes. If permissions
13260        // were revoked because no app in the shared user declares them we have to
13261        // write synchronously to avoid losing runtime permissions state.
13262        for (int userId : changedRuntimePermissionUserIds) {
13263            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13264        }
13265    }
13266
13267    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13268        boolean allowed = false;
13269        final int NP = PackageParser.NEW_PERMISSIONS.length;
13270        for (int ip=0; ip<NP; ip++) {
13271            final PackageParser.NewPermissionInfo npi
13272                    = PackageParser.NEW_PERMISSIONS[ip];
13273            if (npi.name.equals(perm)
13274                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13275                allowed = true;
13276                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13277                        + pkg.packageName);
13278                break;
13279            }
13280        }
13281        return allowed;
13282    }
13283
13284    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13285            BasePermission bp, PermissionsState origPermissions) {
13286        boolean privilegedPermission = (bp.protectionLevel
13287                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13288        boolean privappPermissionsDisable =
13289                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13290        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13291        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13292        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13293                && !platformPackage && platformPermission) {
13294            final ArraySet<String> allowedPermissions = SystemConfig.getInstance()
13295                    .getPrivAppPermissions(pkg.packageName);
13296            final boolean whitelisted =
13297                    allowedPermissions != null && allowedPermissions.contains(perm);
13298            if (!whitelisted) {
13299                Slog.w(TAG, "Privileged permission " + perm + " for package "
13300                        + pkg.packageName + " - not in privapp-permissions whitelist");
13301                // Only report violations for apps on system image
13302                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13303                    // it's only a reportable violation if the permission isn't explicitly denied
13304                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
13305                            .getPrivAppDenyPermissions(pkg.packageName);
13306                    final boolean permissionViolation =
13307                            deniedPermissions == null || !deniedPermissions.contains(perm);
13308                    if (permissionViolation) {
13309                        if (mPrivappPermissionsViolations == null) {
13310                            mPrivappPermissionsViolations = new ArraySet<>();
13311                        }
13312                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13313                    } else {
13314                        return false;
13315                    }
13316                }
13317                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13318                    return false;
13319                }
13320            }
13321        }
13322        boolean allowed = (compareSignatures(
13323                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13324                        == PackageManager.SIGNATURE_MATCH)
13325                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13326                        == PackageManager.SIGNATURE_MATCH);
13327        if (!allowed && privilegedPermission) {
13328            if (isSystemApp(pkg)) {
13329                // For updated system applications, a system permission
13330                // is granted only if it had been defined by the original application.
13331                if (pkg.isUpdatedSystemApp()) {
13332                    final PackageSetting sysPs = mSettings
13333                            .getDisabledSystemPkgLPr(pkg.packageName);
13334                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13335                        // If the original was granted this permission, we take
13336                        // that grant decision as read and propagate it to the
13337                        // update.
13338                        if (sysPs.isPrivileged()) {
13339                            allowed = true;
13340                        }
13341                    } else {
13342                        // The system apk may have been updated with an older
13343                        // version of the one on the data partition, but which
13344                        // granted a new system permission that it didn't have
13345                        // before.  In this case we do want to allow the app to
13346                        // now get the new permission if the ancestral apk is
13347                        // privileged to get it.
13348                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13349                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13350                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13351                                    allowed = true;
13352                                    break;
13353                                }
13354                            }
13355                        }
13356                        // Also if a privileged parent package on the system image or any of
13357                        // its children requested a privileged permission, the updated child
13358                        // packages can also get the permission.
13359                        if (pkg.parentPackage != null) {
13360                            final PackageSetting disabledSysParentPs = mSettings
13361                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13362                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13363                                    && disabledSysParentPs.isPrivileged()) {
13364                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13365                                    allowed = true;
13366                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13367                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13368                                    for (int i = 0; i < count; i++) {
13369                                        PackageParser.Package disabledSysChildPkg =
13370                                                disabledSysParentPs.pkg.childPackages.get(i);
13371                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13372                                                perm)) {
13373                                            allowed = true;
13374                                            break;
13375                                        }
13376                                    }
13377                                }
13378                            }
13379                        }
13380                    }
13381                } else {
13382                    allowed = isPrivilegedApp(pkg);
13383                }
13384            }
13385        }
13386        if (!allowed) {
13387            if (!allowed && (bp.protectionLevel
13388                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13389                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13390                // If this was a previously normal/dangerous permission that got moved
13391                // to a system permission as part of the runtime permission redesign, then
13392                // we still want to blindly grant it to old apps.
13393                allowed = true;
13394            }
13395            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13396                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13397                // If this permission is to be granted to the system installer and
13398                // this app is an installer, then it gets the permission.
13399                allowed = true;
13400            }
13401            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13402                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13403                // If this permission is to be granted to the system verifier and
13404                // this app is a verifier, then it gets the permission.
13405                allowed = true;
13406            }
13407            if (!allowed && (bp.protectionLevel
13408                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13409                    && isSystemApp(pkg)) {
13410                // Any pre-installed system app is allowed to get this permission.
13411                allowed = true;
13412            }
13413            if (!allowed && (bp.protectionLevel
13414                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13415                // For development permissions, a development permission
13416                // is granted only if it was already granted.
13417                allowed = origPermissions.hasInstallPermission(perm);
13418            }
13419            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13420                    && pkg.packageName.equals(mSetupWizardPackage)) {
13421                // If this permission is to be granted to the system setup wizard and
13422                // this app is a setup wizard, then it gets the permission.
13423                allowed = true;
13424            }
13425        }
13426        return allowed;
13427    }
13428
13429    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13430        final int permCount = pkg.requestedPermissions.size();
13431        for (int j = 0; j < permCount; j++) {
13432            String requestedPermission = pkg.requestedPermissions.get(j);
13433            if (permission.equals(requestedPermission)) {
13434                return true;
13435            }
13436        }
13437        return false;
13438    }
13439
13440    final class ActivityIntentResolver
13441            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13442        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13443                boolean defaultOnly, int userId) {
13444            if (!sUserManager.exists(userId)) return null;
13445            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13446            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13447        }
13448
13449        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13450                int userId) {
13451            if (!sUserManager.exists(userId)) return null;
13452            mFlags = flags;
13453            return super.queryIntent(intent, resolvedType,
13454                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13455                    userId);
13456        }
13457
13458        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13459                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13460            if (!sUserManager.exists(userId)) return null;
13461            if (packageActivities == null) {
13462                return null;
13463            }
13464            mFlags = flags;
13465            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13466            final int N = packageActivities.size();
13467            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13468                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13469
13470            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13471            for (int i = 0; i < N; ++i) {
13472                intentFilters = packageActivities.get(i).intents;
13473                if (intentFilters != null && intentFilters.size() > 0) {
13474                    PackageParser.ActivityIntentInfo[] array =
13475                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13476                    intentFilters.toArray(array);
13477                    listCut.add(array);
13478                }
13479            }
13480            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13481        }
13482
13483        /**
13484         * Finds a privileged activity that matches the specified activity names.
13485         */
13486        private PackageParser.Activity findMatchingActivity(
13487                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13488            for (PackageParser.Activity sysActivity : activityList) {
13489                if (sysActivity.info.name.equals(activityInfo.name)) {
13490                    return sysActivity;
13491                }
13492                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13493                    return sysActivity;
13494                }
13495                if (sysActivity.info.targetActivity != null) {
13496                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13497                        return sysActivity;
13498                    }
13499                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13500                        return sysActivity;
13501                    }
13502                }
13503            }
13504            return null;
13505        }
13506
13507        public class IterGenerator<E> {
13508            public Iterator<E> generate(ActivityIntentInfo info) {
13509                return null;
13510            }
13511        }
13512
13513        public class ActionIterGenerator extends IterGenerator<String> {
13514            @Override
13515            public Iterator<String> generate(ActivityIntentInfo info) {
13516                return info.actionsIterator();
13517            }
13518        }
13519
13520        public class CategoriesIterGenerator extends IterGenerator<String> {
13521            @Override
13522            public Iterator<String> generate(ActivityIntentInfo info) {
13523                return info.categoriesIterator();
13524            }
13525        }
13526
13527        public class SchemesIterGenerator extends IterGenerator<String> {
13528            @Override
13529            public Iterator<String> generate(ActivityIntentInfo info) {
13530                return info.schemesIterator();
13531            }
13532        }
13533
13534        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13535            @Override
13536            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13537                return info.authoritiesIterator();
13538            }
13539        }
13540
13541        /**
13542         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13543         * MODIFIED. Do not pass in a list that should not be changed.
13544         */
13545        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13546                IterGenerator<T> generator, Iterator<T> searchIterator) {
13547            // loop through the set of actions; every one must be found in the intent filter
13548            while (searchIterator.hasNext()) {
13549                // we must have at least one filter in the list to consider a match
13550                if (intentList.size() == 0) {
13551                    break;
13552                }
13553
13554                final T searchAction = searchIterator.next();
13555
13556                // loop through the set of intent filters
13557                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13558                while (intentIter.hasNext()) {
13559                    final ActivityIntentInfo intentInfo = intentIter.next();
13560                    boolean selectionFound = false;
13561
13562                    // loop through the intent filter's selection criteria; at least one
13563                    // of them must match the searched criteria
13564                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13565                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13566                        final T intentSelection = intentSelectionIter.next();
13567                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13568                            selectionFound = true;
13569                            break;
13570                        }
13571                    }
13572
13573                    // the selection criteria wasn't found in this filter's set; this filter
13574                    // is not a potential match
13575                    if (!selectionFound) {
13576                        intentIter.remove();
13577                    }
13578                }
13579            }
13580        }
13581
13582        private boolean isProtectedAction(ActivityIntentInfo filter) {
13583            final Iterator<String> actionsIter = filter.actionsIterator();
13584            while (actionsIter != null && actionsIter.hasNext()) {
13585                final String filterAction = actionsIter.next();
13586                if (PROTECTED_ACTIONS.contains(filterAction)) {
13587                    return true;
13588                }
13589            }
13590            return false;
13591        }
13592
13593        /**
13594         * Adjusts the priority of the given intent filter according to policy.
13595         * <p>
13596         * <ul>
13597         * <li>The priority for non privileged applications is capped to '0'</li>
13598         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13599         * <li>The priority for unbundled updates to privileged applications is capped to the
13600         *      priority defined on the system partition</li>
13601         * </ul>
13602         * <p>
13603         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13604         * allowed to obtain any priority on any action.
13605         */
13606        private void adjustPriority(
13607                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13608            // nothing to do; priority is fine as-is
13609            if (intent.getPriority() <= 0) {
13610                return;
13611            }
13612
13613            final ActivityInfo activityInfo = intent.activity.info;
13614            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13615
13616            final boolean privilegedApp =
13617                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13618            if (!privilegedApp) {
13619                // non-privileged applications can never define a priority >0
13620                if (DEBUG_FILTERS) {
13621                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13622                            + " package: " + applicationInfo.packageName
13623                            + " activity: " + intent.activity.className
13624                            + " origPrio: " + intent.getPriority());
13625                }
13626                intent.setPriority(0);
13627                return;
13628            }
13629
13630            if (systemActivities == null) {
13631                // the system package is not disabled; we're parsing the system partition
13632                if (isProtectedAction(intent)) {
13633                    if (mDeferProtectedFilters) {
13634                        // We can't deal with these just yet. No component should ever obtain a
13635                        // >0 priority for a protected actions, with ONE exception -- the setup
13636                        // wizard. The setup wizard, however, cannot be known until we're able to
13637                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13638                        // until all intent filters have been processed. Chicken, meet egg.
13639                        // Let the filter temporarily have a high priority and rectify the
13640                        // priorities after all system packages have been scanned.
13641                        mProtectedFilters.add(intent);
13642                        if (DEBUG_FILTERS) {
13643                            Slog.i(TAG, "Protected action; save for later;"
13644                                    + " package: " + applicationInfo.packageName
13645                                    + " activity: " + intent.activity.className
13646                                    + " origPrio: " + intent.getPriority());
13647                        }
13648                        return;
13649                    } else {
13650                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13651                            Slog.i(TAG, "No setup wizard;"
13652                                + " All protected intents capped to priority 0");
13653                        }
13654                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13655                            if (DEBUG_FILTERS) {
13656                                Slog.i(TAG, "Found setup wizard;"
13657                                    + " allow priority " + intent.getPriority() + ";"
13658                                    + " package: " + intent.activity.info.packageName
13659                                    + " activity: " + intent.activity.className
13660                                    + " priority: " + intent.getPriority());
13661                            }
13662                            // setup wizard gets whatever it wants
13663                            return;
13664                        }
13665                        if (DEBUG_FILTERS) {
13666                            Slog.i(TAG, "Protected action; cap priority to 0;"
13667                                    + " package: " + intent.activity.info.packageName
13668                                    + " activity: " + intent.activity.className
13669                                    + " origPrio: " + intent.getPriority());
13670                        }
13671                        intent.setPriority(0);
13672                        return;
13673                    }
13674                }
13675                // privileged apps on the system image get whatever priority they request
13676                return;
13677            }
13678
13679            // privileged app unbundled update ... try to find the same activity
13680            final PackageParser.Activity foundActivity =
13681                    findMatchingActivity(systemActivities, activityInfo);
13682            if (foundActivity == null) {
13683                // this is a new activity; it cannot obtain >0 priority
13684                if (DEBUG_FILTERS) {
13685                    Slog.i(TAG, "New activity; cap priority to 0;"
13686                            + " package: " + applicationInfo.packageName
13687                            + " activity: " + intent.activity.className
13688                            + " origPrio: " + intent.getPriority());
13689                }
13690                intent.setPriority(0);
13691                return;
13692            }
13693
13694            // found activity, now check for filter equivalence
13695
13696            // a shallow copy is enough; we modify the list, not its contents
13697            final List<ActivityIntentInfo> intentListCopy =
13698                    new ArrayList<>(foundActivity.intents);
13699            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13700
13701            // find matching action subsets
13702            final Iterator<String> actionsIterator = intent.actionsIterator();
13703            if (actionsIterator != null) {
13704                getIntentListSubset(
13705                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13706                if (intentListCopy.size() == 0) {
13707                    // no more intents to match; we're not equivalent
13708                    if (DEBUG_FILTERS) {
13709                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13710                                + " package: " + applicationInfo.packageName
13711                                + " activity: " + intent.activity.className
13712                                + " origPrio: " + intent.getPriority());
13713                    }
13714                    intent.setPriority(0);
13715                    return;
13716                }
13717            }
13718
13719            // find matching category subsets
13720            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13721            if (categoriesIterator != null) {
13722                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13723                        categoriesIterator);
13724                if (intentListCopy.size() == 0) {
13725                    // no more intents to match; we're not equivalent
13726                    if (DEBUG_FILTERS) {
13727                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13728                                + " package: " + applicationInfo.packageName
13729                                + " activity: " + intent.activity.className
13730                                + " origPrio: " + intent.getPriority());
13731                    }
13732                    intent.setPriority(0);
13733                    return;
13734                }
13735            }
13736
13737            // find matching schemes subsets
13738            final Iterator<String> schemesIterator = intent.schemesIterator();
13739            if (schemesIterator != null) {
13740                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13741                        schemesIterator);
13742                if (intentListCopy.size() == 0) {
13743                    // no more intents to match; we're not equivalent
13744                    if (DEBUG_FILTERS) {
13745                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13746                                + " package: " + applicationInfo.packageName
13747                                + " activity: " + intent.activity.className
13748                                + " origPrio: " + intent.getPriority());
13749                    }
13750                    intent.setPriority(0);
13751                    return;
13752                }
13753            }
13754
13755            // find matching authorities subsets
13756            final Iterator<IntentFilter.AuthorityEntry>
13757                    authoritiesIterator = intent.authoritiesIterator();
13758            if (authoritiesIterator != null) {
13759                getIntentListSubset(intentListCopy,
13760                        new AuthoritiesIterGenerator(),
13761                        authoritiesIterator);
13762                if (intentListCopy.size() == 0) {
13763                    // no more intents to match; we're not equivalent
13764                    if (DEBUG_FILTERS) {
13765                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13766                                + " package: " + applicationInfo.packageName
13767                                + " activity: " + intent.activity.className
13768                                + " origPrio: " + intent.getPriority());
13769                    }
13770                    intent.setPriority(0);
13771                    return;
13772                }
13773            }
13774
13775            // we found matching filter(s); app gets the max priority of all intents
13776            int cappedPriority = 0;
13777            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13778                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13779            }
13780            if (intent.getPriority() > cappedPriority) {
13781                if (DEBUG_FILTERS) {
13782                    Slog.i(TAG, "Found matching filter(s);"
13783                            + " cap priority to " + cappedPriority + ";"
13784                            + " package: " + applicationInfo.packageName
13785                            + " activity: " + intent.activity.className
13786                            + " origPrio: " + intent.getPriority());
13787                }
13788                intent.setPriority(cappedPriority);
13789                return;
13790            }
13791            // all this for nothing; the requested priority was <= what was on the system
13792        }
13793
13794        public final void addActivity(PackageParser.Activity a, String type) {
13795            mActivities.put(a.getComponentName(), a);
13796            if (DEBUG_SHOW_INFO)
13797                Log.v(
13798                TAG, "  " + type + " " +
13799                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13800            if (DEBUG_SHOW_INFO)
13801                Log.v(TAG, "    Class=" + a.info.name);
13802            final int NI = a.intents.size();
13803            for (int j=0; j<NI; j++) {
13804                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13805                if ("activity".equals(type)) {
13806                    final PackageSetting ps =
13807                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13808                    final List<PackageParser.Activity> systemActivities =
13809                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13810                    adjustPriority(systemActivities, intent);
13811                }
13812                if (DEBUG_SHOW_INFO) {
13813                    Log.v(TAG, "    IntentFilter:");
13814                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13815                }
13816                if (!intent.debugCheck()) {
13817                    Log.w(TAG, "==> For Activity " + a.info.name);
13818                }
13819                addFilter(intent);
13820            }
13821        }
13822
13823        public final void removeActivity(PackageParser.Activity a, String type) {
13824            mActivities.remove(a.getComponentName());
13825            if (DEBUG_SHOW_INFO) {
13826                Log.v(TAG, "  " + type + " "
13827                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13828                                : a.info.name) + ":");
13829                Log.v(TAG, "    Class=" + a.info.name);
13830            }
13831            final int NI = a.intents.size();
13832            for (int j=0; j<NI; j++) {
13833                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13834                if (DEBUG_SHOW_INFO) {
13835                    Log.v(TAG, "    IntentFilter:");
13836                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13837                }
13838                removeFilter(intent);
13839            }
13840        }
13841
13842        @Override
13843        protected boolean allowFilterResult(
13844                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13845            ActivityInfo filterAi = filter.activity.info;
13846            for (int i=dest.size()-1; i>=0; i--) {
13847                ActivityInfo destAi = dest.get(i).activityInfo;
13848                if (destAi.name == filterAi.name
13849                        && destAi.packageName == filterAi.packageName) {
13850                    return false;
13851                }
13852            }
13853            return true;
13854        }
13855
13856        @Override
13857        protected ActivityIntentInfo[] newArray(int size) {
13858            return new ActivityIntentInfo[size];
13859        }
13860
13861        @Override
13862        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13863            if (!sUserManager.exists(userId)) return true;
13864            PackageParser.Package p = filter.activity.owner;
13865            if (p != null) {
13866                PackageSetting ps = (PackageSetting)p.mExtras;
13867                if (ps != null) {
13868                    // System apps are never considered stopped for purposes of
13869                    // filtering, because there may be no way for the user to
13870                    // actually re-launch them.
13871                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13872                            && ps.getStopped(userId);
13873                }
13874            }
13875            return false;
13876        }
13877
13878        @Override
13879        protected boolean isPackageForFilter(String packageName,
13880                PackageParser.ActivityIntentInfo info) {
13881            return packageName.equals(info.activity.owner.packageName);
13882        }
13883
13884        @Override
13885        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13886                int match, int userId) {
13887            if (!sUserManager.exists(userId)) return null;
13888            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13889                return null;
13890            }
13891            final PackageParser.Activity activity = info.activity;
13892            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13893            if (ps == null) {
13894                return null;
13895            }
13896            final PackageUserState userState = ps.readUserState(userId);
13897            ActivityInfo ai =
13898                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13899            if (ai == null) {
13900                return null;
13901            }
13902            final boolean matchExplicitlyVisibleOnly =
13903                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13904            final boolean matchVisibleToInstantApp =
13905                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13906            final boolean componentVisible =
13907                    matchVisibleToInstantApp
13908                    && info.isVisibleToInstantApp()
13909                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13910            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13911            // throw out filters that aren't visible to ephemeral apps
13912            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13913                return null;
13914            }
13915            // throw out instant app filters if we're not explicitly requesting them
13916            if (!matchInstantApp && userState.instantApp) {
13917                return null;
13918            }
13919            // throw out instant app filters if updates are available; will trigger
13920            // instant app resolution
13921            if (userState.instantApp && ps.isUpdateAvailable()) {
13922                return null;
13923            }
13924            final ResolveInfo res = new ResolveInfo();
13925            res.activityInfo = ai;
13926            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13927                res.filter = info;
13928            }
13929            if (info != null) {
13930                res.handleAllWebDataURI = info.handleAllWebDataURI();
13931            }
13932            res.priority = info.getPriority();
13933            res.preferredOrder = activity.owner.mPreferredOrder;
13934            //System.out.println("Result: " + res.activityInfo.className +
13935            //                   " = " + res.priority);
13936            res.match = match;
13937            res.isDefault = info.hasDefault;
13938            res.labelRes = info.labelRes;
13939            res.nonLocalizedLabel = info.nonLocalizedLabel;
13940            if (userNeedsBadging(userId)) {
13941                res.noResourceId = true;
13942            } else {
13943                res.icon = info.icon;
13944            }
13945            res.iconResourceId = info.icon;
13946            res.system = res.activityInfo.applicationInfo.isSystemApp();
13947            res.isInstantAppAvailable = userState.instantApp;
13948            return res;
13949        }
13950
13951        @Override
13952        protected void sortResults(List<ResolveInfo> results) {
13953            Collections.sort(results, mResolvePrioritySorter);
13954        }
13955
13956        @Override
13957        protected void dumpFilter(PrintWriter out, String prefix,
13958                PackageParser.ActivityIntentInfo filter) {
13959            out.print(prefix); out.print(
13960                    Integer.toHexString(System.identityHashCode(filter.activity)));
13961                    out.print(' ');
13962                    filter.activity.printComponentShortName(out);
13963                    out.print(" filter ");
13964                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13965        }
13966
13967        @Override
13968        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13969            return filter.activity;
13970        }
13971
13972        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13973            PackageParser.Activity activity = (PackageParser.Activity)label;
13974            out.print(prefix); out.print(
13975                    Integer.toHexString(System.identityHashCode(activity)));
13976                    out.print(' ');
13977                    activity.printComponentShortName(out);
13978            if (count > 1) {
13979                out.print(" ("); out.print(count); out.print(" filters)");
13980            }
13981            out.println();
13982        }
13983
13984        // Keys are String (activity class name), values are Activity.
13985        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13986                = new ArrayMap<ComponentName, PackageParser.Activity>();
13987        private int mFlags;
13988    }
13989
13990    private final class ServiceIntentResolver
13991            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13992        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13993                boolean defaultOnly, int userId) {
13994            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13995            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13996        }
13997
13998        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13999                int userId) {
14000            if (!sUserManager.exists(userId)) return null;
14001            mFlags = flags;
14002            return super.queryIntent(intent, resolvedType,
14003                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14004                    userId);
14005        }
14006
14007        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14008                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
14009            if (!sUserManager.exists(userId)) return null;
14010            if (packageServices == null) {
14011                return null;
14012            }
14013            mFlags = flags;
14014            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
14015            final int N = packageServices.size();
14016            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
14017                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
14018
14019            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
14020            for (int i = 0; i < N; ++i) {
14021                intentFilters = packageServices.get(i).intents;
14022                if (intentFilters != null && intentFilters.size() > 0) {
14023                    PackageParser.ServiceIntentInfo[] array =
14024                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
14025                    intentFilters.toArray(array);
14026                    listCut.add(array);
14027                }
14028            }
14029            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14030        }
14031
14032        public final void addService(PackageParser.Service s) {
14033            mServices.put(s.getComponentName(), s);
14034            if (DEBUG_SHOW_INFO) {
14035                Log.v(TAG, "  "
14036                        + (s.info.nonLocalizedLabel != null
14037                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14038                Log.v(TAG, "    Class=" + s.info.name);
14039            }
14040            final int NI = s.intents.size();
14041            int j;
14042            for (j=0; j<NI; j++) {
14043                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14044                if (DEBUG_SHOW_INFO) {
14045                    Log.v(TAG, "    IntentFilter:");
14046                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14047                }
14048                if (!intent.debugCheck()) {
14049                    Log.w(TAG, "==> For Service " + s.info.name);
14050                }
14051                addFilter(intent);
14052            }
14053        }
14054
14055        public final void removeService(PackageParser.Service s) {
14056            mServices.remove(s.getComponentName());
14057            if (DEBUG_SHOW_INFO) {
14058                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
14059                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14060                Log.v(TAG, "    Class=" + s.info.name);
14061            }
14062            final int NI = s.intents.size();
14063            int j;
14064            for (j=0; j<NI; j++) {
14065                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14066                if (DEBUG_SHOW_INFO) {
14067                    Log.v(TAG, "    IntentFilter:");
14068                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14069                }
14070                removeFilter(intent);
14071            }
14072        }
14073
14074        @Override
14075        protected boolean allowFilterResult(
14076                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
14077            ServiceInfo filterSi = filter.service.info;
14078            for (int i=dest.size()-1; i>=0; i--) {
14079                ServiceInfo destAi = dest.get(i).serviceInfo;
14080                if (destAi.name == filterSi.name
14081                        && destAi.packageName == filterSi.packageName) {
14082                    return false;
14083                }
14084            }
14085            return true;
14086        }
14087
14088        @Override
14089        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
14090            return new PackageParser.ServiceIntentInfo[size];
14091        }
14092
14093        @Override
14094        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
14095            if (!sUserManager.exists(userId)) return true;
14096            PackageParser.Package p = filter.service.owner;
14097            if (p != null) {
14098                PackageSetting ps = (PackageSetting)p.mExtras;
14099                if (ps != null) {
14100                    // System apps are never considered stopped for purposes of
14101                    // filtering, because there may be no way for the user to
14102                    // actually re-launch them.
14103                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14104                            && ps.getStopped(userId);
14105                }
14106            }
14107            return false;
14108        }
14109
14110        @Override
14111        protected boolean isPackageForFilter(String packageName,
14112                PackageParser.ServiceIntentInfo info) {
14113            return packageName.equals(info.service.owner.packageName);
14114        }
14115
14116        @Override
14117        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
14118                int match, int userId) {
14119            if (!sUserManager.exists(userId)) return null;
14120            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
14121            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
14122                return null;
14123            }
14124            final PackageParser.Service service = info.service;
14125            PackageSetting ps = (PackageSetting) service.owner.mExtras;
14126            if (ps == null) {
14127                return null;
14128            }
14129            final PackageUserState userState = ps.readUserState(userId);
14130            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
14131                    userState, userId);
14132            if (si == null) {
14133                return null;
14134            }
14135            final boolean matchVisibleToInstantApp =
14136                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14137            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14138            // throw out filters that aren't visible to ephemeral apps
14139            if (matchVisibleToInstantApp
14140                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14141                return null;
14142            }
14143            // throw out ephemeral filters if we're not explicitly requesting them
14144            if (!isInstantApp && userState.instantApp) {
14145                return null;
14146            }
14147            // throw out instant app filters if updates are available; will trigger
14148            // instant app resolution
14149            if (userState.instantApp && ps.isUpdateAvailable()) {
14150                return null;
14151            }
14152            final ResolveInfo res = new ResolveInfo();
14153            res.serviceInfo = si;
14154            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
14155                res.filter = filter;
14156            }
14157            res.priority = info.getPriority();
14158            res.preferredOrder = service.owner.mPreferredOrder;
14159            res.match = match;
14160            res.isDefault = info.hasDefault;
14161            res.labelRes = info.labelRes;
14162            res.nonLocalizedLabel = info.nonLocalizedLabel;
14163            res.icon = info.icon;
14164            res.system = res.serviceInfo.applicationInfo.isSystemApp();
14165            return res;
14166        }
14167
14168        @Override
14169        protected void sortResults(List<ResolveInfo> results) {
14170            Collections.sort(results, mResolvePrioritySorter);
14171        }
14172
14173        @Override
14174        protected void dumpFilter(PrintWriter out, String prefix,
14175                PackageParser.ServiceIntentInfo filter) {
14176            out.print(prefix); out.print(
14177                    Integer.toHexString(System.identityHashCode(filter.service)));
14178                    out.print(' ');
14179                    filter.service.printComponentShortName(out);
14180                    out.print(" filter ");
14181                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14182        }
14183
14184        @Override
14185        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14186            return filter.service;
14187        }
14188
14189        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14190            PackageParser.Service service = (PackageParser.Service)label;
14191            out.print(prefix); out.print(
14192                    Integer.toHexString(System.identityHashCode(service)));
14193                    out.print(' ');
14194                    service.printComponentShortName(out);
14195            if (count > 1) {
14196                out.print(" ("); out.print(count); out.print(" filters)");
14197            }
14198            out.println();
14199        }
14200
14201//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14202//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14203//            final List<ResolveInfo> retList = Lists.newArrayList();
14204//            while (i.hasNext()) {
14205//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14206//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14207//                    retList.add(resolveInfo);
14208//                }
14209//            }
14210//            return retList;
14211//        }
14212
14213        // Keys are String (activity class name), values are Activity.
14214        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14215                = new ArrayMap<ComponentName, PackageParser.Service>();
14216        private int mFlags;
14217    }
14218
14219    private final class ProviderIntentResolver
14220            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14221        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14222                boolean defaultOnly, int userId) {
14223            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14224            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14225        }
14226
14227        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14228                int userId) {
14229            if (!sUserManager.exists(userId))
14230                return null;
14231            mFlags = flags;
14232            return super.queryIntent(intent, resolvedType,
14233                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14234                    userId);
14235        }
14236
14237        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14238                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14239            if (!sUserManager.exists(userId))
14240                return null;
14241            if (packageProviders == null) {
14242                return null;
14243            }
14244            mFlags = flags;
14245            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14246            final int N = packageProviders.size();
14247            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14248                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14249
14250            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14251            for (int i = 0; i < N; ++i) {
14252                intentFilters = packageProviders.get(i).intents;
14253                if (intentFilters != null && intentFilters.size() > 0) {
14254                    PackageParser.ProviderIntentInfo[] array =
14255                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14256                    intentFilters.toArray(array);
14257                    listCut.add(array);
14258                }
14259            }
14260            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14261        }
14262
14263        public final void addProvider(PackageParser.Provider p) {
14264            if (mProviders.containsKey(p.getComponentName())) {
14265                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14266                return;
14267            }
14268
14269            mProviders.put(p.getComponentName(), p);
14270            if (DEBUG_SHOW_INFO) {
14271                Log.v(TAG, "  "
14272                        + (p.info.nonLocalizedLabel != null
14273                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14274                Log.v(TAG, "    Class=" + p.info.name);
14275            }
14276            final int NI = p.intents.size();
14277            int j;
14278            for (j = 0; j < NI; j++) {
14279                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14280                if (DEBUG_SHOW_INFO) {
14281                    Log.v(TAG, "    IntentFilter:");
14282                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14283                }
14284                if (!intent.debugCheck()) {
14285                    Log.w(TAG, "==> For Provider " + p.info.name);
14286                }
14287                addFilter(intent);
14288            }
14289        }
14290
14291        public final void removeProvider(PackageParser.Provider p) {
14292            mProviders.remove(p.getComponentName());
14293            if (DEBUG_SHOW_INFO) {
14294                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14295                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14296                Log.v(TAG, "    Class=" + p.info.name);
14297            }
14298            final int NI = p.intents.size();
14299            int j;
14300            for (j = 0; j < NI; j++) {
14301                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14302                if (DEBUG_SHOW_INFO) {
14303                    Log.v(TAG, "    IntentFilter:");
14304                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14305                }
14306                removeFilter(intent);
14307            }
14308        }
14309
14310        @Override
14311        protected boolean allowFilterResult(
14312                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14313            ProviderInfo filterPi = filter.provider.info;
14314            for (int i = dest.size() - 1; i >= 0; i--) {
14315                ProviderInfo destPi = dest.get(i).providerInfo;
14316                if (destPi.name == filterPi.name
14317                        && destPi.packageName == filterPi.packageName) {
14318                    return false;
14319                }
14320            }
14321            return true;
14322        }
14323
14324        @Override
14325        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14326            return new PackageParser.ProviderIntentInfo[size];
14327        }
14328
14329        @Override
14330        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14331            if (!sUserManager.exists(userId))
14332                return true;
14333            PackageParser.Package p = filter.provider.owner;
14334            if (p != null) {
14335                PackageSetting ps = (PackageSetting) p.mExtras;
14336                if (ps != null) {
14337                    // System apps are never considered stopped for purposes of
14338                    // filtering, because there may be no way for the user to
14339                    // actually re-launch them.
14340                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14341                            && ps.getStopped(userId);
14342                }
14343            }
14344            return false;
14345        }
14346
14347        @Override
14348        protected boolean isPackageForFilter(String packageName,
14349                PackageParser.ProviderIntentInfo info) {
14350            return packageName.equals(info.provider.owner.packageName);
14351        }
14352
14353        @Override
14354        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14355                int match, int userId) {
14356            if (!sUserManager.exists(userId))
14357                return null;
14358            final PackageParser.ProviderIntentInfo info = filter;
14359            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14360                return null;
14361            }
14362            final PackageParser.Provider provider = info.provider;
14363            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14364            if (ps == null) {
14365                return null;
14366            }
14367            final PackageUserState userState = ps.readUserState(userId);
14368            final boolean matchVisibleToInstantApp =
14369                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14370            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14371            // throw out filters that aren't visible to instant applications
14372            if (matchVisibleToInstantApp
14373                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14374                return null;
14375            }
14376            // throw out instant application filters if we're not explicitly requesting them
14377            if (!isInstantApp && userState.instantApp) {
14378                return null;
14379            }
14380            // throw out instant application filters if updates are available; will trigger
14381            // instant application resolution
14382            if (userState.instantApp && ps.isUpdateAvailable()) {
14383                return null;
14384            }
14385            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14386                    userState, userId);
14387            if (pi == null) {
14388                return null;
14389            }
14390            final ResolveInfo res = new ResolveInfo();
14391            res.providerInfo = pi;
14392            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14393                res.filter = filter;
14394            }
14395            res.priority = info.getPriority();
14396            res.preferredOrder = provider.owner.mPreferredOrder;
14397            res.match = match;
14398            res.isDefault = info.hasDefault;
14399            res.labelRes = info.labelRes;
14400            res.nonLocalizedLabel = info.nonLocalizedLabel;
14401            res.icon = info.icon;
14402            res.system = res.providerInfo.applicationInfo.isSystemApp();
14403            return res;
14404        }
14405
14406        @Override
14407        protected void sortResults(List<ResolveInfo> results) {
14408            Collections.sort(results, mResolvePrioritySorter);
14409        }
14410
14411        @Override
14412        protected void dumpFilter(PrintWriter out, String prefix,
14413                PackageParser.ProviderIntentInfo filter) {
14414            out.print(prefix);
14415            out.print(
14416                    Integer.toHexString(System.identityHashCode(filter.provider)));
14417            out.print(' ');
14418            filter.provider.printComponentShortName(out);
14419            out.print(" filter ");
14420            out.println(Integer.toHexString(System.identityHashCode(filter)));
14421        }
14422
14423        @Override
14424        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14425            return filter.provider;
14426        }
14427
14428        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14429            PackageParser.Provider provider = (PackageParser.Provider)label;
14430            out.print(prefix); out.print(
14431                    Integer.toHexString(System.identityHashCode(provider)));
14432                    out.print(' ');
14433                    provider.printComponentShortName(out);
14434            if (count > 1) {
14435                out.print(" ("); out.print(count); out.print(" filters)");
14436            }
14437            out.println();
14438        }
14439
14440        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14441                = new ArrayMap<ComponentName, PackageParser.Provider>();
14442        private int mFlags;
14443    }
14444
14445    static final class EphemeralIntentResolver
14446            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14447        /**
14448         * The result that has the highest defined order. Ordering applies on a
14449         * per-package basis. Mapping is from package name to Pair of order and
14450         * EphemeralResolveInfo.
14451         * <p>
14452         * NOTE: This is implemented as a field variable for convenience and efficiency.
14453         * By having a field variable, we're able to track filter ordering as soon as
14454         * a non-zero order is defined. Otherwise, multiple loops across the result set
14455         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14456         * this needs to be contained entirely within {@link #filterResults}.
14457         */
14458        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14459
14460        @Override
14461        protected AuxiliaryResolveInfo[] newArray(int size) {
14462            return new AuxiliaryResolveInfo[size];
14463        }
14464
14465        @Override
14466        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14467            return true;
14468        }
14469
14470        @Override
14471        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14472                int userId) {
14473            if (!sUserManager.exists(userId)) {
14474                return null;
14475            }
14476            final String packageName = responseObj.resolveInfo.getPackageName();
14477            final Integer order = responseObj.getOrder();
14478            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14479                    mOrderResult.get(packageName);
14480            // ordering is enabled and this item's order isn't high enough
14481            if (lastOrderResult != null && lastOrderResult.first >= order) {
14482                return null;
14483            }
14484            final InstantAppResolveInfo res = responseObj.resolveInfo;
14485            if (order > 0) {
14486                // non-zero order, enable ordering
14487                mOrderResult.put(packageName, new Pair<>(order, res));
14488            }
14489            return responseObj;
14490        }
14491
14492        @Override
14493        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14494            // only do work if ordering is enabled [most of the time it won't be]
14495            if (mOrderResult.size() == 0) {
14496                return;
14497            }
14498            int resultSize = results.size();
14499            for (int i = 0; i < resultSize; i++) {
14500                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14501                final String packageName = info.getPackageName();
14502                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14503                if (savedInfo == null) {
14504                    // package doesn't having ordering
14505                    continue;
14506                }
14507                if (savedInfo.second == info) {
14508                    // circled back to the highest ordered item; remove from order list
14509                    mOrderResult.remove(packageName);
14510                    if (mOrderResult.size() == 0) {
14511                        // no more ordered items
14512                        break;
14513                    }
14514                    continue;
14515                }
14516                // item has a worse order, remove it from the result list
14517                results.remove(i);
14518                resultSize--;
14519                i--;
14520            }
14521        }
14522    }
14523
14524    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14525            new Comparator<ResolveInfo>() {
14526        public int compare(ResolveInfo r1, ResolveInfo r2) {
14527            int v1 = r1.priority;
14528            int v2 = r2.priority;
14529            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14530            if (v1 != v2) {
14531                return (v1 > v2) ? -1 : 1;
14532            }
14533            v1 = r1.preferredOrder;
14534            v2 = r2.preferredOrder;
14535            if (v1 != v2) {
14536                return (v1 > v2) ? -1 : 1;
14537            }
14538            if (r1.isDefault != r2.isDefault) {
14539                return r1.isDefault ? -1 : 1;
14540            }
14541            v1 = r1.match;
14542            v2 = r2.match;
14543            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14544            if (v1 != v2) {
14545                return (v1 > v2) ? -1 : 1;
14546            }
14547            if (r1.system != r2.system) {
14548                return r1.system ? -1 : 1;
14549            }
14550            if (r1.activityInfo != null) {
14551                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14552            }
14553            if (r1.serviceInfo != null) {
14554                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14555            }
14556            if (r1.providerInfo != null) {
14557                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14558            }
14559            return 0;
14560        }
14561    };
14562
14563    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14564            new Comparator<ProviderInfo>() {
14565        public int compare(ProviderInfo p1, ProviderInfo p2) {
14566            final int v1 = p1.initOrder;
14567            final int v2 = p2.initOrder;
14568            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14569        }
14570    };
14571
14572    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14573            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14574            final int[] userIds) {
14575        mHandler.post(new Runnable() {
14576            @Override
14577            public void run() {
14578                try {
14579                    final IActivityManager am = ActivityManager.getService();
14580                    if (am == null) return;
14581                    final int[] resolvedUserIds;
14582                    if (userIds == null) {
14583                        resolvedUserIds = am.getRunningUserIds();
14584                    } else {
14585                        resolvedUserIds = userIds;
14586                    }
14587                    for (int id : resolvedUserIds) {
14588                        final Intent intent = new Intent(action,
14589                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14590                        if (extras != null) {
14591                            intent.putExtras(extras);
14592                        }
14593                        if (targetPkg != null) {
14594                            intent.setPackage(targetPkg);
14595                        }
14596                        // Modify the UID when posting to other users
14597                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14598                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14599                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14600                            intent.putExtra(Intent.EXTRA_UID, uid);
14601                        }
14602                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14603                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14604                        if (DEBUG_BROADCASTS) {
14605                            RuntimeException here = new RuntimeException("here");
14606                            here.fillInStackTrace();
14607                            Slog.d(TAG, "Sending to user " + id + ": "
14608                                    + intent.toShortString(false, true, false, false)
14609                                    + " " + intent.getExtras(), here);
14610                        }
14611                        am.broadcastIntent(null, intent, null, finishedReceiver,
14612                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14613                                null, finishedReceiver != null, false, id);
14614                    }
14615                } catch (RemoteException ex) {
14616                }
14617            }
14618        });
14619    }
14620
14621    /**
14622     * Check if the external storage media is available. This is true if there
14623     * is a mounted external storage medium or if the external storage is
14624     * emulated.
14625     */
14626    private boolean isExternalMediaAvailable() {
14627        return mMediaMounted || Environment.isExternalStorageEmulated();
14628    }
14629
14630    @Override
14631    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14632        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14633            return null;
14634        }
14635        if (!isExternalMediaAvailable()) {
14636                // If the external storage is no longer mounted at this point,
14637                // the caller may not have been able to delete all of this
14638                // packages files and can not delete any more.  Bail.
14639            return null;
14640        }
14641        synchronized (mPackages) {
14642            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14643            if (lastPackage != null) {
14644                pkgs.remove(lastPackage);
14645            }
14646            if (pkgs.size() > 0) {
14647                return pkgs.get(0);
14648            }
14649        }
14650        return null;
14651    }
14652
14653    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14654        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14655                userId, andCode ? 1 : 0, packageName);
14656        if (mSystemReady) {
14657            msg.sendToTarget();
14658        } else {
14659            if (mPostSystemReadyMessages == null) {
14660                mPostSystemReadyMessages = new ArrayList<>();
14661            }
14662            mPostSystemReadyMessages.add(msg);
14663        }
14664    }
14665
14666    void startCleaningPackages() {
14667        // reader
14668        if (!isExternalMediaAvailable()) {
14669            return;
14670        }
14671        synchronized (mPackages) {
14672            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14673                return;
14674            }
14675        }
14676        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14677        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14678        IActivityManager am = ActivityManager.getService();
14679        if (am != null) {
14680            int dcsUid = -1;
14681            synchronized (mPackages) {
14682                if (!mDefaultContainerWhitelisted) {
14683                    mDefaultContainerWhitelisted = true;
14684                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14685                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14686                }
14687            }
14688            try {
14689                if (dcsUid > 0) {
14690                    am.backgroundWhitelistUid(dcsUid);
14691                }
14692                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14693                        UserHandle.USER_SYSTEM);
14694            } catch (RemoteException e) {
14695            }
14696        }
14697    }
14698
14699    @Override
14700    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14701            int installFlags, String installerPackageName, int userId) {
14702        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14703
14704        final int callingUid = Binder.getCallingUid();
14705        enforceCrossUserPermission(callingUid, userId,
14706                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14707
14708        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14709            try {
14710                if (observer != null) {
14711                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14712                }
14713            } catch (RemoteException re) {
14714            }
14715            return;
14716        }
14717
14718        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14719            installFlags |= PackageManager.INSTALL_FROM_ADB;
14720
14721        } else {
14722            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14723            // about installerPackageName.
14724
14725            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14726            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14727        }
14728
14729        UserHandle user;
14730        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14731            user = UserHandle.ALL;
14732        } else {
14733            user = new UserHandle(userId);
14734        }
14735
14736        // Only system components can circumvent runtime permissions when installing.
14737        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14738                && mContext.checkCallingOrSelfPermission(Manifest.permission
14739                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14740            throw new SecurityException("You need the "
14741                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14742                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14743        }
14744
14745        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14746                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14747            throw new IllegalArgumentException(
14748                    "New installs into ASEC containers no longer supported");
14749        }
14750
14751        final File originFile = new File(originPath);
14752        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14753
14754        final Message msg = mHandler.obtainMessage(INIT_COPY);
14755        final VerificationInfo verificationInfo = new VerificationInfo(
14756                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14757        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14758                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14759                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14760                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14761        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14762        msg.obj = params;
14763
14764        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14765                System.identityHashCode(msg.obj));
14766        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14767                System.identityHashCode(msg.obj));
14768
14769        mHandler.sendMessage(msg);
14770    }
14771
14772
14773    /**
14774     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14775     * it is acting on behalf on an enterprise or the user).
14776     *
14777     * Note that the ordering of the conditionals in this method is important. The checks we perform
14778     * are as follows, in this order:
14779     *
14780     * 1) If the install is being performed by a system app, we can trust the app to have set the
14781     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14782     *    what it is.
14783     * 2) If the install is being performed by a device or profile owner app, the install reason
14784     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14785     *    set the install reason correctly. If the app targets an older SDK version where install
14786     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14787     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14788     * 3) In all other cases, the install is being performed by a regular app that is neither part
14789     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14790     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14791     *    set to enterprise policy and if so, change it to unknown instead.
14792     */
14793    private int fixUpInstallReason(String installerPackageName, int installerUid,
14794            int installReason) {
14795        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14796                == PERMISSION_GRANTED) {
14797            // If the install is being performed by a system app, we trust that app to have set the
14798            // install reason correctly.
14799            return installReason;
14800        }
14801
14802        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14803            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14804        if (dpm != null) {
14805            ComponentName owner = null;
14806            try {
14807                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14808                if (owner == null) {
14809                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14810                }
14811            } catch (RemoteException e) {
14812            }
14813            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14814                // If the install is being performed by a device or profile owner, the install
14815                // reason should be enterprise policy.
14816                return PackageManager.INSTALL_REASON_POLICY;
14817            }
14818        }
14819
14820        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14821            // If the install is being performed by a regular app (i.e. neither system app nor
14822            // device or profile owner), we have no reason to believe that the app is acting on
14823            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14824            // change it to unknown instead.
14825            return PackageManager.INSTALL_REASON_UNKNOWN;
14826        }
14827
14828        // If the install is being performed by a regular app and the install reason was set to any
14829        // value but enterprise policy, leave the install reason unchanged.
14830        return installReason;
14831    }
14832
14833    void installStage(String packageName, File stagedDir, String stagedCid,
14834            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14835            String installerPackageName, int installerUid, UserHandle user,
14836            Certificate[][] certificates) {
14837        if (DEBUG_EPHEMERAL) {
14838            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14839                Slog.d(TAG, "Ephemeral install of " + packageName);
14840            }
14841        }
14842        final VerificationInfo verificationInfo = new VerificationInfo(
14843                sessionParams.originatingUri, sessionParams.referrerUri,
14844                sessionParams.originatingUid, installerUid);
14845
14846        final OriginInfo origin;
14847        if (stagedDir != null) {
14848            origin = OriginInfo.fromStagedFile(stagedDir);
14849        } else {
14850            origin = OriginInfo.fromStagedContainer(stagedCid);
14851        }
14852
14853        final Message msg = mHandler.obtainMessage(INIT_COPY);
14854        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14855                sessionParams.installReason);
14856        final InstallParams params = new InstallParams(origin, null, observer,
14857                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14858                verificationInfo, user, sessionParams.abiOverride,
14859                sessionParams.grantedRuntimePermissions, certificates, installReason);
14860        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14861        msg.obj = params;
14862
14863        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14864                System.identityHashCode(msg.obj));
14865        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14866                System.identityHashCode(msg.obj));
14867
14868        mHandler.sendMessage(msg);
14869    }
14870
14871    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14872            int userId) {
14873        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14874        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14875                false /*startReceiver*/, pkgSetting.appId, userId);
14876
14877        // Send a session commit broadcast
14878        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14879        info.installReason = pkgSetting.getInstallReason(userId);
14880        info.appPackageName = packageName;
14881        sendSessionCommitBroadcast(info, userId);
14882    }
14883
14884    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14885            boolean includeStopped, int appId, int... userIds) {
14886        if (ArrayUtils.isEmpty(userIds)) {
14887            return;
14888        }
14889        Bundle extras = new Bundle(1);
14890        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14891        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14892
14893        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14894                packageName, extras, 0, null, null, userIds);
14895        if (sendBootCompleted) {
14896            mHandler.post(() -> {
14897                        for (int userId : userIds) {
14898                            sendBootCompletedBroadcastToSystemApp(
14899                                    packageName, includeStopped, userId);
14900                        }
14901                    }
14902            );
14903        }
14904    }
14905
14906    /**
14907     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14908     * automatically without needing an explicit launch.
14909     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14910     */
14911    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14912            int userId) {
14913        // If user is not running, the app didn't miss any broadcast
14914        if (!mUserManagerInternal.isUserRunning(userId)) {
14915            return;
14916        }
14917        final IActivityManager am = ActivityManager.getService();
14918        try {
14919            // Deliver LOCKED_BOOT_COMPLETED first
14920            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14921                    .setPackage(packageName);
14922            if (includeStopped) {
14923                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14924            }
14925            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14926            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14927                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14928
14929            // Deliver BOOT_COMPLETED only if user is unlocked
14930            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14931                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14932                if (includeStopped) {
14933                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14934                }
14935                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14936                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14937            }
14938        } catch (RemoteException e) {
14939            throw e.rethrowFromSystemServer();
14940        }
14941    }
14942
14943    @Override
14944    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14945            int userId) {
14946        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14947        PackageSetting pkgSetting;
14948        final int callingUid = Binder.getCallingUid();
14949        enforceCrossUserPermission(callingUid, userId,
14950                true /* requireFullPermission */, true /* checkShell */,
14951                "setApplicationHiddenSetting for user " + userId);
14952
14953        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14954            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14955            return false;
14956        }
14957
14958        long callingId = Binder.clearCallingIdentity();
14959        try {
14960            boolean sendAdded = false;
14961            boolean sendRemoved = false;
14962            // writer
14963            synchronized (mPackages) {
14964                pkgSetting = mSettings.mPackages.get(packageName);
14965                if (pkgSetting == null) {
14966                    return false;
14967                }
14968                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14969                    return false;
14970                }
14971                // Do not allow "android" is being disabled
14972                if ("android".equals(packageName)) {
14973                    Slog.w(TAG, "Cannot hide package: android");
14974                    return false;
14975                }
14976                // Cannot hide static shared libs as they are considered
14977                // a part of the using app (emulating static linking). Also
14978                // static libs are installed always on internal storage.
14979                PackageParser.Package pkg = mPackages.get(packageName);
14980                if (pkg != null && pkg.staticSharedLibName != null) {
14981                    Slog.w(TAG, "Cannot hide package: " + packageName
14982                            + " providing static shared library: "
14983                            + pkg.staticSharedLibName);
14984                    return false;
14985                }
14986                // Only allow protected packages to hide themselves.
14987                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14988                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14989                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14990                    return false;
14991                }
14992
14993                if (pkgSetting.getHidden(userId) != hidden) {
14994                    pkgSetting.setHidden(hidden, userId);
14995                    mSettings.writePackageRestrictionsLPr(userId);
14996                    if (hidden) {
14997                        sendRemoved = true;
14998                    } else {
14999                        sendAdded = true;
15000                    }
15001                }
15002            }
15003            if (sendAdded) {
15004                sendPackageAddedForUser(packageName, pkgSetting, userId);
15005                return true;
15006            }
15007            if (sendRemoved) {
15008                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
15009                        "hiding pkg");
15010                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
15011                return true;
15012            }
15013        } finally {
15014            Binder.restoreCallingIdentity(callingId);
15015        }
15016        return false;
15017    }
15018
15019    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
15020            int userId) {
15021        final PackageRemovedInfo info = new PackageRemovedInfo(this);
15022        info.removedPackage = packageName;
15023        info.installerPackageName = pkgSetting.installerPackageName;
15024        info.removedUsers = new int[] {userId};
15025        info.broadcastUsers = new int[] {userId};
15026        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
15027        info.sendPackageRemovedBroadcasts(true /*killApp*/);
15028    }
15029
15030    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
15031        if (pkgList.length > 0) {
15032            Bundle extras = new Bundle(1);
15033            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15034
15035            sendPackageBroadcast(
15036                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
15037                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
15038                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
15039                    new int[] {userId});
15040        }
15041    }
15042
15043    /**
15044     * Returns true if application is not found or there was an error. Otherwise it returns
15045     * the hidden state of the package for the given user.
15046     */
15047    @Override
15048    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
15049        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15050        final int callingUid = Binder.getCallingUid();
15051        enforceCrossUserPermission(callingUid, userId,
15052                true /* requireFullPermission */, false /* checkShell */,
15053                "getApplicationHidden for user " + userId);
15054        PackageSetting ps;
15055        long callingId = Binder.clearCallingIdentity();
15056        try {
15057            // writer
15058            synchronized (mPackages) {
15059                ps = mSettings.mPackages.get(packageName);
15060                if (ps == null) {
15061                    return true;
15062                }
15063                if (filterAppAccessLPr(ps, callingUid, userId)) {
15064                    return true;
15065                }
15066                return ps.getHidden(userId);
15067            }
15068        } finally {
15069            Binder.restoreCallingIdentity(callingId);
15070        }
15071    }
15072
15073    /**
15074     * @hide
15075     */
15076    @Override
15077    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
15078            int installReason) {
15079        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
15080                null);
15081        PackageSetting pkgSetting;
15082        final int callingUid = Binder.getCallingUid();
15083        enforceCrossUserPermission(callingUid, userId,
15084                true /* requireFullPermission */, true /* checkShell */,
15085                "installExistingPackage for user " + userId);
15086        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
15087            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
15088        }
15089
15090        long callingId = Binder.clearCallingIdentity();
15091        try {
15092            boolean installed = false;
15093            final boolean instantApp =
15094                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15095            final boolean fullApp =
15096                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
15097
15098            // writer
15099            synchronized (mPackages) {
15100                pkgSetting = mSettings.mPackages.get(packageName);
15101                if (pkgSetting == null) {
15102                    return PackageManager.INSTALL_FAILED_INVALID_URI;
15103                }
15104                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
15105                    // only allow the existing package to be used if it's installed as a full
15106                    // application for at least one user
15107                    boolean installAllowed = false;
15108                    for (int checkUserId : sUserManager.getUserIds()) {
15109                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
15110                        if (installAllowed) {
15111                            break;
15112                        }
15113                    }
15114                    if (!installAllowed) {
15115                        return PackageManager.INSTALL_FAILED_INVALID_URI;
15116                    }
15117                }
15118                if (!pkgSetting.getInstalled(userId)) {
15119                    pkgSetting.setInstalled(true, userId);
15120                    pkgSetting.setHidden(false, userId);
15121                    pkgSetting.setInstallReason(installReason, userId);
15122                    mSettings.writePackageRestrictionsLPr(userId);
15123                    mSettings.writeKernelMappingLPr(pkgSetting);
15124                    installed = true;
15125                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15126                    // upgrade app from instant to full; we don't allow app downgrade
15127                    installed = true;
15128                }
15129                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
15130            }
15131
15132            if (installed) {
15133                if (pkgSetting.pkg != null) {
15134                    synchronized (mInstallLock) {
15135                        // We don't need to freeze for a brand new install
15136                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
15137                    }
15138                }
15139                sendPackageAddedForUser(packageName, pkgSetting, userId);
15140                synchronized (mPackages) {
15141                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
15142                }
15143            }
15144        } finally {
15145            Binder.restoreCallingIdentity(callingId);
15146        }
15147
15148        return PackageManager.INSTALL_SUCCEEDED;
15149    }
15150
15151    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
15152            boolean instantApp, boolean fullApp) {
15153        // no state specified; do nothing
15154        if (!instantApp && !fullApp) {
15155            return;
15156        }
15157        if (userId != UserHandle.USER_ALL) {
15158            if (instantApp && !pkgSetting.getInstantApp(userId)) {
15159                pkgSetting.setInstantApp(true /*instantApp*/, userId);
15160            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15161                pkgSetting.setInstantApp(false /*instantApp*/, userId);
15162            }
15163        } else {
15164            for (int currentUserId : sUserManager.getUserIds()) {
15165                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
15166                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
15167                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
15168                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
15169                }
15170            }
15171        }
15172    }
15173
15174    boolean isUserRestricted(int userId, String restrictionKey) {
15175        Bundle restrictions = sUserManager.getUserRestrictions(userId);
15176        if (restrictions.getBoolean(restrictionKey, false)) {
15177            Log.w(TAG, "User is restricted: " + restrictionKey);
15178            return true;
15179        }
15180        return false;
15181    }
15182
15183    @Override
15184    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15185            int userId) {
15186        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15187        final int callingUid = Binder.getCallingUid();
15188        enforceCrossUserPermission(callingUid, userId,
15189                true /* requireFullPermission */, true /* checkShell */,
15190                "setPackagesSuspended for user " + userId);
15191
15192        if (ArrayUtils.isEmpty(packageNames)) {
15193            return packageNames;
15194        }
15195
15196        // List of package names for whom the suspended state has changed.
15197        List<String> changedPackages = new ArrayList<>(packageNames.length);
15198        // List of package names for whom the suspended state is not set as requested in this
15199        // method.
15200        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15201        long callingId = Binder.clearCallingIdentity();
15202        try {
15203            for (int i = 0; i < packageNames.length; i++) {
15204                String packageName = packageNames[i];
15205                boolean changed = false;
15206                final int appId;
15207                synchronized (mPackages) {
15208                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15209                    if (pkgSetting == null
15210                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15211                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15212                                + "\". Skipping suspending/un-suspending.");
15213                        unactionedPackages.add(packageName);
15214                        continue;
15215                    }
15216                    appId = pkgSetting.appId;
15217                    if (pkgSetting.getSuspended(userId) != suspended) {
15218                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15219                            unactionedPackages.add(packageName);
15220                            continue;
15221                        }
15222                        pkgSetting.setSuspended(suspended, userId);
15223                        mSettings.writePackageRestrictionsLPr(userId);
15224                        changed = true;
15225                        changedPackages.add(packageName);
15226                    }
15227                }
15228
15229                if (changed && suspended) {
15230                    killApplication(packageName, UserHandle.getUid(userId, appId),
15231                            "suspending package");
15232                }
15233            }
15234        } finally {
15235            Binder.restoreCallingIdentity(callingId);
15236        }
15237
15238        if (!changedPackages.isEmpty()) {
15239            sendPackagesSuspendedForUser(changedPackages.toArray(
15240                    new String[changedPackages.size()]), userId, suspended);
15241        }
15242
15243        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15244    }
15245
15246    @Override
15247    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15248        final int callingUid = Binder.getCallingUid();
15249        enforceCrossUserPermission(callingUid, userId,
15250                true /* requireFullPermission */, false /* checkShell */,
15251                "isPackageSuspendedForUser for user " + userId);
15252        synchronized (mPackages) {
15253            final PackageSetting ps = mSettings.mPackages.get(packageName);
15254            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15255                throw new IllegalArgumentException("Unknown target package: " + packageName);
15256            }
15257            return ps.getSuspended(userId);
15258        }
15259    }
15260
15261    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15262        if (isPackageDeviceAdmin(packageName, userId)) {
15263            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15264                    + "\": has an active device admin");
15265            return false;
15266        }
15267
15268        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15269        if (packageName.equals(activeLauncherPackageName)) {
15270            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15271                    + "\": contains the active launcher");
15272            return false;
15273        }
15274
15275        if (packageName.equals(mRequiredInstallerPackage)) {
15276            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15277                    + "\": required for package installation");
15278            return false;
15279        }
15280
15281        if (packageName.equals(mRequiredUninstallerPackage)) {
15282            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15283                    + "\": required for package uninstallation");
15284            return false;
15285        }
15286
15287        if (packageName.equals(mRequiredVerifierPackage)) {
15288            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15289                    + "\": required for package verification");
15290            return false;
15291        }
15292
15293        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15294            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15295                    + "\": is the default dialer");
15296            return false;
15297        }
15298
15299        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15300            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15301                    + "\": protected package");
15302            return false;
15303        }
15304
15305        // Cannot suspend static shared libs as they are considered
15306        // a part of the using app (emulating static linking). Also
15307        // static libs are installed always on internal storage.
15308        PackageParser.Package pkg = mPackages.get(packageName);
15309        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15310            Slog.w(TAG, "Cannot suspend package: " + packageName
15311                    + " providing static shared library: "
15312                    + pkg.staticSharedLibName);
15313            return false;
15314        }
15315
15316        return true;
15317    }
15318
15319    private String getActiveLauncherPackageName(int userId) {
15320        Intent intent = new Intent(Intent.ACTION_MAIN);
15321        intent.addCategory(Intent.CATEGORY_HOME);
15322        ResolveInfo resolveInfo = resolveIntent(
15323                intent,
15324                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15325                PackageManager.MATCH_DEFAULT_ONLY,
15326                userId);
15327
15328        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15329    }
15330
15331    private String getDefaultDialerPackageName(int userId) {
15332        synchronized (mPackages) {
15333            return mSettings.getDefaultDialerPackageNameLPw(userId);
15334        }
15335    }
15336
15337    @Override
15338    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15339        mContext.enforceCallingOrSelfPermission(
15340                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15341                "Only package verification agents can verify applications");
15342
15343        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15344        final PackageVerificationResponse response = new PackageVerificationResponse(
15345                verificationCode, Binder.getCallingUid());
15346        msg.arg1 = id;
15347        msg.obj = response;
15348        mHandler.sendMessage(msg);
15349    }
15350
15351    @Override
15352    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15353            long millisecondsToDelay) {
15354        mContext.enforceCallingOrSelfPermission(
15355                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15356                "Only package verification agents can extend verification timeouts");
15357
15358        final PackageVerificationState state = mPendingVerification.get(id);
15359        final PackageVerificationResponse response = new PackageVerificationResponse(
15360                verificationCodeAtTimeout, Binder.getCallingUid());
15361
15362        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15363            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15364        }
15365        if (millisecondsToDelay < 0) {
15366            millisecondsToDelay = 0;
15367        }
15368        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15369                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15370            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15371        }
15372
15373        if ((state != null) && !state.timeoutExtended()) {
15374            state.extendTimeout();
15375
15376            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15377            msg.arg1 = id;
15378            msg.obj = response;
15379            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15380        }
15381    }
15382
15383    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15384            int verificationCode, UserHandle user) {
15385        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15386        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15387        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15388        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15389        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15390
15391        mContext.sendBroadcastAsUser(intent, user,
15392                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15393    }
15394
15395    private ComponentName matchComponentForVerifier(String packageName,
15396            List<ResolveInfo> receivers) {
15397        ActivityInfo targetReceiver = null;
15398
15399        final int NR = receivers.size();
15400        for (int i = 0; i < NR; i++) {
15401            final ResolveInfo info = receivers.get(i);
15402            if (info.activityInfo == null) {
15403                continue;
15404            }
15405
15406            if (packageName.equals(info.activityInfo.packageName)) {
15407                targetReceiver = info.activityInfo;
15408                break;
15409            }
15410        }
15411
15412        if (targetReceiver == null) {
15413            return null;
15414        }
15415
15416        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15417    }
15418
15419    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15420            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15421        if (pkgInfo.verifiers.length == 0) {
15422            return null;
15423        }
15424
15425        final int N = pkgInfo.verifiers.length;
15426        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15427        for (int i = 0; i < N; i++) {
15428            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15429
15430            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15431                    receivers);
15432            if (comp == null) {
15433                continue;
15434            }
15435
15436            final int verifierUid = getUidForVerifier(verifierInfo);
15437            if (verifierUid == -1) {
15438                continue;
15439            }
15440
15441            if (DEBUG_VERIFY) {
15442                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15443                        + " with the correct signature");
15444            }
15445            sufficientVerifiers.add(comp);
15446            verificationState.addSufficientVerifier(verifierUid);
15447        }
15448
15449        return sufficientVerifiers;
15450    }
15451
15452    private int getUidForVerifier(VerifierInfo verifierInfo) {
15453        synchronized (mPackages) {
15454            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15455            if (pkg == null) {
15456                return -1;
15457            } else if (pkg.mSignatures.length != 1) {
15458                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15459                        + " has more than one signature; ignoring");
15460                return -1;
15461            }
15462
15463            /*
15464             * If the public key of the package's signature does not match
15465             * our expected public key, then this is a different package and
15466             * we should skip.
15467             */
15468
15469            final byte[] expectedPublicKey;
15470            try {
15471                final Signature verifierSig = pkg.mSignatures[0];
15472                final PublicKey publicKey = verifierSig.getPublicKey();
15473                expectedPublicKey = publicKey.getEncoded();
15474            } catch (CertificateException e) {
15475                return -1;
15476            }
15477
15478            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15479
15480            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15481                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15482                        + " does not have the expected public key; ignoring");
15483                return -1;
15484            }
15485
15486            return pkg.applicationInfo.uid;
15487        }
15488    }
15489
15490    @Override
15491    public void finishPackageInstall(int token, boolean didLaunch) {
15492        enforceSystemOrRoot("Only the system is allowed to finish installs");
15493
15494        if (DEBUG_INSTALL) {
15495            Slog.v(TAG, "BM finishing package install for " + token);
15496        }
15497        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15498
15499        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15500        mHandler.sendMessage(msg);
15501    }
15502
15503    /**
15504     * Get the verification agent timeout.  Used for both the APK verifier and the
15505     * intent filter verifier.
15506     *
15507     * @return verification timeout in milliseconds
15508     */
15509    private long getVerificationTimeout() {
15510        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15511                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15512                DEFAULT_VERIFICATION_TIMEOUT);
15513    }
15514
15515    /**
15516     * Get the default verification agent response code.
15517     *
15518     * @return default verification response code
15519     */
15520    private int getDefaultVerificationResponse(UserHandle user) {
15521        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15522            return PackageManager.VERIFICATION_REJECT;
15523        }
15524        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15525                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15526                DEFAULT_VERIFICATION_RESPONSE);
15527    }
15528
15529    /**
15530     * Check whether or not package verification has been enabled.
15531     *
15532     * @return true if verification should be performed
15533     */
15534    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15535        if (!DEFAULT_VERIFY_ENABLE) {
15536            return false;
15537        }
15538
15539        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15540
15541        // Check if installing from ADB
15542        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15543            // Do not run verification in a test harness environment
15544            if (ActivityManager.isRunningInTestHarness()) {
15545                return false;
15546            }
15547            if (ensureVerifyAppsEnabled) {
15548                return true;
15549            }
15550            // Check if the developer does not want package verification for ADB installs
15551            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15552                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15553                return false;
15554            }
15555        } else {
15556            // only when not installed from ADB, skip verification for instant apps when
15557            // the installer and verifier are the same.
15558            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15559                if (mInstantAppInstallerActivity != null
15560                        && mInstantAppInstallerActivity.packageName.equals(
15561                                mRequiredVerifierPackage)) {
15562                    try {
15563                        mContext.getSystemService(AppOpsManager.class)
15564                                .checkPackage(installerUid, mRequiredVerifierPackage);
15565                        if (DEBUG_VERIFY) {
15566                            Slog.i(TAG, "disable verification for instant app");
15567                        }
15568                        return false;
15569                    } catch (SecurityException ignore) { }
15570                }
15571            }
15572        }
15573
15574        if (ensureVerifyAppsEnabled) {
15575            return true;
15576        }
15577
15578        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15579                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15580    }
15581
15582    @Override
15583    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15584            throws RemoteException {
15585        mContext.enforceCallingOrSelfPermission(
15586                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15587                "Only intentfilter verification agents can verify applications");
15588
15589        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15590        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15591                Binder.getCallingUid(), verificationCode, failedDomains);
15592        msg.arg1 = id;
15593        msg.obj = response;
15594        mHandler.sendMessage(msg);
15595    }
15596
15597    @Override
15598    public int getIntentVerificationStatus(String packageName, int userId) {
15599        final int callingUid = Binder.getCallingUid();
15600        if (UserHandle.getUserId(callingUid) != userId) {
15601            mContext.enforceCallingOrSelfPermission(
15602                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15603                    "getIntentVerificationStatus" + userId);
15604        }
15605        if (getInstantAppPackageName(callingUid) != null) {
15606            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15607        }
15608        synchronized (mPackages) {
15609            final PackageSetting ps = mSettings.mPackages.get(packageName);
15610            if (ps == null
15611                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15612                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15613            }
15614            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15615        }
15616    }
15617
15618    @Override
15619    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15620        mContext.enforceCallingOrSelfPermission(
15621                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15622
15623        boolean result = false;
15624        synchronized (mPackages) {
15625            final PackageSetting ps = mSettings.mPackages.get(packageName);
15626            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15627                return false;
15628            }
15629            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15630        }
15631        if (result) {
15632            scheduleWritePackageRestrictionsLocked(userId);
15633        }
15634        return result;
15635    }
15636
15637    @Override
15638    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15639            String packageName) {
15640        final int callingUid = Binder.getCallingUid();
15641        if (getInstantAppPackageName(callingUid) != null) {
15642            return ParceledListSlice.emptyList();
15643        }
15644        synchronized (mPackages) {
15645            final PackageSetting ps = mSettings.mPackages.get(packageName);
15646            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15647                return ParceledListSlice.emptyList();
15648            }
15649            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15650        }
15651    }
15652
15653    @Override
15654    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15655        if (TextUtils.isEmpty(packageName)) {
15656            return ParceledListSlice.emptyList();
15657        }
15658        final int callingUid = Binder.getCallingUid();
15659        final int callingUserId = UserHandle.getUserId(callingUid);
15660        synchronized (mPackages) {
15661            PackageParser.Package pkg = mPackages.get(packageName);
15662            if (pkg == null || pkg.activities == null) {
15663                return ParceledListSlice.emptyList();
15664            }
15665            if (pkg.mExtras == null) {
15666                return ParceledListSlice.emptyList();
15667            }
15668            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15669            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15670                return ParceledListSlice.emptyList();
15671            }
15672            final int count = pkg.activities.size();
15673            ArrayList<IntentFilter> result = new ArrayList<>();
15674            for (int n=0; n<count; n++) {
15675                PackageParser.Activity activity = pkg.activities.get(n);
15676                if (activity.intents != null && activity.intents.size() > 0) {
15677                    result.addAll(activity.intents);
15678                }
15679            }
15680            return new ParceledListSlice<>(result);
15681        }
15682    }
15683
15684    @Override
15685    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15686        mContext.enforceCallingOrSelfPermission(
15687                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15688        if (UserHandle.getCallingUserId() != userId) {
15689            mContext.enforceCallingOrSelfPermission(
15690                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15691        }
15692
15693        synchronized (mPackages) {
15694            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15695            if (packageName != null) {
15696                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15697                        packageName, userId);
15698            }
15699            return result;
15700        }
15701    }
15702
15703    @Override
15704    public String getDefaultBrowserPackageName(int userId) {
15705        if (UserHandle.getCallingUserId() != userId) {
15706            mContext.enforceCallingOrSelfPermission(
15707                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15708        }
15709        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15710            return null;
15711        }
15712        synchronized (mPackages) {
15713            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15714        }
15715    }
15716
15717    /**
15718     * Get the "allow unknown sources" setting.
15719     *
15720     * @return the current "allow unknown sources" setting
15721     */
15722    private int getUnknownSourcesSettings() {
15723        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15724                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15725                -1);
15726    }
15727
15728    @Override
15729    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15730        final int callingUid = Binder.getCallingUid();
15731        if (getInstantAppPackageName(callingUid) != null) {
15732            return;
15733        }
15734        // writer
15735        synchronized (mPackages) {
15736            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15737            if (targetPackageSetting == null
15738                    || filterAppAccessLPr(
15739                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15740                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15741            }
15742
15743            PackageSetting installerPackageSetting;
15744            if (installerPackageName != null) {
15745                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15746                if (installerPackageSetting == null) {
15747                    throw new IllegalArgumentException("Unknown installer package: "
15748                            + installerPackageName);
15749                }
15750            } else {
15751                installerPackageSetting = null;
15752            }
15753
15754            Signature[] callerSignature;
15755            Object obj = mSettings.getUserIdLPr(callingUid);
15756            if (obj != null) {
15757                if (obj instanceof SharedUserSetting) {
15758                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15759                } else if (obj instanceof PackageSetting) {
15760                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15761                } else {
15762                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15763                }
15764            } else {
15765                throw new SecurityException("Unknown calling UID: " + callingUid);
15766            }
15767
15768            // Verify: can't set installerPackageName to a package that is
15769            // not signed with the same cert as the caller.
15770            if (installerPackageSetting != null) {
15771                if (compareSignatures(callerSignature,
15772                        installerPackageSetting.signatures.mSignatures)
15773                        != PackageManager.SIGNATURE_MATCH) {
15774                    throw new SecurityException(
15775                            "Caller does not have same cert as new installer package "
15776                            + installerPackageName);
15777                }
15778            }
15779
15780            // Verify: if target already has an installer package, it must
15781            // be signed with the same cert as the caller.
15782            if (targetPackageSetting.installerPackageName != null) {
15783                PackageSetting setting = mSettings.mPackages.get(
15784                        targetPackageSetting.installerPackageName);
15785                // If the currently set package isn't valid, then it's always
15786                // okay to change it.
15787                if (setting != null) {
15788                    if (compareSignatures(callerSignature,
15789                            setting.signatures.mSignatures)
15790                            != PackageManager.SIGNATURE_MATCH) {
15791                        throw new SecurityException(
15792                                "Caller does not have same cert as old installer package "
15793                                + targetPackageSetting.installerPackageName);
15794                    }
15795                }
15796            }
15797
15798            // Okay!
15799            targetPackageSetting.installerPackageName = installerPackageName;
15800            if (installerPackageName != null) {
15801                mSettings.mInstallerPackages.add(installerPackageName);
15802            }
15803            scheduleWriteSettingsLocked();
15804        }
15805    }
15806
15807    @Override
15808    public void setApplicationCategoryHint(String packageName, int categoryHint,
15809            String callerPackageName) {
15810        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15811            throw new SecurityException("Instant applications don't have access to this method");
15812        }
15813        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15814                callerPackageName);
15815        synchronized (mPackages) {
15816            PackageSetting ps = mSettings.mPackages.get(packageName);
15817            if (ps == null) {
15818                throw new IllegalArgumentException("Unknown target package " + packageName);
15819            }
15820            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15821                throw new IllegalArgumentException("Unknown target package " + packageName);
15822            }
15823            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15824                throw new IllegalArgumentException("Calling package " + callerPackageName
15825                        + " is not installer for " + packageName);
15826            }
15827
15828            if (ps.categoryHint != categoryHint) {
15829                ps.categoryHint = categoryHint;
15830                scheduleWriteSettingsLocked();
15831            }
15832        }
15833    }
15834
15835    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15836        // Queue up an async operation since the package installation may take a little while.
15837        mHandler.post(new Runnable() {
15838            public void run() {
15839                mHandler.removeCallbacks(this);
15840                 // Result object to be returned
15841                PackageInstalledInfo res = new PackageInstalledInfo();
15842                res.setReturnCode(currentStatus);
15843                res.uid = -1;
15844                res.pkg = null;
15845                res.removedInfo = null;
15846                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15847                    args.doPreInstall(res.returnCode);
15848                    synchronized (mInstallLock) {
15849                        installPackageTracedLI(args, res);
15850                    }
15851                    args.doPostInstall(res.returnCode, res.uid);
15852                }
15853
15854                // A restore should be performed at this point if (a) the install
15855                // succeeded, (b) the operation is not an update, and (c) the new
15856                // package has not opted out of backup participation.
15857                final boolean update = res.removedInfo != null
15858                        && res.removedInfo.removedPackage != null;
15859                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15860                boolean doRestore = !update
15861                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15862
15863                // Set up the post-install work request bookkeeping.  This will be used
15864                // and cleaned up by the post-install event handling regardless of whether
15865                // there's a restore pass performed.  Token values are >= 1.
15866                int token;
15867                if (mNextInstallToken < 0) mNextInstallToken = 1;
15868                token = mNextInstallToken++;
15869
15870                PostInstallData data = new PostInstallData(args, res);
15871                mRunningInstalls.put(token, data);
15872                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15873
15874                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15875                    // Pass responsibility to the Backup Manager.  It will perform a
15876                    // restore if appropriate, then pass responsibility back to the
15877                    // Package Manager to run the post-install observer callbacks
15878                    // and broadcasts.
15879                    IBackupManager bm = IBackupManager.Stub.asInterface(
15880                            ServiceManager.getService(Context.BACKUP_SERVICE));
15881                    if (bm != null) {
15882                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15883                                + " to BM for possible restore");
15884                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15885                        try {
15886                            // TODO: http://b/22388012
15887                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15888                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15889                            } else {
15890                                doRestore = false;
15891                            }
15892                        } catch (RemoteException e) {
15893                            // can't happen; the backup manager is local
15894                        } catch (Exception e) {
15895                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15896                            doRestore = false;
15897                        }
15898                    } else {
15899                        Slog.e(TAG, "Backup Manager not found!");
15900                        doRestore = false;
15901                    }
15902                }
15903
15904                if (!doRestore) {
15905                    // No restore possible, or the Backup Manager was mysteriously not
15906                    // available -- just fire the post-install work request directly.
15907                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15908
15909                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15910
15911                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15912                    mHandler.sendMessage(msg);
15913                }
15914            }
15915        });
15916    }
15917
15918    /**
15919     * Callback from PackageSettings whenever an app is first transitioned out of the
15920     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15921     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15922     * here whether the app is the target of an ongoing install, and only send the
15923     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15924     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15925     * handling.
15926     */
15927    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15928        // Serialize this with the rest of the install-process message chain.  In the
15929        // restore-at-install case, this Runnable will necessarily run before the
15930        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15931        // are coherent.  In the non-restore case, the app has already completed install
15932        // and been launched through some other means, so it is not in a problematic
15933        // state for observers to see the FIRST_LAUNCH signal.
15934        mHandler.post(new Runnable() {
15935            @Override
15936            public void run() {
15937                for (int i = 0; i < mRunningInstalls.size(); i++) {
15938                    final PostInstallData data = mRunningInstalls.valueAt(i);
15939                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15940                        continue;
15941                    }
15942                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15943                        // right package; but is it for the right user?
15944                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15945                            if (userId == data.res.newUsers[uIndex]) {
15946                                if (DEBUG_BACKUP) {
15947                                    Slog.i(TAG, "Package " + pkgName
15948                                            + " being restored so deferring FIRST_LAUNCH");
15949                                }
15950                                return;
15951                            }
15952                        }
15953                    }
15954                }
15955                // didn't find it, so not being restored
15956                if (DEBUG_BACKUP) {
15957                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15958                }
15959                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15960            }
15961        });
15962    }
15963
15964    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15965        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15966                installerPkg, null, userIds);
15967    }
15968
15969    private abstract class HandlerParams {
15970        private static final int MAX_RETRIES = 4;
15971
15972        /**
15973         * Number of times startCopy() has been attempted and had a non-fatal
15974         * error.
15975         */
15976        private int mRetries = 0;
15977
15978        /** User handle for the user requesting the information or installation. */
15979        private final UserHandle mUser;
15980        String traceMethod;
15981        int traceCookie;
15982
15983        HandlerParams(UserHandle user) {
15984            mUser = user;
15985        }
15986
15987        UserHandle getUser() {
15988            return mUser;
15989        }
15990
15991        HandlerParams setTraceMethod(String traceMethod) {
15992            this.traceMethod = traceMethod;
15993            return this;
15994        }
15995
15996        HandlerParams setTraceCookie(int traceCookie) {
15997            this.traceCookie = traceCookie;
15998            return this;
15999        }
16000
16001        final boolean startCopy() {
16002            boolean res;
16003            try {
16004                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
16005
16006                if (++mRetries > MAX_RETRIES) {
16007                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
16008                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
16009                    handleServiceError();
16010                    return false;
16011                } else {
16012                    handleStartCopy();
16013                    res = true;
16014                }
16015            } catch (RemoteException e) {
16016                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
16017                mHandler.sendEmptyMessage(MCS_RECONNECT);
16018                res = false;
16019            }
16020            handleReturnCode();
16021            return res;
16022        }
16023
16024        final void serviceError() {
16025            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
16026            handleServiceError();
16027            handleReturnCode();
16028        }
16029
16030        abstract void handleStartCopy() throws RemoteException;
16031        abstract void handleServiceError();
16032        abstract void handleReturnCode();
16033    }
16034
16035    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
16036        for (File path : paths) {
16037            try {
16038                mcs.clearDirectory(path.getAbsolutePath());
16039            } catch (RemoteException e) {
16040            }
16041        }
16042    }
16043
16044    static class OriginInfo {
16045        /**
16046         * Location where install is coming from, before it has been
16047         * copied/renamed into place. This could be a single monolithic APK
16048         * file, or a cluster directory. This location may be untrusted.
16049         */
16050        final File file;
16051        final String cid;
16052
16053        /**
16054         * Flag indicating that {@link #file} or {@link #cid} has already been
16055         * staged, meaning downstream users don't need to defensively copy the
16056         * contents.
16057         */
16058        final boolean staged;
16059
16060        /**
16061         * Flag indicating that {@link #file} or {@link #cid} is an already
16062         * installed app that is being moved.
16063         */
16064        final boolean existing;
16065
16066        final String resolvedPath;
16067        final File resolvedFile;
16068
16069        static OriginInfo fromNothing() {
16070            return new OriginInfo(null, null, false, false);
16071        }
16072
16073        static OriginInfo fromUntrustedFile(File file) {
16074            return new OriginInfo(file, null, false, false);
16075        }
16076
16077        static OriginInfo fromExistingFile(File file) {
16078            return new OriginInfo(file, null, false, true);
16079        }
16080
16081        static OriginInfo fromStagedFile(File file) {
16082            return new OriginInfo(file, null, true, false);
16083        }
16084
16085        static OriginInfo fromStagedContainer(String cid) {
16086            return new OriginInfo(null, cid, true, false);
16087        }
16088
16089        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
16090            this.file = file;
16091            this.cid = cid;
16092            this.staged = staged;
16093            this.existing = existing;
16094
16095            if (cid != null) {
16096                resolvedPath = PackageHelper.getSdDir(cid);
16097                resolvedFile = new File(resolvedPath);
16098            } else if (file != null) {
16099                resolvedPath = file.getAbsolutePath();
16100                resolvedFile = file;
16101            } else {
16102                resolvedPath = null;
16103                resolvedFile = null;
16104            }
16105        }
16106    }
16107
16108    static class MoveInfo {
16109        final int moveId;
16110        final String fromUuid;
16111        final String toUuid;
16112        final String packageName;
16113        final String dataAppName;
16114        final int appId;
16115        final String seinfo;
16116        final int targetSdkVersion;
16117
16118        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
16119                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
16120            this.moveId = moveId;
16121            this.fromUuid = fromUuid;
16122            this.toUuid = toUuid;
16123            this.packageName = packageName;
16124            this.dataAppName = dataAppName;
16125            this.appId = appId;
16126            this.seinfo = seinfo;
16127            this.targetSdkVersion = targetSdkVersion;
16128        }
16129    }
16130
16131    static class VerificationInfo {
16132        /** A constant used to indicate that a uid value is not present. */
16133        public static final int NO_UID = -1;
16134
16135        /** URI referencing where the package was downloaded from. */
16136        final Uri originatingUri;
16137
16138        /** HTTP referrer URI associated with the originatingURI. */
16139        final Uri referrer;
16140
16141        /** UID of the application that the install request originated from. */
16142        final int originatingUid;
16143
16144        /** UID of application requesting the install */
16145        final int installerUid;
16146
16147        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
16148            this.originatingUri = originatingUri;
16149            this.referrer = referrer;
16150            this.originatingUid = originatingUid;
16151            this.installerUid = installerUid;
16152        }
16153    }
16154
16155    class InstallParams extends HandlerParams {
16156        final OriginInfo origin;
16157        final MoveInfo move;
16158        final IPackageInstallObserver2 observer;
16159        int installFlags;
16160        final String installerPackageName;
16161        final String volumeUuid;
16162        private InstallArgs mArgs;
16163        private int mRet;
16164        final String packageAbiOverride;
16165        final String[] grantedRuntimePermissions;
16166        final VerificationInfo verificationInfo;
16167        final Certificate[][] certificates;
16168        final int installReason;
16169
16170        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16171                int installFlags, String installerPackageName, String volumeUuid,
16172                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16173                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16174            super(user);
16175            this.origin = origin;
16176            this.move = move;
16177            this.observer = observer;
16178            this.installFlags = installFlags;
16179            this.installerPackageName = installerPackageName;
16180            this.volumeUuid = volumeUuid;
16181            this.verificationInfo = verificationInfo;
16182            this.packageAbiOverride = packageAbiOverride;
16183            this.grantedRuntimePermissions = grantedPermissions;
16184            this.certificates = certificates;
16185            this.installReason = installReason;
16186        }
16187
16188        @Override
16189        public String toString() {
16190            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16191                    + " file=" + origin.file + " cid=" + origin.cid + "}";
16192        }
16193
16194        private int installLocationPolicy(PackageInfoLite pkgLite) {
16195            String packageName = pkgLite.packageName;
16196            int installLocation = pkgLite.installLocation;
16197            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16198            // reader
16199            synchronized (mPackages) {
16200                // Currently installed package which the new package is attempting to replace or
16201                // null if no such package is installed.
16202                PackageParser.Package installedPkg = mPackages.get(packageName);
16203                // Package which currently owns the data which the new package will own if installed.
16204                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16205                // will be null whereas dataOwnerPkg will contain information about the package
16206                // which was uninstalled while keeping its data.
16207                PackageParser.Package dataOwnerPkg = installedPkg;
16208                if (dataOwnerPkg  == null) {
16209                    PackageSetting ps = mSettings.mPackages.get(packageName);
16210                    if (ps != null) {
16211                        dataOwnerPkg = ps.pkg;
16212                    }
16213                }
16214
16215                if (dataOwnerPkg != null) {
16216                    // If installed, the package will get access to data left on the device by its
16217                    // predecessor. As a security measure, this is permited only if this is not a
16218                    // version downgrade or if the predecessor package is marked as debuggable and
16219                    // a downgrade is explicitly requested.
16220                    //
16221                    // On debuggable platform builds, downgrades are permitted even for
16222                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16223                    // not offer security guarantees and thus it's OK to disable some security
16224                    // mechanisms to make debugging/testing easier on those builds. However, even on
16225                    // debuggable builds downgrades of packages are permitted only if requested via
16226                    // installFlags. This is because we aim to keep the behavior of debuggable
16227                    // platform builds as close as possible to the behavior of non-debuggable
16228                    // platform builds.
16229                    final boolean downgradeRequested =
16230                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16231                    final boolean packageDebuggable =
16232                                (dataOwnerPkg.applicationInfo.flags
16233                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16234                    final boolean downgradePermitted =
16235                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16236                    if (!downgradePermitted) {
16237                        try {
16238                            checkDowngrade(dataOwnerPkg, pkgLite);
16239                        } catch (PackageManagerException e) {
16240                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16241                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16242                        }
16243                    }
16244                }
16245
16246                if (installedPkg != null) {
16247                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16248                        // Check for updated system application.
16249                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16250                            if (onSd) {
16251                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16252                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16253                            }
16254                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16255                        } else {
16256                            if (onSd) {
16257                                // Install flag overrides everything.
16258                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16259                            }
16260                            // If current upgrade specifies particular preference
16261                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16262                                // Application explicitly specified internal.
16263                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16264                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16265                                // App explictly prefers external. Let policy decide
16266                            } else {
16267                                // Prefer previous location
16268                                if (isExternal(installedPkg)) {
16269                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16270                                }
16271                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16272                            }
16273                        }
16274                    } else {
16275                        // Invalid install. Return error code
16276                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16277                    }
16278                }
16279            }
16280            // All the special cases have been taken care of.
16281            // Return result based on recommended install location.
16282            if (onSd) {
16283                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16284            }
16285            return pkgLite.recommendedInstallLocation;
16286        }
16287
16288        /*
16289         * Invoke remote method to get package information and install
16290         * location values. Override install location based on default
16291         * policy if needed and then create install arguments based
16292         * on the install location.
16293         */
16294        public void handleStartCopy() throws RemoteException {
16295            int ret = PackageManager.INSTALL_SUCCEEDED;
16296
16297            // If we're already staged, we've firmly committed to an install location
16298            if (origin.staged) {
16299                if (origin.file != null) {
16300                    installFlags |= PackageManager.INSTALL_INTERNAL;
16301                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16302                } else if (origin.cid != null) {
16303                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16304                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16305                } else {
16306                    throw new IllegalStateException("Invalid stage location");
16307                }
16308            }
16309
16310            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16311            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16312            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16313            PackageInfoLite pkgLite = null;
16314
16315            if (onInt && onSd) {
16316                // Check if both bits are set.
16317                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16318                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16319            } else if (onSd && ephemeral) {
16320                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16321                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16322            } else {
16323                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16324                        packageAbiOverride);
16325
16326                if (DEBUG_EPHEMERAL && ephemeral) {
16327                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16328                }
16329
16330                /*
16331                 * If we have too little free space, try to free cache
16332                 * before giving up.
16333                 */
16334                if (!origin.staged && pkgLite.recommendedInstallLocation
16335                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16336                    // TODO: focus freeing disk space on the target device
16337                    final StorageManager storage = StorageManager.from(mContext);
16338                    final long lowThreshold = storage.getStorageLowBytes(
16339                            Environment.getDataDirectory());
16340
16341                    final long sizeBytes = mContainerService.calculateInstalledSize(
16342                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16343
16344                    try {
16345                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16346                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16347                                installFlags, packageAbiOverride);
16348                    } catch (InstallerException e) {
16349                        Slog.w(TAG, "Failed to free cache", e);
16350                    }
16351
16352                    /*
16353                     * The cache free must have deleted the file we
16354                     * downloaded to install.
16355                     *
16356                     * TODO: fix the "freeCache" call to not delete
16357                     *       the file we care about.
16358                     */
16359                    if (pkgLite.recommendedInstallLocation
16360                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16361                        pkgLite.recommendedInstallLocation
16362                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16363                    }
16364                }
16365            }
16366
16367            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16368                int loc = pkgLite.recommendedInstallLocation;
16369                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16370                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16371                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16372                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16373                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16374                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16375                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16376                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16377                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16378                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16379                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16380                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16381                } else {
16382                    // Override with defaults if needed.
16383                    loc = installLocationPolicy(pkgLite);
16384                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16385                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16386                    } else if (!onSd && !onInt) {
16387                        // Override install location with flags
16388                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16389                            // Set the flag to install on external media.
16390                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16391                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16392                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16393                            if (DEBUG_EPHEMERAL) {
16394                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16395                            }
16396                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16397                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16398                                    |PackageManager.INSTALL_INTERNAL);
16399                        } else {
16400                            // Make sure the flag for installing on external
16401                            // media is unset
16402                            installFlags |= PackageManager.INSTALL_INTERNAL;
16403                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16404                        }
16405                    }
16406                }
16407            }
16408
16409            final InstallArgs args = createInstallArgs(this);
16410            mArgs = args;
16411
16412            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16413                // TODO: http://b/22976637
16414                // Apps installed for "all" users use the device owner to verify the app
16415                UserHandle verifierUser = getUser();
16416                if (verifierUser == UserHandle.ALL) {
16417                    verifierUser = UserHandle.SYSTEM;
16418                }
16419
16420                /*
16421                 * Determine if we have any installed package verifiers. If we
16422                 * do, then we'll defer to them to verify the packages.
16423                 */
16424                final int requiredUid = mRequiredVerifierPackage == null ? -1
16425                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16426                                verifierUser.getIdentifier());
16427                final int installerUid =
16428                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16429                if (!origin.existing && requiredUid != -1
16430                        && isVerificationEnabled(
16431                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16432                    final Intent verification = new Intent(
16433                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16434                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16435                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16436                            PACKAGE_MIME_TYPE);
16437                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16438
16439                    // Query all live verifiers based on current user state
16440                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16441                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16442                            false /*allowDynamicSplits*/);
16443
16444                    if (DEBUG_VERIFY) {
16445                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16446                                + verification.toString() + " with " + pkgLite.verifiers.length
16447                                + " optional verifiers");
16448                    }
16449
16450                    final int verificationId = mPendingVerificationToken++;
16451
16452                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16453
16454                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16455                            installerPackageName);
16456
16457                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16458                            installFlags);
16459
16460                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16461                            pkgLite.packageName);
16462
16463                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16464                            pkgLite.versionCode);
16465
16466                    if (verificationInfo != null) {
16467                        if (verificationInfo.originatingUri != null) {
16468                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16469                                    verificationInfo.originatingUri);
16470                        }
16471                        if (verificationInfo.referrer != null) {
16472                            verification.putExtra(Intent.EXTRA_REFERRER,
16473                                    verificationInfo.referrer);
16474                        }
16475                        if (verificationInfo.originatingUid >= 0) {
16476                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16477                                    verificationInfo.originatingUid);
16478                        }
16479                        if (verificationInfo.installerUid >= 0) {
16480                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16481                                    verificationInfo.installerUid);
16482                        }
16483                    }
16484
16485                    final PackageVerificationState verificationState = new PackageVerificationState(
16486                            requiredUid, args);
16487
16488                    mPendingVerification.append(verificationId, verificationState);
16489
16490                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16491                            receivers, verificationState);
16492
16493                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16494                    final long idleDuration = getVerificationTimeout();
16495
16496                    /*
16497                     * If any sufficient verifiers were listed in the package
16498                     * manifest, attempt to ask them.
16499                     */
16500                    if (sufficientVerifiers != null) {
16501                        final int N = sufficientVerifiers.size();
16502                        if (N == 0) {
16503                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16504                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16505                        } else {
16506                            for (int i = 0; i < N; i++) {
16507                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16508                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16509                                        verifierComponent.getPackageName(), idleDuration,
16510                                        verifierUser.getIdentifier(), false, "package verifier");
16511
16512                                final Intent sufficientIntent = new Intent(verification);
16513                                sufficientIntent.setComponent(verifierComponent);
16514                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16515                            }
16516                        }
16517                    }
16518
16519                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16520                            mRequiredVerifierPackage, receivers);
16521                    if (ret == PackageManager.INSTALL_SUCCEEDED
16522                            && mRequiredVerifierPackage != null) {
16523                        Trace.asyncTraceBegin(
16524                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16525                        /*
16526                         * Send the intent to the required verification agent,
16527                         * but only start the verification timeout after the
16528                         * target BroadcastReceivers have run.
16529                         */
16530                        verification.setComponent(requiredVerifierComponent);
16531                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16532                                mRequiredVerifierPackage, idleDuration,
16533                                verifierUser.getIdentifier(), false, "package verifier");
16534                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16535                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16536                                new BroadcastReceiver() {
16537                                    @Override
16538                                    public void onReceive(Context context, Intent intent) {
16539                                        final Message msg = mHandler
16540                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16541                                        msg.arg1 = verificationId;
16542                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16543                                    }
16544                                }, null, 0, null, null);
16545
16546                        /*
16547                         * We don't want the copy to proceed until verification
16548                         * succeeds, so null out this field.
16549                         */
16550                        mArgs = null;
16551                    }
16552                } else {
16553                    /*
16554                     * No package verification is enabled, so immediately start
16555                     * the remote call to initiate copy using temporary file.
16556                     */
16557                    ret = args.copyApk(mContainerService, true);
16558                }
16559            }
16560
16561            mRet = ret;
16562        }
16563
16564        @Override
16565        void handleReturnCode() {
16566            // If mArgs is null, then MCS couldn't be reached. When it
16567            // reconnects, it will try again to install. At that point, this
16568            // will succeed.
16569            if (mArgs != null) {
16570                processPendingInstall(mArgs, mRet);
16571            }
16572        }
16573
16574        @Override
16575        void handleServiceError() {
16576            mArgs = createInstallArgs(this);
16577            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16578        }
16579
16580        public boolean isForwardLocked() {
16581            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16582        }
16583    }
16584
16585    /**
16586     * Used during creation of InstallArgs
16587     *
16588     * @param installFlags package installation flags
16589     * @return true if should be installed on external storage
16590     */
16591    private static boolean installOnExternalAsec(int installFlags) {
16592        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16593            return false;
16594        }
16595        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16596            return true;
16597        }
16598        return false;
16599    }
16600
16601    /**
16602     * Used during creation of InstallArgs
16603     *
16604     * @param installFlags package installation flags
16605     * @return true if should be installed as forward locked
16606     */
16607    private static boolean installForwardLocked(int installFlags) {
16608        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16609    }
16610
16611    private InstallArgs createInstallArgs(InstallParams params) {
16612        if (params.move != null) {
16613            return new MoveInstallArgs(params);
16614        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16615            return new AsecInstallArgs(params);
16616        } else {
16617            return new FileInstallArgs(params);
16618        }
16619    }
16620
16621    /**
16622     * Create args that describe an existing installed package. Typically used
16623     * when cleaning up old installs, or used as a move source.
16624     */
16625    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16626            String resourcePath, String[] instructionSets) {
16627        final boolean isInAsec;
16628        if (installOnExternalAsec(installFlags)) {
16629            /* Apps on SD card are always in ASEC containers. */
16630            isInAsec = true;
16631        } else if (installForwardLocked(installFlags)
16632                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16633            /*
16634             * Forward-locked apps are only in ASEC containers if they're the
16635             * new style
16636             */
16637            isInAsec = true;
16638        } else {
16639            isInAsec = false;
16640        }
16641
16642        if (isInAsec) {
16643            return new AsecInstallArgs(codePath, instructionSets,
16644                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16645        } else {
16646            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16647        }
16648    }
16649
16650    static abstract class InstallArgs {
16651        /** @see InstallParams#origin */
16652        final OriginInfo origin;
16653        /** @see InstallParams#move */
16654        final MoveInfo move;
16655
16656        final IPackageInstallObserver2 observer;
16657        // Always refers to PackageManager flags only
16658        final int installFlags;
16659        final String installerPackageName;
16660        final String volumeUuid;
16661        final UserHandle user;
16662        final String abiOverride;
16663        final String[] installGrantPermissions;
16664        /** If non-null, drop an async trace when the install completes */
16665        final String traceMethod;
16666        final int traceCookie;
16667        final Certificate[][] certificates;
16668        final int installReason;
16669
16670        // The list of instruction sets supported by this app. This is currently
16671        // only used during the rmdex() phase to clean up resources. We can get rid of this
16672        // if we move dex files under the common app path.
16673        /* nullable */ String[] instructionSets;
16674
16675        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16676                int installFlags, String installerPackageName, String volumeUuid,
16677                UserHandle user, String[] instructionSets,
16678                String abiOverride, String[] installGrantPermissions,
16679                String traceMethod, int traceCookie, Certificate[][] certificates,
16680                int installReason) {
16681            this.origin = origin;
16682            this.move = move;
16683            this.installFlags = installFlags;
16684            this.observer = observer;
16685            this.installerPackageName = installerPackageName;
16686            this.volumeUuid = volumeUuid;
16687            this.user = user;
16688            this.instructionSets = instructionSets;
16689            this.abiOverride = abiOverride;
16690            this.installGrantPermissions = installGrantPermissions;
16691            this.traceMethod = traceMethod;
16692            this.traceCookie = traceCookie;
16693            this.certificates = certificates;
16694            this.installReason = installReason;
16695        }
16696
16697        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16698        abstract int doPreInstall(int status);
16699
16700        /**
16701         * Rename package into final resting place. All paths on the given
16702         * scanned package should be updated to reflect the rename.
16703         */
16704        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16705        abstract int doPostInstall(int status, int uid);
16706
16707        /** @see PackageSettingBase#codePathString */
16708        abstract String getCodePath();
16709        /** @see PackageSettingBase#resourcePathString */
16710        abstract String getResourcePath();
16711
16712        // Need installer lock especially for dex file removal.
16713        abstract void cleanUpResourcesLI();
16714        abstract boolean doPostDeleteLI(boolean delete);
16715
16716        /**
16717         * Called before the source arguments are copied. This is used mostly
16718         * for MoveParams when it needs to read the source file to put it in the
16719         * destination.
16720         */
16721        int doPreCopy() {
16722            return PackageManager.INSTALL_SUCCEEDED;
16723        }
16724
16725        /**
16726         * Called after the source arguments are copied. This is used mostly for
16727         * MoveParams when it needs to read the source file to put it in the
16728         * destination.
16729         */
16730        int doPostCopy(int uid) {
16731            return PackageManager.INSTALL_SUCCEEDED;
16732        }
16733
16734        protected boolean isFwdLocked() {
16735            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16736        }
16737
16738        protected boolean isExternalAsec() {
16739            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16740        }
16741
16742        protected boolean isEphemeral() {
16743            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16744        }
16745
16746        UserHandle getUser() {
16747            return user;
16748        }
16749    }
16750
16751    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16752        if (!allCodePaths.isEmpty()) {
16753            if (instructionSets == null) {
16754                throw new IllegalStateException("instructionSet == null");
16755            }
16756            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16757            for (String codePath : allCodePaths) {
16758                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16759                    try {
16760                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16761                    } catch (InstallerException ignored) {
16762                    }
16763                }
16764            }
16765        }
16766    }
16767
16768    /**
16769     * Logic to handle installation of non-ASEC applications, including copying
16770     * and renaming logic.
16771     */
16772    class FileInstallArgs extends InstallArgs {
16773        private File codeFile;
16774        private File resourceFile;
16775
16776        // Example topology:
16777        // /data/app/com.example/base.apk
16778        // /data/app/com.example/split_foo.apk
16779        // /data/app/com.example/lib/arm/libfoo.so
16780        // /data/app/com.example/lib/arm64/libfoo.so
16781        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16782
16783        /** New install */
16784        FileInstallArgs(InstallParams params) {
16785            super(params.origin, params.move, params.observer, params.installFlags,
16786                    params.installerPackageName, params.volumeUuid,
16787                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16788                    params.grantedRuntimePermissions,
16789                    params.traceMethod, params.traceCookie, params.certificates,
16790                    params.installReason);
16791            if (isFwdLocked()) {
16792                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16793            }
16794        }
16795
16796        /** Existing install */
16797        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16798            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16799                    null, null, null, 0, null /*certificates*/,
16800                    PackageManager.INSTALL_REASON_UNKNOWN);
16801            this.codeFile = (codePath != null) ? new File(codePath) : null;
16802            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16803        }
16804
16805        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16806            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16807            try {
16808                return doCopyApk(imcs, temp);
16809            } finally {
16810                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16811            }
16812        }
16813
16814        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16815            if (origin.staged) {
16816                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16817                codeFile = origin.file;
16818                resourceFile = origin.file;
16819                return PackageManager.INSTALL_SUCCEEDED;
16820            }
16821
16822            try {
16823                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16824                final File tempDir =
16825                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16826                codeFile = tempDir;
16827                resourceFile = tempDir;
16828            } catch (IOException e) {
16829                Slog.w(TAG, "Failed to create copy file: " + e);
16830                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16831            }
16832
16833            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16834                @Override
16835                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16836                    if (!FileUtils.isValidExtFilename(name)) {
16837                        throw new IllegalArgumentException("Invalid filename: " + name);
16838                    }
16839                    try {
16840                        final File file = new File(codeFile, name);
16841                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16842                                O_RDWR | O_CREAT, 0644);
16843                        Os.chmod(file.getAbsolutePath(), 0644);
16844                        return new ParcelFileDescriptor(fd);
16845                    } catch (ErrnoException e) {
16846                        throw new RemoteException("Failed to open: " + e.getMessage());
16847                    }
16848                }
16849            };
16850
16851            int ret = PackageManager.INSTALL_SUCCEEDED;
16852            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16853            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16854                Slog.e(TAG, "Failed to copy package");
16855                return ret;
16856            }
16857
16858            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16859            NativeLibraryHelper.Handle handle = null;
16860            try {
16861                handle = NativeLibraryHelper.Handle.create(codeFile);
16862                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16863                        abiOverride);
16864            } catch (IOException e) {
16865                Slog.e(TAG, "Copying native libraries failed", e);
16866                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16867            } finally {
16868                IoUtils.closeQuietly(handle);
16869            }
16870
16871            return ret;
16872        }
16873
16874        int doPreInstall(int status) {
16875            if (status != PackageManager.INSTALL_SUCCEEDED) {
16876                cleanUp();
16877            }
16878            return status;
16879        }
16880
16881        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16882            if (status != PackageManager.INSTALL_SUCCEEDED) {
16883                cleanUp();
16884                return false;
16885            }
16886
16887            final File targetDir = codeFile.getParentFile();
16888            final File beforeCodeFile = codeFile;
16889            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16890
16891            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16892            try {
16893                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16894            } catch (ErrnoException e) {
16895                Slog.w(TAG, "Failed to rename", e);
16896                return false;
16897            }
16898
16899            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16900                Slog.w(TAG, "Failed to restorecon");
16901                return false;
16902            }
16903
16904            // Reflect the rename internally
16905            codeFile = afterCodeFile;
16906            resourceFile = afterCodeFile;
16907
16908            // Reflect the rename in scanned details
16909            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16910            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16911                    afterCodeFile, pkg.baseCodePath));
16912            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16913                    afterCodeFile, pkg.splitCodePaths));
16914
16915            // Reflect the rename in app info
16916            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16917            pkg.setApplicationInfoCodePath(pkg.codePath);
16918            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16919            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16920            pkg.setApplicationInfoResourcePath(pkg.codePath);
16921            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16922            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16923
16924            return true;
16925        }
16926
16927        int doPostInstall(int status, int uid) {
16928            if (status != PackageManager.INSTALL_SUCCEEDED) {
16929                cleanUp();
16930            }
16931            return status;
16932        }
16933
16934        @Override
16935        String getCodePath() {
16936            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16937        }
16938
16939        @Override
16940        String getResourcePath() {
16941            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16942        }
16943
16944        private boolean cleanUp() {
16945            if (codeFile == null || !codeFile.exists()) {
16946                return false;
16947            }
16948
16949            removeCodePathLI(codeFile);
16950
16951            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16952                resourceFile.delete();
16953            }
16954
16955            return true;
16956        }
16957
16958        void cleanUpResourcesLI() {
16959            // Try enumerating all code paths before deleting
16960            List<String> allCodePaths = Collections.EMPTY_LIST;
16961            if (codeFile != null && codeFile.exists()) {
16962                try {
16963                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16964                    allCodePaths = pkg.getAllCodePaths();
16965                } catch (PackageParserException e) {
16966                    // Ignored; we tried our best
16967                }
16968            }
16969
16970            cleanUp();
16971            removeDexFiles(allCodePaths, instructionSets);
16972        }
16973
16974        boolean doPostDeleteLI(boolean delete) {
16975            // XXX err, shouldn't we respect the delete flag?
16976            cleanUpResourcesLI();
16977            return true;
16978        }
16979    }
16980
16981    private boolean isAsecExternal(String cid) {
16982        final String asecPath = PackageHelper.getSdFilesystem(cid);
16983        return !asecPath.startsWith(mAsecInternalPath);
16984    }
16985
16986    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16987            PackageManagerException {
16988        if (copyRet < 0) {
16989            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16990                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16991                throw new PackageManagerException(copyRet, message);
16992            }
16993        }
16994    }
16995
16996    /**
16997     * Extract the StorageManagerService "container ID" from the full code path of an
16998     * .apk.
16999     */
17000    static String cidFromCodePath(String fullCodePath) {
17001        int eidx = fullCodePath.lastIndexOf("/");
17002        String subStr1 = fullCodePath.substring(0, eidx);
17003        int sidx = subStr1.lastIndexOf("/");
17004        return subStr1.substring(sidx+1, eidx);
17005    }
17006
17007    /**
17008     * Logic to handle installation of ASEC applications, including copying and
17009     * renaming logic.
17010     */
17011    class AsecInstallArgs extends InstallArgs {
17012        static final String RES_FILE_NAME = "pkg.apk";
17013        static final String PUBLIC_RES_FILE_NAME = "res.zip";
17014
17015        String cid;
17016        String packagePath;
17017        String resourcePath;
17018
17019        /** New install */
17020        AsecInstallArgs(InstallParams params) {
17021            super(params.origin, params.move, params.observer, params.installFlags,
17022                    params.installerPackageName, params.volumeUuid,
17023                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17024                    params.grantedRuntimePermissions,
17025                    params.traceMethod, params.traceCookie, params.certificates,
17026                    params.installReason);
17027        }
17028
17029        /** Existing install */
17030        AsecInstallArgs(String fullCodePath, String[] instructionSets,
17031                        boolean isExternal, boolean isForwardLocked) {
17032            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
17033                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
17034                    instructionSets, null, null, null, 0, null /*certificates*/,
17035                    PackageManager.INSTALL_REASON_UNKNOWN);
17036            // Hackily pretend we're still looking at a full code path
17037            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
17038                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
17039            }
17040
17041            // Extract cid from fullCodePath
17042            int eidx = fullCodePath.lastIndexOf("/");
17043            String subStr1 = fullCodePath.substring(0, eidx);
17044            int sidx = subStr1.lastIndexOf("/");
17045            cid = subStr1.substring(sidx+1, eidx);
17046            setMountPath(subStr1);
17047        }
17048
17049        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
17050            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
17051                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
17052                    instructionSets, null, null, null, 0, null /*certificates*/,
17053                    PackageManager.INSTALL_REASON_UNKNOWN);
17054            this.cid = cid;
17055            setMountPath(PackageHelper.getSdDir(cid));
17056        }
17057
17058        void createCopyFile() {
17059            cid = mInstallerService.allocateExternalStageCidLegacy();
17060        }
17061
17062        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
17063            if (origin.staged && origin.cid != null) {
17064                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
17065                cid = origin.cid;
17066                setMountPath(PackageHelper.getSdDir(cid));
17067                return PackageManager.INSTALL_SUCCEEDED;
17068            }
17069
17070            if (temp) {
17071                createCopyFile();
17072            } else {
17073                /*
17074                 * Pre-emptively destroy the container since it's destroyed if
17075                 * copying fails due to it existing anyway.
17076                 */
17077                PackageHelper.destroySdDir(cid);
17078            }
17079
17080            final String newMountPath = imcs.copyPackageToContainer(
17081                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
17082                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
17083
17084            if (newMountPath != null) {
17085                setMountPath(newMountPath);
17086                return PackageManager.INSTALL_SUCCEEDED;
17087            } else {
17088                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17089            }
17090        }
17091
17092        @Override
17093        String getCodePath() {
17094            return packagePath;
17095        }
17096
17097        @Override
17098        String getResourcePath() {
17099            return resourcePath;
17100        }
17101
17102        int doPreInstall(int status) {
17103            if (status != PackageManager.INSTALL_SUCCEEDED) {
17104                // Destroy container
17105                PackageHelper.destroySdDir(cid);
17106            } else {
17107                boolean mounted = PackageHelper.isContainerMounted(cid);
17108                if (!mounted) {
17109                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
17110                            Process.SYSTEM_UID);
17111                    if (newMountPath != null) {
17112                        setMountPath(newMountPath);
17113                    } else {
17114                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17115                    }
17116                }
17117            }
17118            return status;
17119        }
17120
17121        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17122            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
17123            String newMountPath = null;
17124            if (PackageHelper.isContainerMounted(cid)) {
17125                // Unmount the container
17126                if (!PackageHelper.unMountSdDir(cid)) {
17127                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
17128                    return false;
17129                }
17130            }
17131            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17132                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
17133                        " which might be stale. Will try to clean up.");
17134                // Clean up the stale container and proceed to recreate.
17135                if (!PackageHelper.destroySdDir(newCacheId)) {
17136                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
17137                    return false;
17138                }
17139                // Successfully cleaned up stale container. Try to rename again.
17140                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17141                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
17142                            + " inspite of cleaning it up.");
17143                    return false;
17144                }
17145            }
17146            if (!PackageHelper.isContainerMounted(newCacheId)) {
17147                Slog.w(TAG, "Mounting container " + newCacheId);
17148                newMountPath = PackageHelper.mountSdDir(newCacheId,
17149                        getEncryptKey(), Process.SYSTEM_UID);
17150            } else {
17151                newMountPath = PackageHelper.getSdDir(newCacheId);
17152            }
17153            if (newMountPath == null) {
17154                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
17155                return false;
17156            }
17157            Log.i(TAG, "Succesfully renamed " + cid +
17158                    " to " + newCacheId +
17159                    " at new path: " + newMountPath);
17160            cid = newCacheId;
17161
17162            final File beforeCodeFile = new File(packagePath);
17163            setMountPath(newMountPath);
17164            final File afterCodeFile = new File(packagePath);
17165
17166            // Reflect the rename in scanned details
17167            pkg.setCodePath(afterCodeFile.getAbsolutePath());
17168            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
17169                    afterCodeFile, pkg.baseCodePath));
17170            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
17171                    afterCodeFile, pkg.splitCodePaths));
17172
17173            // Reflect the rename in app info
17174            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17175            pkg.setApplicationInfoCodePath(pkg.codePath);
17176            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17177            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17178            pkg.setApplicationInfoResourcePath(pkg.codePath);
17179            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17180            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17181
17182            return true;
17183        }
17184
17185        private void setMountPath(String mountPath) {
17186            final File mountFile = new File(mountPath);
17187
17188            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
17189            if (monolithicFile.exists()) {
17190                packagePath = monolithicFile.getAbsolutePath();
17191                if (isFwdLocked()) {
17192                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
17193                } else {
17194                    resourcePath = packagePath;
17195                }
17196            } else {
17197                packagePath = mountFile.getAbsolutePath();
17198                resourcePath = packagePath;
17199            }
17200        }
17201
17202        int doPostInstall(int status, int uid) {
17203            if (status != PackageManager.INSTALL_SUCCEEDED) {
17204                cleanUp();
17205            } else {
17206                final int groupOwner;
17207                final String protectedFile;
17208                if (isFwdLocked()) {
17209                    groupOwner = UserHandle.getSharedAppGid(uid);
17210                    protectedFile = RES_FILE_NAME;
17211                } else {
17212                    groupOwner = -1;
17213                    protectedFile = null;
17214                }
17215
17216                if (uid < Process.FIRST_APPLICATION_UID
17217                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
17218                    Slog.e(TAG, "Failed to finalize " + cid);
17219                    PackageHelper.destroySdDir(cid);
17220                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17221                }
17222
17223                boolean mounted = PackageHelper.isContainerMounted(cid);
17224                if (!mounted) {
17225                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17226                }
17227            }
17228            return status;
17229        }
17230
17231        private void cleanUp() {
17232            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17233
17234            // Destroy secure container
17235            PackageHelper.destroySdDir(cid);
17236        }
17237
17238        private List<String> getAllCodePaths() {
17239            final File codeFile = new File(getCodePath());
17240            if (codeFile != null && codeFile.exists()) {
17241                try {
17242                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17243                    return pkg.getAllCodePaths();
17244                } catch (PackageParserException e) {
17245                    // Ignored; we tried our best
17246                }
17247            }
17248            return Collections.EMPTY_LIST;
17249        }
17250
17251        void cleanUpResourcesLI() {
17252            // Enumerate all code paths before deleting
17253            cleanUpResourcesLI(getAllCodePaths());
17254        }
17255
17256        private void cleanUpResourcesLI(List<String> allCodePaths) {
17257            cleanUp();
17258            removeDexFiles(allCodePaths, instructionSets);
17259        }
17260
17261        String getPackageName() {
17262            return getAsecPackageName(cid);
17263        }
17264
17265        boolean doPostDeleteLI(boolean delete) {
17266            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17267            final List<String> allCodePaths = getAllCodePaths();
17268            boolean mounted = PackageHelper.isContainerMounted(cid);
17269            if (mounted) {
17270                // Unmount first
17271                if (PackageHelper.unMountSdDir(cid)) {
17272                    mounted = false;
17273                }
17274            }
17275            if (!mounted && delete) {
17276                cleanUpResourcesLI(allCodePaths);
17277            }
17278            return !mounted;
17279        }
17280
17281        @Override
17282        int doPreCopy() {
17283            if (isFwdLocked()) {
17284                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17285                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17286                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17287                }
17288            }
17289
17290            return PackageManager.INSTALL_SUCCEEDED;
17291        }
17292
17293        @Override
17294        int doPostCopy(int uid) {
17295            if (isFwdLocked()) {
17296                if (uid < Process.FIRST_APPLICATION_UID
17297                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17298                                RES_FILE_NAME)) {
17299                    Slog.e(TAG, "Failed to finalize " + cid);
17300                    PackageHelper.destroySdDir(cid);
17301                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17302                }
17303            }
17304
17305            return PackageManager.INSTALL_SUCCEEDED;
17306        }
17307    }
17308
17309    /**
17310     * Logic to handle movement of existing installed applications.
17311     */
17312    class MoveInstallArgs extends InstallArgs {
17313        private File codeFile;
17314        private File resourceFile;
17315
17316        /** New install */
17317        MoveInstallArgs(InstallParams params) {
17318            super(params.origin, params.move, params.observer, params.installFlags,
17319                    params.installerPackageName, params.volumeUuid,
17320                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17321                    params.grantedRuntimePermissions,
17322                    params.traceMethod, params.traceCookie, params.certificates,
17323                    params.installReason);
17324        }
17325
17326        int copyApk(IMediaContainerService imcs, boolean temp) {
17327            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17328                    + move.fromUuid + " to " + move.toUuid);
17329            synchronized (mInstaller) {
17330                try {
17331                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17332                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17333                } catch (InstallerException e) {
17334                    Slog.w(TAG, "Failed to move app", e);
17335                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17336                }
17337            }
17338
17339            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17340            resourceFile = codeFile;
17341            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17342
17343            return PackageManager.INSTALL_SUCCEEDED;
17344        }
17345
17346        int doPreInstall(int status) {
17347            if (status != PackageManager.INSTALL_SUCCEEDED) {
17348                cleanUp(move.toUuid);
17349            }
17350            return status;
17351        }
17352
17353        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17354            if (status != PackageManager.INSTALL_SUCCEEDED) {
17355                cleanUp(move.toUuid);
17356                return false;
17357            }
17358
17359            // Reflect the move in app info
17360            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17361            pkg.setApplicationInfoCodePath(pkg.codePath);
17362            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17363            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17364            pkg.setApplicationInfoResourcePath(pkg.codePath);
17365            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17366            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17367
17368            return true;
17369        }
17370
17371        int doPostInstall(int status, int uid) {
17372            if (status == PackageManager.INSTALL_SUCCEEDED) {
17373                cleanUp(move.fromUuid);
17374            } else {
17375                cleanUp(move.toUuid);
17376            }
17377            return status;
17378        }
17379
17380        @Override
17381        String getCodePath() {
17382            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17383        }
17384
17385        @Override
17386        String getResourcePath() {
17387            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17388        }
17389
17390        private boolean cleanUp(String volumeUuid) {
17391            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17392                    move.dataAppName);
17393            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17394            final int[] userIds = sUserManager.getUserIds();
17395            synchronized (mInstallLock) {
17396                // Clean up both app data and code
17397                // All package moves are frozen until finished
17398                for (int userId : userIds) {
17399                    try {
17400                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17401                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17402                    } catch (InstallerException e) {
17403                        Slog.w(TAG, String.valueOf(e));
17404                    }
17405                }
17406                removeCodePathLI(codeFile);
17407            }
17408            return true;
17409        }
17410
17411        void cleanUpResourcesLI() {
17412            throw new UnsupportedOperationException();
17413        }
17414
17415        boolean doPostDeleteLI(boolean delete) {
17416            throw new UnsupportedOperationException();
17417        }
17418    }
17419
17420    static String getAsecPackageName(String packageCid) {
17421        int idx = packageCid.lastIndexOf("-");
17422        if (idx == -1) {
17423            return packageCid;
17424        }
17425        return packageCid.substring(0, idx);
17426    }
17427
17428    // Utility method used to create code paths based on package name and available index.
17429    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17430        String idxStr = "";
17431        int idx = 1;
17432        // Fall back to default value of idx=1 if prefix is not
17433        // part of oldCodePath
17434        if (oldCodePath != null) {
17435            String subStr = oldCodePath;
17436            // Drop the suffix right away
17437            if (suffix != null && subStr.endsWith(suffix)) {
17438                subStr = subStr.substring(0, subStr.length() - suffix.length());
17439            }
17440            // If oldCodePath already contains prefix find out the
17441            // ending index to either increment or decrement.
17442            int sidx = subStr.lastIndexOf(prefix);
17443            if (sidx != -1) {
17444                subStr = subStr.substring(sidx + prefix.length());
17445                if (subStr != null) {
17446                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17447                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17448                    }
17449                    try {
17450                        idx = Integer.parseInt(subStr);
17451                        if (idx <= 1) {
17452                            idx++;
17453                        } else {
17454                            idx--;
17455                        }
17456                    } catch(NumberFormatException e) {
17457                    }
17458                }
17459            }
17460        }
17461        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17462        return prefix + idxStr;
17463    }
17464
17465    private File getNextCodePath(File targetDir, String packageName) {
17466        File result;
17467        SecureRandom random = new SecureRandom();
17468        byte[] bytes = new byte[16];
17469        do {
17470            random.nextBytes(bytes);
17471            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17472            result = new File(targetDir, packageName + "-" + suffix);
17473        } while (result.exists());
17474        return result;
17475    }
17476
17477    // Utility method that returns the relative package path with respect
17478    // to the installation directory. Like say for /data/data/com.test-1.apk
17479    // string com.test-1 is returned.
17480    static String deriveCodePathName(String codePath) {
17481        if (codePath == null) {
17482            return null;
17483        }
17484        final File codeFile = new File(codePath);
17485        final String name = codeFile.getName();
17486        if (codeFile.isDirectory()) {
17487            return name;
17488        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17489            final int lastDot = name.lastIndexOf('.');
17490            return name.substring(0, lastDot);
17491        } else {
17492            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17493            return null;
17494        }
17495    }
17496
17497    static class PackageInstalledInfo {
17498        String name;
17499        int uid;
17500        // The set of users that originally had this package installed.
17501        int[] origUsers;
17502        // The set of users that now have this package installed.
17503        int[] newUsers;
17504        PackageParser.Package pkg;
17505        int returnCode;
17506        String returnMsg;
17507        String installerPackageName;
17508        PackageRemovedInfo removedInfo;
17509        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17510
17511        public void setError(int code, String msg) {
17512            setReturnCode(code);
17513            setReturnMessage(msg);
17514            Slog.w(TAG, msg);
17515        }
17516
17517        public void setError(String msg, PackageParserException e) {
17518            setReturnCode(e.error);
17519            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17520            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17521            for (int i = 0; i < childCount; i++) {
17522                addedChildPackages.valueAt(i).setError(msg, e);
17523            }
17524            Slog.w(TAG, msg, e);
17525        }
17526
17527        public void setError(String msg, PackageManagerException e) {
17528            returnCode = e.error;
17529            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17530            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17531            for (int i = 0; i < childCount; i++) {
17532                addedChildPackages.valueAt(i).setError(msg, e);
17533            }
17534            Slog.w(TAG, msg, e);
17535        }
17536
17537        public void setReturnCode(int returnCode) {
17538            this.returnCode = returnCode;
17539            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17540            for (int i = 0; i < childCount; i++) {
17541                addedChildPackages.valueAt(i).returnCode = returnCode;
17542            }
17543        }
17544
17545        private void setReturnMessage(String returnMsg) {
17546            this.returnMsg = returnMsg;
17547            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17548            for (int i = 0; i < childCount; i++) {
17549                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17550            }
17551        }
17552
17553        // In some error cases we want to convey more info back to the observer
17554        String origPackage;
17555        String origPermission;
17556    }
17557
17558    /*
17559     * Install a non-existing package.
17560     */
17561    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17562            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17563            PackageInstalledInfo res, int installReason) {
17564        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17565
17566        // Remember this for later, in case we need to rollback this install
17567        String pkgName = pkg.packageName;
17568
17569        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17570
17571        synchronized(mPackages) {
17572            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17573            if (renamedPackage != null) {
17574                // A package with the same name is already installed, though
17575                // it has been renamed to an older name.  The package we
17576                // are trying to install should be installed as an update to
17577                // the existing one, but that has not been requested, so bail.
17578                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17579                        + " without first uninstalling package running as "
17580                        + renamedPackage);
17581                return;
17582            }
17583            if (mPackages.containsKey(pkgName)) {
17584                // Don't allow installation over an existing package with the same name.
17585                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17586                        + " without first uninstalling.");
17587                return;
17588            }
17589        }
17590
17591        try {
17592            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17593                    System.currentTimeMillis(), user);
17594
17595            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17596
17597            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17598                prepareAppDataAfterInstallLIF(newPackage);
17599
17600            } else {
17601                // Remove package from internal structures, but keep around any
17602                // data that might have already existed
17603                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17604                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17605            }
17606        } catch (PackageManagerException e) {
17607            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17608        }
17609
17610        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17611    }
17612
17613    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17614        // Can't rotate keys during boot or if sharedUser.
17615        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17616                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17617            return false;
17618        }
17619        // app is using upgradeKeySets; make sure all are valid
17620        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17621        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17622        for (int i = 0; i < upgradeKeySets.length; i++) {
17623            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17624                Slog.wtf(TAG, "Package "
17625                         + (oldPs.name != null ? oldPs.name : "<null>")
17626                         + " contains upgrade-key-set reference to unknown key-set: "
17627                         + upgradeKeySets[i]
17628                         + " reverting to signatures check.");
17629                return false;
17630            }
17631        }
17632        return true;
17633    }
17634
17635    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17636        // Upgrade keysets are being used.  Determine if new package has a superset of the
17637        // required keys.
17638        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17639        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17640        for (int i = 0; i < upgradeKeySets.length; i++) {
17641            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17642            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17643                return true;
17644            }
17645        }
17646        return false;
17647    }
17648
17649    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17650        try (DigestInputStream digestStream =
17651                new DigestInputStream(new FileInputStream(file), digest)) {
17652            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17653        }
17654    }
17655
17656    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17657            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17658            int installReason) {
17659        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17660
17661        final PackageParser.Package oldPackage;
17662        final PackageSetting ps;
17663        final String pkgName = pkg.packageName;
17664        final int[] allUsers;
17665        final int[] installedUsers;
17666
17667        synchronized(mPackages) {
17668            oldPackage = mPackages.get(pkgName);
17669            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17670
17671            // don't allow upgrade to target a release SDK from a pre-release SDK
17672            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17673                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17674            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17675                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17676            if (oldTargetsPreRelease
17677                    && !newTargetsPreRelease
17678                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17679                Slog.w(TAG, "Can't install package targeting released sdk");
17680                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17681                return;
17682            }
17683
17684            ps = mSettings.mPackages.get(pkgName);
17685
17686            // verify signatures are valid
17687            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17688                if (!checkUpgradeKeySetLP(ps, pkg)) {
17689                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17690                            "New package not signed by keys specified by upgrade-keysets: "
17691                                    + pkgName);
17692                    return;
17693                }
17694            } else {
17695                // default to original signature matching
17696                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17697                        != PackageManager.SIGNATURE_MATCH) {
17698                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17699                            "New package has a different signature: " + pkgName);
17700                    return;
17701                }
17702            }
17703
17704            // don't allow a system upgrade unless the upgrade hash matches
17705            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17706                byte[] digestBytes = null;
17707                try {
17708                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17709                    updateDigest(digest, new File(pkg.baseCodePath));
17710                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17711                        for (String path : pkg.splitCodePaths) {
17712                            updateDigest(digest, new File(path));
17713                        }
17714                    }
17715                    digestBytes = digest.digest();
17716                } catch (NoSuchAlgorithmException | IOException e) {
17717                    res.setError(INSTALL_FAILED_INVALID_APK,
17718                            "Could not compute hash: " + pkgName);
17719                    return;
17720                }
17721                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17722                    res.setError(INSTALL_FAILED_INVALID_APK,
17723                            "New package fails restrict-update check: " + pkgName);
17724                    return;
17725                }
17726                // retain upgrade restriction
17727                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17728            }
17729
17730            // Check for shared user id changes
17731            String invalidPackageName =
17732                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17733            if (invalidPackageName != null) {
17734                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17735                        "Package " + invalidPackageName + " tried to change user "
17736                                + oldPackage.mSharedUserId);
17737                return;
17738            }
17739
17740            // check if the new package supports all of the abis which the old package supports
17741            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
17742            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
17743            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
17744                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17745                        "Update to package " + pkgName + " doesn't support multi arch");
17746                return;
17747            }
17748
17749            // In case of rollback, remember per-user/profile install state
17750            allUsers = sUserManager.getUserIds();
17751            installedUsers = ps.queryInstalledUsers(allUsers, true);
17752
17753            // don't allow an upgrade from full to ephemeral
17754            if (isInstantApp) {
17755                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17756                    for (int currentUser : allUsers) {
17757                        if (!ps.getInstantApp(currentUser)) {
17758                            // can't downgrade from full to instant
17759                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17760                                    + " for user: " + currentUser);
17761                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17762                            return;
17763                        }
17764                    }
17765                } else if (!ps.getInstantApp(user.getIdentifier())) {
17766                    // can't downgrade from full to instant
17767                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17768                            + " for user: " + user.getIdentifier());
17769                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17770                    return;
17771                }
17772            }
17773        }
17774
17775        // Update what is removed
17776        res.removedInfo = new PackageRemovedInfo(this);
17777        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17778        res.removedInfo.removedPackage = oldPackage.packageName;
17779        res.removedInfo.installerPackageName = ps.installerPackageName;
17780        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17781        res.removedInfo.isUpdate = true;
17782        res.removedInfo.origUsers = installedUsers;
17783        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17784        for (int i = 0; i < installedUsers.length; i++) {
17785            final int userId = installedUsers[i];
17786            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17787        }
17788
17789        final int childCount = (oldPackage.childPackages != null)
17790                ? oldPackage.childPackages.size() : 0;
17791        for (int i = 0; i < childCount; i++) {
17792            boolean childPackageUpdated = false;
17793            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17794            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17795            if (res.addedChildPackages != null) {
17796                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17797                if (childRes != null) {
17798                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17799                    childRes.removedInfo.removedPackage = childPkg.packageName;
17800                    if (childPs != null) {
17801                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17802                    }
17803                    childRes.removedInfo.isUpdate = true;
17804                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17805                    childPackageUpdated = true;
17806                }
17807            }
17808            if (!childPackageUpdated) {
17809                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17810                childRemovedRes.removedPackage = childPkg.packageName;
17811                if (childPs != null) {
17812                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17813                }
17814                childRemovedRes.isUpdate = false;
17815                childRemovedRes.dataRemoved = true;
17816                synchronized (mPackages) {
17817                    if (childPs != null) {
17818                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17819                    }
17820                }
17821                if (res.removedInfo.removedChildPackages == null) {
17822                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17823                }
17824                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17825            }
17826        }
17827
17828        boolean sysPkg = (isSystemApp(oldPackage));
17829        if (sysPkg) {
17830            // Set the system/privileged flags as needed
17831            final boolean privileged =
17832                    (oldPackage.applicationInfo.privateFlags
17833                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17834            final int systemPolicyFlags = policyFlags
17835                    | PackageParser.PARSE_IS_SYSTEM
17836                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17837
17838            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17839                    user, allUsers, installerPackageName, res, installReason);
17840        } else {
17841            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17842                    user, allUsers, installerPackageName, res, installReason);
17843        }
17844    }
17845
17846    @Override
17847    public List<String> getPreviousCodePaths(String packageName) {
17848        final int callingUid = Binder.getCallingUid();
17849        final List<String> result = new ArrayList<>();
17850        if (getInstantAppPackageName(callingUid) != null) {
17851            return result;
17852        }
17853        final PackageSetting ps = mSettings.mPackages.get(packageName);
17854        if (ps != null
17855                && ps.oldCodePaths != null
17856                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17857            result.addAll(ps.oldCodePaths);
17858        }
17859        return result;
17860    }
17861
17862    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17863            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17864            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17865            int installReason) {
17866        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17867                + deletedPackage);
17868
17869        String pkgName = deletedPackage.packageName;
17870        boolean deletedPkg = true;
17871        boolean addedPkg = false;
17872        boolean updatedSettings = false;
17873        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17874        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17875                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17876
17877        final long origUpdateTime = (pkg.mExtras != null)
17878                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17879
17880        // First delete the existing package while retaining the data directory
17881        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17882                res.removedInfo, true, pkg)) {
17883            // If the existing package wasn't successfully deleted
17884            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17885            deletedPkg = false;
17886        } else {
17887            // Successfully deleted the old package; proceed with replace.
17888
17889            // If deleted package lived in a container, give users a chance to
17890            // relinquish resources before killing.
17891            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17892                if (DEBUG_INSTALL) {
17893                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17894                }
17895                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17896                final ArrayList<String> pkgList = new ArrayList<String>(1);
17897                pkgList.add(deletedPackage.applicationInfo.packageName);
17898                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17899            }
17900
17901            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17902                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17903            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17904
17905            try {
17906                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17907                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17908                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17909                        installReason);
17910
17911                // Update the in-memory copy of the previous code paths.
17912                PackageSetting ps = mSettings.mPackages.get(pkgName);
17913                if (!killApp) {
17914                    if (ps.oldCodePaths == null) {
17915                        ps.oldCodePaths = new ArraySet<>();
17916                    }
17917                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17918                    if (deletedPackage.splitCodePaths != null) {
17919                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17920                    }
17921                } else {
17922                    ps.oldCodePaths = null;
17923                }
17924                if (ps.childPackageNames != null) {
17925                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17926                        final String childPkgName = ps.childPackageNames.get(i);
17927                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17928                        childPs.oldCodePaths = ps.oldCodePaths;
17929                    }
17930                }
17931                // set instant app status, but, only if it's explicitly specified
17932                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17933                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17934                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17935                prepareAppDataAfterInstallLIF(newPackage);
17936                addedPkg = true;
17937                mDexManager.notifyPackageUpdated(newPackage.packageName,
17938                        newPackage.baseCodePath, newPackage.splitCodePaths);
17939            } catch (PackageManagerException e) {
17940                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17941            }
17942        }
17943
17944        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17945            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17946
17947            // Revert all internal state mutations and added folders for the failed install
17948            if (addedPkg) {
17949                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17950                        res.removedInfo, true, null);
17951            }
17952
17953            // Restore the old package
17954            if (deletedPkg) {
17955                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17956                File restoreFile = new File(deletedPackage.codePath);
17957                // Parse old package
17958                boolean oldExternal = isExternal(deletedPackage);
17959                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17960                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17961                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17962                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17963                try {
17964                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17965                            null);
17966                } catch (PackageManagerException e) {
17967                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17968                            + e.getMessage());
17969                    return;
17970                }
17971
17972                synchronized (mPackages) {
17973                    // Ensure the installer package name up to date
17974                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17975
17976                    // Update permissions for restored package
17977                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17978
17979                    mSettings.writeLPr();
17980                }
17981
17982                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17983            }
17984        } else {
17985            synchronized (mPackages) {
17986                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17987                if (ps != null) {
17988                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17989                    if (res.removedInfo.removedChildPackages != null) {
17990                        final int childCount = res.removedInfo.removedChildPackages.size();
17991                        // Iterate in reverse as we may modify the collection
17992                        for (int i = childCount - 1; i >= 0; i--) {
17993                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17994                            if (res.addedChildPackages.containsKey(childPackageName)) {
17995                                res.removedInfo.removedChildPackages.removeAt(i);
17996                            } else {
17997                                PackageRemovedInfo childInfo = res.removedInfo
17998                                        .removedChildPackages.valueAt(i);
17999                                childInfo.removedForAllUsers = mPackages.get(
18000                                        childInfo.removedPackage) == null;
18001                            }
18002                        }
18003                    }
18004                }
18005            }
18006        }
18007    }
18008
18009    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
18010            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
18011            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
18012            int installReason) {
18013        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
18014                + ", old=" + deletedPackage);
18015
18016        final boolean disabledSystem;
18017
18018        // Remove existing system package
18019        removePackageLI(deletedPackage, true);
18020
18021        synchronized (mPackages) {
18022            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
18023        }
18024        if (!disabledSystem) {
18025            // We didn't need to disable the .apk as a current system package,
18026            // which means we are replacing another update that is already
18027            // installed.  We need to make sure to delete the older one's .apk.
18028            res.removedInfo.args = createInstallArgsForExisting(0,
18029                    deletedPackage.applicationInfo.getCodePath(),
18030                    deletedPackage.applicationInfo.getResourcePath(),
18031                    getAppDexInstructionSets(deletedPackage.applicationInfo));
18032        } else {
18033            res.removedInfo.args = null;
18034        }
18035
18036        // Successfully disabled the old package. Now proceed with re-installation
18037        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
18038                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18039        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
18040
18041        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18042        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
18043                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
18044
18045        PackageParser.Package newPackage = null;
18046        try {
18047            // Add the package to the internal data structures
18048            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
18049
18050            // Set the update and install times
18051            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
18052            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
18053                    System.currentTimeMillis());
18054
18055            // Update the package dynamic state if succeeded
18056            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18057                // Now that the install succeeded make sure we remove data
18058                // directories for any child package the update removed.
18059                final int deletedChildCount = (deletedPackage.childPackages != null)
18060                        ? deletedPackage.childPackages.size() : 0;
18061                final int newChildCount = (newPackage.childPackages != null)
18062                        ? newPackage.childPackages.size() : 0;
18063                for (int i = 0; i < deletedChildCount; i++) {
18064                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
18065                    boolean childPackageDeleted = true;
18066                    for (int j = 0; j < newChildCount; j++) {
18067                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
18068                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
18069                            childPackageDeleted = false;
18070                            break;
18071                        }
18072                    }
18073                    if (childPackageDeleted) {
18074                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
18075                                deletedChildPkg.packageName);
18076                        if (ps != null && res.removedInfo.removedChildPackages != null) {
18077                            PackageRemovedInfo removedChildRes = res.removedInfo
18078                                    .removedChildPackages.get(deletedChildPkg.packageName);
18079                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
18080                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
18081                        }
18082                    }
18083                }
18084
18085                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
18086                        installReason);
18087                prepareAppDataAfterInstallLIF(newPackage);
18088
18089                mDexManager.notifyPackageUpdated(newPackage.packageName,
18090                            newPackage.baseCodePath, newPackage.splitCodePaths);
18091            }
18092        } catch (PackageManagerException e) {
18093            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
18094            res.setError("Package couldn't be installed in " + pkg.codePath, e);
18095        }
18096
18097        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
18098            // Re installation failed. Restore old information
18099            // Remove new pkg information
18100            if (newPackage != null) {
18101                removeInstalledPackageLI(newPackage, true);
18102            }
18103            // Add back the old system package
18104            try {
18105                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
18106            } catch (PackageManagerException e) {
18107                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
18108            }
18109
18110            synchronized (mPackages) {
18111                if (disabledSystem) {
18112                    enableSystemPackageLPw(deletedPackage);
18113                }
18114
18115                // Ensure the installer package name up to date
18116                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
18117
18118                // Update permissions for restored package
18119                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
18120
18121                mSettings.writeLPr();
18122            }
18123
18124            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
18125                    + " after failed upgrade");
18126        }
18127    }
18128
18129    /**
18130     * Checks whether the parent or any of the child packages have a change shared
18131     * user. For a package to be a valid update the shred users of the parent and
18132     * the children should match. We may later support changing child shared users.
18133     * @param oldPkg The updated package.
18134     * @param newPkg The update package.
18135     * @return The shared user that change between the versions.
18136     */
18137    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
18138            PackageParser.Package newPkg) {
18139        // Check parent shared user
18140        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
18141            return newPkg.packageName;
18142        }
18143        // Check child shared users
18144        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18145        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
18146        for (int i = 0; i < newChildCount; i++) {
18147            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
18148            // If this child was present, did it have the same shared user?
18149            for (int j = 0; j < oldChildCount; j++) {
18150                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
18151                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
18152                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
18153                    return newChildPkg.packageName;
18154                }
18155            }
18156        }
18157        return null;
18158    }
18159
18160    private void removeNativeBinariesLI(PackageSetting ps) {
18161        // Remove the lib path for the parent package
18162        if (ps != null) {
18163            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
18164            // Remove the lib path for the child packages
18165            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18166            for (int i = 0; i < childCount; i++) {
18167                PackageSetting childPs = null;
18168                synchronized (mPackages) {
18169                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18170                }
18171                if (childPs != null) {
18172                    NativeLibraryHelper.removeNativeBinariesLI(childPs
18173                            .legacyNativeLibraryPathString);
18174                }
18175            }
18176        }
18177    }
18178
18179    private void enableSystemPackageLPw(PackageParser.Package pkg) {
18180        // Enable the parent package
18181        mSettings.enableSystemPackageLPw(pkg.packageName);
18182        // Enable the child packages
18183        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18184        for (int i = 0; i < childCount; i++) {
18185            PackageParser.Package childPkg = pkg.childPackages.get(i);
18186            mSettings.enableSystemPackageLPw(childPkg.packageName);
18187        }
18188    }
18189
18190    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
18191            PackageParser.Package newPkg) {
18192        // Disable the parent package (parent always replaced)
18193        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
18194        // Disable the child packages
18195        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18196        for (int i = 0; i < childCount; i++) {
18197            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
18198            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
18199            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
18200        }
18201        return disabled;
18202    }
18203
18204    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
18205            String installerPackageName) {
18206        // Enable the parent package
18207        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
18208        // Enable the child packages
18209        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18210        for (int i = 0; i < childCount; i++) {
18211            PackageParser.Package childPkg = pkg.childPackages.get(i);
18212            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
18213        }
18214    }
18215
18216    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
18217        // Collect all used permissions in the UID
18218        ArraySet<String> usedPermissions = new ArraySet<>();
18219        final int packageCount = su.packages.size();
18220        for (int i = 0; i < packageCount; i++) {
18221            PackageSetting ps = su.packages.valueAt(i);
18222            if (ps.pkg == null) {
18223                continue;
18224            }
18225            final int requestedPermCount = ps.pkg.requestedPermissions.size();
18226            for (int j = 0; j < requestedPermCount; j++) {
18227                String permission = ps.pkg.requestedPermissions.get(j);
18228                BasePermission bp = mSettings.mPermissions.get(permission);
18229                if (bp != null) {
18230                    usedPermissions.add(permission);
18231                }
18232            }
18233        }
18234
18235        PermissionsState permissionsState = su.getPermissionsState();
18236        // Prune install permissions
18237        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18238        final int installPermCount = installPermStates.size();
18239        for (int i = installPermCount - 1; i >= 0;  i--) {
18240            PermissionState permissionState = installPermStates.get(i);
18241            if (!usedPermissions.contains(permissionState.getName())) {
18242                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18243                if (bp != null) {
18244                    permissionsState.revokeInstallPermission(bp);
18245                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18246                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18247                }
18248            }
18249        }
18250
18251        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18252
18253        // Prune runtime permissions
18254        for (int userId : allUserIds) {
18255            List<PermissionState> runtimePermStates = permissionsState
18256                    .getRuntimePermissionStates(userId);
18257            final int runtimePermCount = runtimePermStates.size();
18258            for (int i = runtimePermCount - 1; i >= 0; i--) {
18259                PermissionState permissionState = runtimePermStates.get(i);
18260                if (!usedPermissions.contains(permissionState.getName())) {
18261                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18262                    if (bp != null) {
18263                        permissionsState.revokeRuntimePermission(bp, userId);
18264                        permissionsState.updatePermissionFlags(bp, userId,
18265                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18266                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18267                                runtimePermissionChangedUserIds, userId);
18268                    }
18269                }
18270            }
18271        }
18272
18273        return runtimePermissionChangedUserIds;
18274    }
18275
18276    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18277            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18278        // Update the parent package setting
18279        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18280                res, user, installReason);
18281        // Update the child packages setting
18282        final int childCount = (newPackage.childPackages != null)
18283                ? newPackage.childPackages.size() : 0;
18284        for (int i = 0; i < childCount; i++) {
18285            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18286            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18287            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18288                    childRes.origUsers, childRes, user, installReason);
18289        }
18290    }
18291
18292    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18293            String installerPackageName, int[] allUsers, int[] installedForUsers,
18294            PackageInstalledInfo res, UserHandle user, int installReason) {
18295        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18296
18297        String pkgName = newPackage.packageName;
18298        synchronized (mPackages) {
18299            //write settings. the installStatus will be incomplete at this stage.
18300            //note that the new package setting would have already been
18301            //added to mPackages. It hasn't been persisted yet.
18302            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18303            // TODO: Remove this write? It's also written at the end of this method
18304            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18305            mSettings.writeLPr();
18306            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18307        }
18308
18309        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18310        synchronized (mPackages) {
18311            updatePermissionsLPw(newPackage.packageName, newPackage,
18312                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18313                            ? UPDATE_PERMISSIONS_ALL : 0));
18314            // For system-bundled packages, we assume that installing an upgraded version
18315            // of the package implies that the user actually wants to run that new code,
18316            // so we enable the package.
18317            PackageSetting ps = mSettings.mPackages.get(pkgName);
18318            final int userId = user.getIdentifier();
18319            if (ps != null) {
18320                if (isSystemApp(newPackage)) {
18321                    if (DEBUG_INSTALL) {
18322                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18323                    }
18324                    // Enable system package for requested users
18325                    if (res.origUsers != null) {
18326                        for (int origUserId : res.origUsers) {
18327                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18328                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18329                                        origUserId, installerPackageName);
18330                            }
18331                        }
18332                    }
18333                    // Also convey the prior install/uninstall state
18334                    if (allUsers != null && installedForUsers != null) {
18335                        for (int currentUserId : allUsers) {
18336                            final boolean installed = ArrayUtils.contains(
18337                                    installedForUsers, currentUserId);
18338                            if (DEBUG_INSTALL) {
18339                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18340                            }
18341                            ps.setInstalled(installed, currentUserId);
18342                        }
18343                        // these install state changes will be persisted in the
18344                        // upcoming call to mSettings.writeLPr().
18345                    }
18346                }
18347                // It's implied that when a user requests installation, they want the app to be
18348                // installed and enabled.
18349                if (userId != UserHandle.USER_ALL) {
18350                    ps.setInstalled(true, userId);
18351                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18352                }
18353
18354                // When replacing an existing package, preserve the original install reason for all
18355                // users that had the package installed before.
18356                final Set<Integer> previousUserIds = new ArraySet<>();
18357                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18358                    final int installReasonCount = res.removedInfo.installReasons.size();
18359                    for (int i = 0; i < installReasonCount; i++) {
18360                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18361                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18362                        ps.setInstallReason(previousInstallReason, previousUserId);
18363                        previousUserIds.add(previousUserId);
18364                    }
18365                }
18366
18367                // Set install reason for users that are having the package newly installed.
18368                if (userId == UserHandle.USER_ALL) {
18369                    for (int currentUserId : sUserManager.getUserIds()) {
18370                        if (!previousUserIds.contains(currentUserId)) {
18371                            ps.setInstallReason(installReason, currentUserId);
18372                        }
18373                    }
18374                } else if (!previousUserIds.contains(userId)) {
18375                    ps.setInstallReason(installReason, userId);
18376                }
18377                mSettings.writeKernelMappingLPr(ps);
18378            }
18379            res.name = pkgName;
18380            res.uid = newPackage.applicationInfo.uid;
18381            res.pkg = newPackage;
18382            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18383            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18384            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18385            //to update install status
18386            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18387            mSettings.writeLPr();
18388            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18389        }
18390
18391        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18392    }
18393
18394    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18395        try {
18396            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18397            installPackageLI(args, res);
18398        } finally {
18399            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18400        }
18401    }
18402
18403    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18404        final int installFlags = args.installFlags;
18405        final String installerPackageName = args.installerPackageName;
18406        final String volumeUuid = args.volumeUuid;
18407        final File tmpPackageFile = new File(args.getCodePath());
18408        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18409        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18410                || (args.volumeUuid != null));
18411        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18412        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18413        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18414        final boolean virtualPreload =
18415                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18416        boolean replace = false;
18417        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18418        if (args.move != null) {
18419            // moving a complete application; perform an initial scan on the new install location
18420            scanFlags |= SCAN_INITIAL;
18421        }
18422        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18423            scanFlags |= SCAN_DONT_KILL_APP;
18424        }
18425        if (instantApp) {
18426            scanFlags |= SCAN_AS_INSTANT_APP;
18427        }
18428        if (fullApp) {
18429            scanFlags |= SCAN_AS_FULL_APP;
18430        }
18431        if (virtualPreload) {
18432            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18433        }
18434
18435        // Result object to be returned
18436        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18437        res.installerPackageName = installerPackageName;
18438
18439        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18440
18441        // Sanity check
18442        if (instantApp && (forwardLocked || onExternal)) {
18443            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18444                    + " external=" + onExternal);
18445            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18446            return;
18447        }
18448
18449        // Retrieve PackageSettings and parse package
18450        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18451                | PackageParser.PARSE_ENFORCE_CODE
18452                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18453                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18454                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18455                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18456        PackageParser pp = new PackageParser();
18457        pp.setSeparateProcesses(mSeparateProcesses);
18458        pp.setDisplayMetrics(mMetrics);
18459        pp.setCallback(mPackageParserCallback);
18460
18461        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18462        final PackageParser.Package pkg;
18463        try {
18464            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18465        } catch (PackageParserException e) {
18466            res.setError("Failed parse during installPackageLI", e);
18467            return;
18468        } finally {
18469            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18470        }
18471
18472        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18473        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18474            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18475            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18476                    "Instant app package must target O");
18477            return;
18478        }
18479        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18480            Slog.w(TAG, "Instant app package " + pkg.packageName
18481                    + " does not target targetSandboxVersion 2");
18482            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18483                    "Instant app package must use targetSanboxVersion 2");
18484            return;
18485        }
18486
18487        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18488            // Static shared libraries have synthetic package names
18489            renameStaticSharedLibraryPackage(pkg);
18490
18491            // No static shared libs on external storage
18492            if (onExternal) {
18493                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18494                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18495                        "Packages declaring static-shared libs cannot be updated");
18496                return;
18497            }
18498        }
18499
18500        // If we are installing a clustered package add results for the children
18501        if (pkg.childPackages != null) {
18502            synchronized (mPackages) {
18503                final int childCount = pkg.childPackages.size();
18504                for (int i = 0; i < childCount; i++) {
18505                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18506                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18507                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18508                    childRes.pkg = childPkg;
18509                    childRes.name = childPkg.packageName;
18510                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18511                    if (childPs != null) {
18512                        childRes.origUsers = childPs.queryInstalledUsers(
18513                                sUserManager.getUserIds(), true);
18514                    }
18515                    if ((mPackages.containsKey(childPkg.packageName))) {
18516                        childRes.removedInfo = new PackageRemovedInfo(this);
18517                        childRes.removedInfo.removedPackage = childPkg.packageName;
18518                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18519                    }
18520                    if (res.addedChildPackages == null) {
18521                        res.addedChildPackages = new ArrayMap<>();
18522                    }
18523                    res.addedChildPackages.put(childPkg.packageName, childRes);
18524                }
18525            }
18526        }
18527
18528        // If package doesn't declare API override, mark that we have an install
18529        // time CPU ABI override.
18530        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18531            pkg.cpuAbiOverride = args.abiOverride;
18532        }
18533
18534        String pkgName = res.name = pkg.packageName;
18535        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18536            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18537                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18538                return;
18539            }
18540        }
18541
18542        try {
18543            // either use what we've been given or parse directly from the APK
18544            if (args.certificates != null) {
18545                try {
18546                    PackageParser.populateCertificates(pkg, args.certificates);
18547                } catch (PackageParserException e) {
18548                    // there was something wrong with the certificates we were given;
18549                    // try to pull them from the APK
18550                    PackageParser.collectCertificates(pkg, parseFlags);
18551                }
18552            } else {
18553                PackageParser.collectCertificates(pkg, parseFlags);
18554            }
18555        } catch (PackageParserException e) {
18556            res.setError("Failed collect during installPackageLI", e);
18557            return;
18558        }
18559
18560        // Get rid of all references to package scan path via parser.
18561        pp = null;
18562        String oldCodePath = null;
18563        boolean systemApp = false;
18564        synchronized (mPackages) {
18565            // Check if installing already existing package
18566            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18567                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18568                if (pkg.mOriginalPackages != null
18569                        && pkg.mOriginalPackages.contains(oldName)
18570                        && mPackages.containsKey(oldName)) {
18571                    // This package is derived from an original package,
18572                    // and this device has been updating from that original
18573                    // name.  We must continue using the original name, so
18574                    // rename the new package here.
18575                    pkg.setPackageName(oldName);
18576                    pkgName = pkg.packageName;
18577                    replace = true;
18578                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18579                            + oldName + " pkgName=" + pkgName);
18580                } else if (mPackages.containsKey(pkgName)) {
18581                    // This package, under its official name, already exists
18582                    // on the device; we should replace it.
18583                    replace = true;
18584                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18585                }
18586
18587                // Child packages are installed through the parent package
18588                if (pkg.parentPackage != null) {
18589                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18590                            "Package " + pkg.packageName + " is child of package "
18591                                    + pkg.parentPackage.parentPackage + ". Child packages "
18592                                    + "can be updated only through the parent package.");
18593                    return;
18594                }
18595
18596                if (replace) {
18597                    // Prevent apps opting out from runtime permissions
18598                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18599                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18600                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18601                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18602                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18603                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18604                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18605                                        + " doesn't support runtime permissions but the old"
18606                                        + " target SDK " + oldTargetSdk + " does.");
18607                        return;
18608                    }
18609                    // Prevent persistent apps from being updated
18610                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
18611                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
18612                                "Package " + oldPackage.packageName + " is a persistent app. "
18613                                        + "Persistent apps are not updateable.");
18614                        return;
18615                    }
18616                    // Prevent apps from downgrading their targetSandbox.
18617                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18618                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18619                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18620                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18621                                "Package " + pkg.packageName + " new target sandbox "
18622                                + newTargetSandbox + " is incompatible with the previous value of"
18623                                + oldTargetSandbox + ".");
18624                        return;
18625                    }
18626
18627                    // Prevent installing of child packages
18628                    if (oldPackage.parentPackage != null) {
18629                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18630                                "Package " + pkg.packageName + " is child of package "
18631                                        + oldPackage.parentPackage + ". Child packages "
18632                                        + "can be updated only through the parent package.");
18633                        return;
18634                    }
18635                }
18636            }
18637
18638            PackageSetting ps = mSettings.mPackages.get(pkgName);
18639            if (ps != null) {
18640                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18641
18642                // Static shared libs have same package with different versions where
18643                // we internally use a synthetic package name to allow multiple versions
18644                // of the same package, therefore we need to compare signatures against
18645                // the package setting for the latest library version.
18646                PackageSetting signatureCheckPs = ps;
18647                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18648                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18649                    if (libraryEntry != null) {
18650                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18651                    }
18652                }
18653
18654                // Quick sanity check that we're signed correctly if updating;
18655                // we'll check this again later when scanning, but we want to
18656                // bail early here before tripping over redefined permissions.
18657                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18658                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18659                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18660                                + pkg.packageName + " upgrade keys do not match the "
18661                                + "previously installed version");
18662                        return;
18663                    }
18664                } else {
18665                    try {
18666                        verifySignaturesLP(signatureCheckPs, pkg);
18667                    } catch (PackageManagerException e) {
18668                        res.setError(e.error, e.getMessage());
18669                        return;
18670                    }
18671                }
18672
18673                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18674                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18675                    systemApp = (ps.pkg.applicationInfo.flags &
18676                            ApplicationInfo.FLAG_SYSTEM) != 0;
18677                }
18678                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18679            }
18680
18681            int N = pkg.permissions.size();
18682            for (int i = N-1; i >= 0; i--) {
18683                PackageParser.Permission perm = pkg.permissions.get(i);
18684                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18685
18686                // Don't allow anyone but the system to define ephemeral permissions.
18687                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
18688                        && !systemApp) {
18689                    Slog.w(TAG, "Non-System package " + pkg.packageName
18690                            + " attempting to delcare ephemeral permission "
18691                            + perm.info.name + "; Removing ephemeral.");
18692                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
18693                }
18694                // Check whether the newly-scanned package wants to define an already-defined perm
18695                if (bp != null) {
18696                    // If the defining package is signed with our cert, it's okay.  This
18697                    // also includes the "updating the same package" case, of course.
18698                    // "updating same package" could also involve key-rotation.
18699                    final boolean sigsOk;
18700                    if (bp.sourcePackage.equals(pkg.packageName)
18701                            && (bp.packageSetting instanceof PackageSetting)
18702                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18703                                    scanFlags))) {
18704                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18705                    } else {
18706                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18707                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18708                    }
18709                    if (!sigsOk) {
18710                        // If the owning package is the system itself, we log but allow
18711                        // install to proceed; we fail the install on all other permission
18712                        // redefinitions.
18713                        if (!bp.sourcePackage.equals("android")) {
18714                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18715                                    + pkg.packageName + " attempting to redeclare permission "
18716                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18717                            res.origPermission = perm.info.name;
18718                            res.origPackage = bp.sourcePackage;
18719                            return;
18720                        } else {
18721                            Slog.w(TAG, "Package " + pkg.packageName
18722                                    + " attempting to redeclare system permission "
18723                                    + perm.info.name + "; ignoring new declaration");
18724                            pkg.permissions.remove(i);
18725                        }
18726                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18727                        // Prevent apps to change protection level to dangerous from any other
18728                        // type as this would allow a privilege escalation where an app adds a
18729                        // normal/signature permission in other app's group and later redefines
18730                        // it as dangerous leading to the group auto-grant.
18731                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18732                                == PermissionInfo.PROTECTION_DANGEROUS) {
18733                            if (bp != null && !bp.isRuntime()) {
18734                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18735                                        + "non-runtime permission " + perm.info.name
18736                                        + " to runtime; keeping old protection level");
18737                                perm.info.protectionLevel = bp.protectionLevel;
18738                            }
18739                        }
18740                    }
18741                }
18742            }
18743        }
18744
18745        if (systemApp) {
18746            if (onExternal) {
18747                // Abort update; system app can't be replaced with app on sdcard
18748                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18749                        "Cannot install updates to system apps on sdcard");
18750                return;
18751            } else if (instantApp) {
18752                // Abort update; system app can't be replaced with an instant app
18753                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18754                        "Cannot update a system app with an instant app");
18755                return;
18756            }
18757        }
18758
18759        if (args.move != null) {
18760            // We did an in-place move, so dex is ready to roll
18761            scanFlags |= SCAN_NO_DEX;
18762            scanFlags |= SCAN_MOVE;
18763
18764            synchronized (mPackages) {
18765                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18766                if (ps == null) {
18767                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18768                            "Missing settings for moved package " + pkgName);
18769                }
18770
18771                // We moved the entire application as-is, so bring over the
18772                // previously derived ABI information.
18773                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18774                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18775            }
18776
18777        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18778            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18779            scanFlags |= SCAN_NO_DEX;
18780
18781            try {
18782                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18783                    args.abiOverride : pkg.cpuAbiOverride);
18784                final boolean extractNativeLibs = !pkg.isLibrary();
18785                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18786                        extractNativeLibs, mAppLib32InstallDir);
18787            } catch (PackageManagerException pme) {
18788                Slog.e(TAG, "Error deriving application ABI", pme);
18789                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18790                return;
18791            }
18792
18793            // Shared libraries for the package need to be updated.
18794            synchronized (mPackages) {
18795                try {
18796                    updateSharedLibrariesLPr(pkg, null);
18797                } catch (PackageManagerException e) {
18798                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18799                }
18800            }
18801        }
18802
18803        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18804            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18805            return;
18806        }
18807
18808        if (!instantApp) {
18809            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18810        } else {
18811            if (DEBUG_DOMAIN_VERIFICATION) {
18812                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
18813            }
18814        }
18815
18816        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18817                "installPackageLI")) {
18818            if (replace) {
18819                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18820                    // Static libs have a synthetic package name containing the version
18821                    // and cannot be updated as an update would get a new package name,
18822                    // unless this is the exact same version code which is useful for
18823                    // development.
18824                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18825                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18826                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18827                                + "static-shared libs cannot be updated");
18828                        return;
18829                    }
18830                }
18831                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18832                        installerPackageName, res, args.installReason);
18833            } else {
18834                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18835                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18836            }
18837        }
18838
18839        // Check whether we need to dexopt the app.
18840        //
18841        // NOTE: it is IMPORTANT to call dexopt:
18842        //   - after doRename which will sync the package data from PackageParser.Package and its
18843        //     corresponding ApplicationInfo.
18844        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
18845        //     uid of the application (pkg.applicationInfo.uid).
18846        //     This update happens in place!
18847        //
18848        // We only need to dexopt if the package meets ALL of the following conditions:
18849        //   1) it is not forward locked.
18850        //   2) it is not on on an external ASEC container.
18851        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18852        //
18853        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18854        // complete, so we skip this step during installation. Instead, we'll take extra time
18855        // the first time the instant app starts. It's preferred to do it this way to provide
18856        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18857        // middle of running an instant app. The default behaviour can be overridden
18858        // via gservices.
18859        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
18860                && !forwardLocked
18861                && !pkg.applicationInfo.isExternalAsec()
18862                && (!instantApp || Global.getInt(mContext.getContentResolver(),
18863                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18864
18865        if (performDexopt) {
18866            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18867            // Do not run PackageDexOptimizer through the local performDexOpt
18868            // method because `pkg` may not be in `mPackages` yet.
18869            //
18870            // Also, don't fail application installs if the dexopt step fails.
18871            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18872                    REASON_INSTALL,
18873                    DexoptOptions.DEXOPT_BOOT_COMPLETE);
18874            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18875                    null /* instructionSets */,
18876                    getOrCreateCompilerPackageStats(pkg),
18877                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18878                    dexoptOptions);
18879            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18880        }
18881
18882        // Notify BackgroundDexOptService that the package has been changed.
18883        // If this is an update of a package which used to fail to compile,
18884        // BackgroundDexOptService will remove it from its blacklist.
18885        // TODO: Layering violation
18886        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18887
18888        synchronized (mPackages) {
18889            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18890            if (ps != null) {
18891                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18892                ps.setUpdateAvailable(false /*updateAvailable*/);
18893            }
18894
18895            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18896            for (int i = 0; i < childCount; i++) {
18897                PackageParser.Package childPkg = pkg.childPackages.get(i);
18898                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18899                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18900                if (childPs != null) {
18901                    childRes.newUsers = childPs.queryInstalledUsers(
18902                            sUserManager.getUserIds(), true);
18903                }
18904            }
18905
18906            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18907                updateSequenceNumberLP(ps, res.newUsers);
18908                updateInstantAppInstallerLocked(pkgName);
18909            }
18910        }
18911    }
18912
18913    private void startIntentFilterVerifications(int userId, boolean replacing,
18914            PackageParser.Package pkg) {
18915        if (mIntentFilterVerifierComponent == null) {
18916            Slog.w(TAG, "No IntentFilter verification will not be done as "
18917                    + "there is no IntentFilterVerifier available!");
18918            return;
18919        }
18920
18921        final int verifierUid = getPackageUid(
18922                mIntentFilterVerifierComponent.getPackageName(),
18923                MATCH_DEBUG_TRIAGED_MISSING,
18924                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18925
18926        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18927        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18928        mHandler.sendMessage(msg);
18929
18930        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18931        for (int i = 0; i < childCount; i++) {
18932            PackageParser.Package childPkg = pkg.childPackages.get(i);
18933            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18934            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18935            mHandler.sendMessage(msg);
18936        }
18937    }
18938
18939    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18940            PackageParser.Package pkg) {
18941        int size = pkg.activities.size();
18942        if (size == 0) {
18943            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18944                    "No activity, so no need to verify any IntentFilter!");
18945            return;
18946        }
18947
18948        final boolean hasDomainURLs = hasDomainURLs(pkg);
18949        if (!hasDomainURLs) {
18950            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18951                    "No domain URLs, so no need to verify any IntentFilter!");
18952            return;
18953        }
18954
18955        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18956                + " if any IntentFilter from the " + size
18957                + " Activities needs verification ...");
18958
18959        int count = 0;
18960        final String packageName = pkg.packageName;
18961
18962        synchronized (mPackages) {
18963            // If this is a new install and we see that we've already run verification for this
18964            // package, we have nothing to do: it means the state was restored from backup.
18965            if (!replacing) {
18966                IntentFilterVerificationInfo ivi =
18967                        mSettings.getIntentFilterVerificationLPr(packageName);
18968                if (ivi != null) {
18969                    if (DEBUG_DOMAIN_VERIFICATION) {
18970                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18971                                + ivi.getStatusString());
18972                    }
18973                    return;
18974                }
18975            }
18976
18977            // If any filters need to be verified, then all need to be.
18978            boolean needToVerify = false;
18979            for (PackageParser.Activity a : pkg.activities) {
18980                for (ActivityIntentInfo filter : a.intents) {
18981                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18982                        if (DEBUG_DOMAIN_VERIFICATION) {
18983                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18984                        }
18985                        needToVerify = true;
18986                        break;
18987                    }
18988                }
18989            }
18990
18991            if (needToVerify) {
18992                final int verificationId = mIntentFilterVerificationToken++;
18993                for (PackageParser.Activity a : pkg.activities) {
18994                    for (ActivityIntentInfo filter : a.intents) {
18995                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18996                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18997                                    "Verification needed for IntentFilter:" + filter.toString());
18998                            mIntentFilterVerifier.addOneIntentFilterVerification(
18999                                    verifierUid, userId, verificationId, filter, packageName);
19000                            count++;
19001                        }
19002                    }
19003                }
19004            }
19005        }
19006
19007        if (count > 0) {
19008            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
19009                    + " IntentFilter verification" + (count > 1 ? "s" : "")
19010                    +  " for userId:" + userId);
19011            mIntentFilterVerifier.startVerifications(userId);
19012        } else {
19013            if (DEBUG_DOMAIN_VERIFICATION) {
19014                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
19015            }
19016        }
19017    }
19018
19019    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
19020        final ComponentName cn  = filter.activity.getComponentName();
19021        final String packageName = cn.getPackageName();
19022
19023        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
19024                packageName);
19025        if (ivi == null) {
19026            return true;
19027        }
19028        int status = ivi.getStatus();
19029        switch (status) {
19030            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
19031            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
19032                return true;
19033
19034            default:
19035                // Nothing to do
19036                return false;
19037        }
19038    }
19039
19040    private static boolean isMultiArch(ApplicationInfo info) {
19041        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
19042    }
19043
19044    private static boolean isExternal(PackageParser.Package pkg) {
19045        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
19046    }
19047
19048    private static boolean isExternal(PackageSetting ps) {
19049        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
19050    }
19051
19052    private static boolean isSystemApp(PackageParser.Package pkg) {
19053        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
19054    }
19055
19056    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
19057        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
19058    }
19059
19060    private static boolean hasDomainURLs(PackageParser.Package pkg) {
19061        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
19062    }
19063
19064    private static boolean isSystemApp(PackageSetting ps) {
19065        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
19066    }
19067
19068    private static boolean isUpdatedSystemApp(PackageSetting ps) {
19069        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
19070    }
19071
19072    private int packageFlagsToInstallFlags(PackageSetting ps) {
19073        int installFlags = 0;
19074        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
19075            // This existing package was an external ASEC install when we have
19076            // the external flag without a UUID
19077            installFlags |= PackageManager.INSTALL_EXTERNAL;
19078        }
19079        if (ps.isForwardLocked()) {
19080            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
19081        }
19082        return installFlags;
19083    }
19084
19085    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
19086        if (isExternal(pkg)) {
19087            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19088                return StorageManager.UUID_PRIMARY_PHYSICAL;
19089            } else {
19090                return pkg.volumeUuid;
19091            }
19092        } else {
19093            return StorageManager.UUID_PRIVATE_INTERNAL;
19094        }
19095    }
19096
19097    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
19098        if (isExternal(pkg)) {
19099            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19100                return mSettings.getExternalVersion();
19101            } else {
19102                return mSettings.findOrCreateVersion(pkg.volumeUuid);
19103            }
19104        } else {
19105            return mSettings.getInternalVersion();
19106        }
19107    }
19108
19109    private void deleteTempPackageFiles() {
19110        final FilenameFilter filter = new FilenameFilter() {
19111            public boolean accept(File dir, String name) {
19112                return name.startsWith("vmdl") && name.endsWith(".tmp");
19113            }
19114        };
19115        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
19116            file.delete();
19117        }
19118    }
19119
19120    @Override
19121    public void deletePackageAsUser(String packageName, int versionCode,
19122            IPackageDeleteObserver observer, int userId, int flags) {
19123        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
19124                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
19125    }
19126
19127    @Override
19128    public void deletePackageVersioned(VersionedPackage versionedPackage,
19129            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
19130        final int callingUid = Binder.getCallingUid();
19131        mContext.enforceCallingOrSelfPermission(
19132                android.Manifest.permission.DELETE_PACKAGES, null);
19133        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
19134        Preconditions.checkNotNull(versionedPackage);
19135        Preconditions.checkNotNull(observer);
19136        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
19137                PackageManager.VERSION_CODE_HIGHEST,
19138                Integer.MAX_VALUE, "versionCode must be >= -1");
19139
19140        final String packageName = versionedPackage.getPackageName();
19141        final int versionCode = versionedPackage.getVersionCode();
19142        final String internalPackageName;
19143        synchronized (mPackages) {
19144            // Normalize package name to handle renamed packages and static libs
19145            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
19146                    versionedPackage.getVersionCode());
19147        }
19148
19149        final int uid = Binder.getCallingUid();
19150        if (!isOrphaned(internalPackageName)
19151                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
19152            try {
19153                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
19154                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
19155                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
19156                observer.onUserActionRequired(intent);
19157            } catch (RemoteException re) {
19158            }
19159            return;
19160        }
19161        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
19162        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
19163        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
19164            mContext.enforceCallingOrSelfPermission(
19165                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
19166                    "deletePackage for user " + userId);
19167        }
19168
19169        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
19170            try {
19171                observer.onPackageDeleted(packageName,
19172                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
19173            } catch (RemoteException re) {
19174            }
19175            return;
19176        }
19177
19178        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
19179            try {
19180                observer.onPackageDeleted(packageName,
19181                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
19182            } catch (RemoteException re) {
19183            }
19184            return;
19185        }
19186
19187        if (DEBUG_REMOVE) {
19188            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
19189                    + " deleteAllUsers: " + deleteAllUsers + " version="
19190                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
19191                    ? "VERSION_CODE_HIGHEST" : versionCode));
19192        }
19193        // Queue up an async operation since the package deletion may take a little while.
19194        mHandler.post(new Runnable() {
19195            public void run() {
19196                mHandler.removeCallbacks(this);
19197                int returnCode;
19198                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
19199                boolean doDeletePackage = true;
19200                if (ps != null) {
19201                    final boolean targetIsInstantApp =
19202                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19203                    doDeletePackage = !targetIsInstantApp
19204                            || canViewInstantApps;
19205                }
19206                if (doDeletePackage) {
19207                    if (!deleteAllUsers) {
19208                        returnCode = deletePackageX(internalPackageName, versionCode,
19209                                userId, deleteFlags);
19210                    } else {
19211                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
19212                                internalPackageName, users);
19213                        // If nobody is blocking uninstall, proceed with delete for all users
19214                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
19215                            returnCode = deletePackageX(internalPackageName, versionCode,
19216                                    userId, deleteFlags);
19217                        } else {
19218                            // Otherwise uninstall individually for users with blockUninstalls=false
19219                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
19220                            for (int userId : users) {
19221                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
19222                                    returnCode = deletePackageX(internalPackageName, versionCode,
19223                                            userId, userFlags);
19224                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
19225                                        Slog.w(TAG, "Package delete failed for user " + userId
19226                                                + ", returnCode " + returnCode);
19227                                    }
19228                                }
19229                            }
19230                            // The app has only been marked uninstalled for certain users.
19231                            // We still need to report that delete was blocked
19232                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
19233                        }
19234                    }
19235                } else {
19236                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19237                }
19238                try {
19239                    observer.onPackageDeleted(packageName, returnCode, null);
19240                } catch (RemoteException e) {
19241                    Log.i(TAG, "Observer no longer exists.");
19242                } //end catch
19243            } //end run
19244        });
19245    }
19246
19247    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
19248        if (pkg.staticSharedLibName != null) {
19249            return pkg.manifestPackageName;
19250        }
19251        return pkg.packageName;
19252    }
19253
19254    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
19255        // Handle renamed packages
19256        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
19257        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
19258
19259        // Is this a static library?
19260        SparseArray<SharedLibraryEntry> versionedLib =
19261                mStaticLibsByDeclaringPackage.get(packageName);
19262        if (versionedLib == null || versionedLib.size() <= 0) {
19263            return packageName;
19264        }
19265
19266        // Figure out which lib versions the caller can see
19267        SparseIntArray versionsCallerCanSee = null;
19268        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19269        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19270                && callingAppId != Process.ROOT_UID) {
19271            versionsCallerCanSee = new SparseIntArray();
19272            String libName = versionedLib.valueAt(0).info.getName();
19273            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19274            if (uidPackages != null) {
19275                for (String uidPackage : uidPackages) {
19276                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19277                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19278                    if (libIdx >= 0) {
19279                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19280                        versionsCallerCanSee.append(libVersion, libVersion);
19281                    }
19282                }
19283            }
19284        }
19285
19286        // Caller can see nothing - done
19287        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19288            return packageName;
19289        }
19290
19291        // Find the version the caller can see and the app version code
19292        SharedLibraryEntry highestVersion = null;
19293        final int versionCount = versionedLib.size();
19294        for (int i = 0; i < versionCount; i++) {
19295            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19296            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19297                    libEntry.info.getVersion()) < 0) {
19298                continue;
19299            }
19300            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19301            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19302                if (libVersionCode == versionCode) {
19303                    return libEntry.apk;
19304                }
19305            } else if (highestVersion == null) {
19306                highestVersion = libEntry;
19307            } else if (libVersionCode  > highestVersion.info
19308                    .getDeclaringPackage().getVersionCode()) {
19309                highestVersion = libEntry;
19310            }
19311        }
19312
19313        if (highestVersion != null) {
19314            return highestVersion.apk;
19315        }
19316
19317        return packageName;
19318    }
19319
19320    boolean isCallerVerifier(int callingUid) {
19321        final int callingUserId = UserHandle.getUserId(callingUid);
19322        return mRequiredVerifierPackage != null &&
19323                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19324    }
19325
19326    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19327        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19328              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19329            return true;
19330        }
19331        final int callingUserId = UserHandle.getUserId(callingUid);
19332        // If the caller installed the pkgName, then allow it to silently uninstall.
19333        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19334            return true;
19335        }
19336
19337        // Allow package verifier to silently uninstall.
19338        if (mRequiredVerifierPackage != null &&
19339                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19340            return true;
19341        }
19342
19343        // Allow package uninstaller to silently uninstall.
19344        if (mRequiredUninstallerPackage != null &&
19345                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19346            return true;
19347        }
19348
19349        // Allow storage manager to silently uninstall.
19350        if (mStorageManagerPackage != null &&
19351                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19352            return true;
19353        }
19354
19355        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19356        // uninstall for device owner provisioning.
19357        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19358                == PERMISSION_GRANTED) {
19359            return true;
19360        }
19361
19362        return false;
19363    }
19364
19365    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19366        int[] result = EMPTY_INT_ARRAY;
19367        for (int userId : userIds) {
19368            if (getBlockUninstallForUser(packageName, userId)) {
19369                result = ArrayUtils.appendInt(result, userId);
19370            }
19371        }
19372        return result;
19373    }
19374
19375    @Override
19376    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19377        final int callingUid = Binder.getCallingUid();
19378        if (getInstantAppPackageName(callingUid) != null
19379                && !isCallerSameApp(packageName, callingUid)) {
19380            return false;
19381        }
19382        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19383    }
19384
19385    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19386        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19387                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19388        try {
19389            if (dpm != null) {
19390                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19391                        /* callingUserOnly =*/ false);
19392                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19393                        : deviceOwnerComponentName.getPackageName();
19394                // Does the package contains the device owner?
19395                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19396                // this check is probably not needed, since DO should be registered as a device
19397                // admin on some user too. (Original bug for this: b/17657954)
19398                if (packageName.equals(deviceOwnerPackageName)) {
19399                    return true;
19400                }
19401                // Does it contain a device admin for any user?
19402                int[] users;
19403                if (userId == UserHandle.USER_ALL) {
19404                    users = sUserManager.getUserIds();
19405                } else {
19406                    users = new int[]{userId};
19407                }
19408                for (int i = 0; i < users.length; ++i) {
19409                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19410                        return true;
19411                    }
19412                }
19413            }
19414        } catch (RemoteException e) {
19415        }
19416        return false;
19417    }
19418
19419    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19420        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19421    }
19422
19423    /**
19424     *  This method is an internal method that could be get invoked either
19425     *  to delete an installed package or to clean up a failed installation.
19426     *  After deleting an installed package, a broadcast is sent to notify any
19427     *  listeners that the package has been removed. For cleaning up a failed
19428     *  installation, the broadcast is not necessary since the package's
19429     *  installation wouldn't have sent the initial broadcast either
19430     *  The key steps in deleting a package are
19431     *  deleting the package information in internal structures like mPackages,
19432     *  deleting the packages base directories through installd
19433     *  updating mSettings to reflect current status
19434     *  persisting settings for later use
19435     *  sending a broadcast if necessary
19436     */
19437    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19438        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19439        final boolean res;
19440
19441        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19442                ? UserHandle.USER_ALL : userId;
19443
19444        if (isPackageDeviceAdmin(packageName, removeUser)) {
19445            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19446            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19447        }
19448
19449        PackageSetting uninstalledPs = null;
19450        PackageParser.Package pkg = null;
19451
19452        // for the uninstall-updates case and restricted profiles, remember the per-
19453        // user handle installed state
19454        int[] allUsers;
19455        synchronized (mPackages) {
19456            uninstalledPs = mSettings.mPackages.get(packageName);
19457            if (uninstalledPs == null) {
19458                Slog.w(TAG, "Not removing non-existent package " + packageName);
19459                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19460            }
19461
19462            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19463                    && uninstalledPs.versionCode != versionCode) {
19464                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19465                        + uninstalledPs.versionCode + " != " + versionCode);
19466                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19467            }
19468
19469            // Static shared libs can be declared by any package, so let us not
19470            // allow removing a package if it provides a lib others depend on.
19471            pkg = mPackages.get(packageName);
19472
19473            allUsers = sUserManager.getUserIds();
19474
19475            if (pkg != null && pkg.staticSharedLibName != null) {
19476                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19477                        pkg.staticSharedLibVersion);
19478                if (libEntry != null) {
19479                    for (int currUserId : allUsers) {
19480                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19481                            continue;
19482                        }
19483                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19484                                libEntry.info, 0, currUserId);
19485                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19486                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19487                                    + " hosting lib " + libEntry.info.getName() + " version "
19488                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19489                                    + " for user " + currUserId);
19490                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19491                        }
19492                    }
19493                }
19494            }
19495
19496            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19497        }
19498
19499        final int freezeUser;
19500        if (isUpdatedSystemApp(uninstalledPs)
19501                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19502            // We're downgrading a system app, which will apply to all users, so
19503            // freeze them all during the downgrade
19504            freezeUser = UserHandle.USER_ALL;
19505        } else {
19506            freezeUser = removeUser;
19507        }
19508
19509        synchronized (mInstallLock) {
19510            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19511            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19512                    deleteFlags, "deletePackageX")) {
19513                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19514                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19515            }
19516            synchronized (mPackages) {
19517                if (res) {
19518                    if (pkg != null) {
19519                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19520                    }
19521                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19522                    updateInstantAppInstallerLocked(packageName);
19523                }
19524            }
19525        }
19526
19527        if (res) {
19528            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19529            info.sendPackageRemovedBroadcasts(killApp);
19530            info.sendSystemPackageUpdatedBroadcasts();
19531            info.sendSystemPackageAppearedBroadcasts();
19532        }
19533        // Force a gc here.
19534        Runtime.getRuntime().gc();
19535        // Delete the resources here after sending the broadcast to let
19536        // other processes clean up before deleting resources.
19537        if (info.args != null) {
19538            synchronized (mInstallLock) {
19539                info.args.doPostDeleteLI(true);
19540            }
19541        }
19542
19543        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19544    }
19545
19546    static class PackageRemovedInfo {
19547        final PackageSender packageSender;
19548        String removedPackage;
19549        String installerPackageName;
19550        int uid = -1;
19551        int removedAppId = -1;
19552        int[] origUsers;
19553        int[] removedUsers = null;
19554        int[] broadcastUsers = null;
19555        SparseArray<Integer> installReasons;
19556        boolean isRemovedPackageSystemUpdate = false;
19557        boolean isUpdate;
19558        boolean dataRemoved;
19559        boolean removedForAllUsers;
19560        boolean isStaticSharedLib;
19561        // Clean up resources deleted packages.
19562        InstallArgs args = null;
19563        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19564        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19565
19566        PackageRemovedInfo(PackageSender packageSender) {
19567            this.packageSender = packageSender;
19568        }
19569
19570        void sendPackageRemovedBroadcasts(boolean killApp) {
19571            sendPackageRemovedBroadcastInternal(killApp);
19572            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19573            for (int i = 0; i < childCount; i++) {
19574                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19575                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19576            }
19577        }
19578
19579        void sendSystemPackageUpdatedBroadcasts() {
19580            if (isRemovedPackageSystemUpdate) {
19581                sendSystemPackageUpdatedBroadcastsInternal();
19582                final int childCount = (removedChildPackages != null)
19583                        ? removedChildPackages.size() : 0;
19584                for (int i = 0; i < childCount; i++) {
19585                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19586                    if (childInfo.isRemovedPackageSystemUpdate) {
19587                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19588                    }
19589                }
19590            }
19591        }
19592
19593        void sendSystemPackageAppearedBroadcasts() {
19594            final int packageCount = (appearedChildPackages != null)
19595                    ? appearedChildPackages.size() : 0;
19596            for (int i = 0; i < packageCount; i++) {
19597                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19598                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19599                    true /*sendBootCompleted*/, false /*startReceiver*/,
19600                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19601            }
19602        }
19603
19604        private void sendSystemPackageUpdatedBroadcastsInternal() {
19605            Bundle extras = new Bundle(2);
19606            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19607            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19608            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19609                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19610            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19611                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19612            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19613                null, null, 0, removedPackage, null, null);
19614            if (installerPackageName != null) {
19615                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19616                        removedPackage, extras, 0 /*flags*/,
19617                        installerPackageName, null, null);
19618                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19619                        removedPackage, extras, 0 /*flags*/,
19620                        installerPackageName, null, null);
19621            }
19622        }
19623
19624        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19625            // Don't send static shared library removal broadcasts as these
19626            // libs are visible only the the apps that depend on them an one
19627            // cannot remove the library if it has a dependency.
19628            if (isStaticSharedLib) {
19629                return;
19630            }
19631            Bundle extras = new Bundle(2);
19632            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19633            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19634            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19635            if (isUpdate || isRemovedPackageSystemUpdate) {
19636                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19637            }
19638            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19639            if (removedPackage != null) {
19640                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19641                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19642                if (installerPackageName != null) {
19643                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19644                            removedPackage, extras, 0 /*flags*/,
19645                            installerPackageName, null, broadcastUsers);
19646                }
19647                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19648                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19649                        removedPackage, extras,
19650                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19651                        null, null, broadcastUsers);
19652                }
19653            }
19654            if (removedAppId >= 0) {
19655                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19656                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19657                    null, null, broadcastUsers);
19658            }
19659        }
19660
19661        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19662            removedUsers = userIds;
19663            if (removedUsers == null) {
19664                broadcastUsers = null;
19665                return;
19666            }
19667
19668            broadcastUsers = EMPTY_INT_ARRAY;
19669            for (int i = userIds.length - 1; i >= 0; --i) {
19670                final int userId = userIds[i];
19671                if (deletedPackageSetting.getInstantApp(userId)) {
19672                    continue;
19673                }
19674                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19675            }
19676        }
19677    }
19678
19679    /*
19680     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19681     * flag is not set, the data directory is removed as well.
19682     * make sure this flag is set for partially installed apps. If not its meaningless to
19683     * delete a partially installed application.
19684     */
19685    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19686            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19687        String packageName = ps.name;
19688        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19689        // Retrieve object to delete permissions for shared user later on
19690        final PackageParser.Package deletedPkg;
19691        final PackageSetting deletedPs;
19692        // reader
19693        synchronized (mPackages) {
19694            deletedPkg = mPackages.get(packageName);
19695            deletedPs = mSettings.mPackages.get(packageName);
19696            if (outInfo != null) {
19697                outInfo.removedPackage = packageName;
19698                outInfo.installerPackageName = ps.installerPackageName;
19699                outInfo.isStaticSharedLib = deletedPkg != null
19700                        && deletedPkg.staticSharedLibName != null;
19701                outInfo.populateUsers(deletedPs == null ? null
19702                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19703            }
19704        }
19705
19706        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19707
19708        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19709            final PackageParser.Package resolvedPkg;
19710            if (deletedPkg != null) {
19711                resolvedPkg = deletedPkg;
19712            } else {
19713                // We don't have a parsed package when it lives on an ejected
19714                // adopted storage device, so fake something together
19715                resolvedPkg = new PackageParser.Package(ps.name);
19716                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19717            }
19718            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19719                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19720            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19721            if (outInfo != null) {
19722                outInfo.dataRemoved = true;
19723            }
19724            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19725        }
19726
19727        int removedAppId = -1;
19728
19729        // writer
19730        synchronized (mPackages) {
19731            boolean installedStateChanged = false;
19732            if (deletedPs != null) {
19733                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19734                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19735                    clearDefaultBrowserIfNeeded(packageName);
19736                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19737                    removedAppId = mSettings.removePackageLPw(packageName);
19738                    if (outInfo != null) {
19739                        outInfo.removedAppId = removedAppId;
19740                    }
19741                    updatePermissionsLPw(deletedPs.name, null, 0);
19742                    if (deletedPs.sharedUser != null) {
19743                        // Remove permissions associated with package. Since runtime
19744                        // permissions are per user we have to kill the removed package
19745                        // or packages running under the shared user of the removed
19746                        // package if revoking the permissions requested only by the removed
19747                        // package is successful and this causes a change in gids.
19748                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19749                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19750                                    userId);
19751                            if (userIdToKill == UserHandle.USER_ALL
19752                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19753                                // If gids changed for this user, kill all affected packages.
19754                                mHandler.post(new Runnable() {
19755                                    @Override
19756                                    public void run() {
19757                                        // This has to happen with no lock held.
19758                                        killApplication(deletedPs.name, deletedPs.appId,
19759                                                KILL_APP_REASON_GIDS_CHANGED);
19760                                    }
19761                                });
19762                                break;
19763                            }
19764                        }
19765                    }
19766                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19767                }
19768                // make sure to preserve per-user disabled state if this removal was just
19769                // a downgrade of a system app to the factory package
19770                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19771                    if (DEBUG_REMOVE) {
19772                        Slog.d(TAG, "Propagating install state across downgrade");
19773                    }
19774                    for (int userId : allUserHandles) {
19775                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19776                        if (DEBUG_REMOVE) {
19777                            Slog.d(TAG, "    user " + userId + " => " + installed);
19778                        }
19779                        if (installed != ps.getInstalled(userId)) {
19780                            installedStateChanged = true;
19781                        }
19782                        ps.setInstalled(installed, userId);
19783                    }
19784                }
19785            }
19786            // can downgrade to reader
19787            if (writeSettings) {
19788                // Save settings now
19789                mSettings.writeLPr();
19790            }
19791            if (installedStateChanged) {
19792                mSettings.writeKernelMappingLPr(ps);
19793            }
19794        }
19795        if (removedAppId != -1) {
19796            // A user ID was deleted here. Go through all users and remove it
19797            // from KeyStore.
19798            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19799        }
19800    }
19801
19802    static boolean locationIsPrivileged(File path) {
19803        try {
19804            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19805                    .getCanonicalPath();
19806            return path.getCanonicalPath().startsWith(privilegedAppDir);
19807        } catch (IOException e) {
19808            Slog.e(TAG, "Unable to access code path " + path);
19809        }
19810        return false;
19811    }
19812
19813    /*
19814     * Tries to delete system package.
19815     */
19816    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19817            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19818            boolean writeSettings) {
19819        if (deletedPs.parentPackageName != null) {
19820            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19821            return false;
19822        }
19823
19824        final boolean applyUserRestrictions
19825                = (allUserHandles != null) && (outInfo.origUsers != null);
19826        final PackageSetting disabledPs;
19827        // Confirm if the system package has been updated
19828        // An updated system app can be deleted. This will also have to restore
19829        // the system pkg from system partition
19830        // reader
19831        synchronized (mPackages) {
19832            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19833        }
19834
19835        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19836                + " disabledPs=" + disabledPs);
19837
19838        if (disabledPs == null) {
19839            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19840            return false;
19841        } else if (DEBUG_REMOVE) {
19842            Slog.d(TAG, "Deleting system pkg from data partition");
19843        }
19844
19845        if (DEBUG_REMOVE) {
19846            if (applyUserRestrictions) {
19847                Slog.d(TAG, "Remembering install states:");
19848                for (int userId : allUserHandles) {
19849                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19850                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19851                }
19852            }
19853        }
19854
19855        // Delete the updated package
19856        outInfo.isRemovedPackageSystemUpdate = true;
19857        if (outInfo.removedChildPackages != null) {
19858            final int childCount = (deletedPs.childPackageNames != null)
19859                    ? deletedPs.childPackageNames.size() : 0;
19860            for (int i = 0; i < childCount; i++) {
19861                String childPackageName = deletedPs.childPackageNames.get(i);
19862                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19863                        .contains(childPackageName)) {
19864                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19865                            childPackageName);
19866                    if (childInfo != null) {
19867                        childInfo.isRemovedPackageSystemUpdate = true;
19868                    }
19869                }
19870            }
19871        }
19872
19873        if (disabledPs.versionCode < deletedPs.versionCode) {
19874            // Delete data for downgrades
19875            flags &= ~PackageManager.DELETE_KEEP_DATA;
19876        } else {
19877            // Preserve data by setting flag
19878            flags |= PackageManager.DELETE_KEEP_DATA;
19879        }
19880
19881        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19882                outInfo, writeSettings, disabledPs.pkg);
19883        if (!ret) {
19884            return false;
19885        }
19886
19887        // writer
19888        synchronized (mPackages) {
19889            // NOTE: The system package always needs to be enabled; even if it's for
19890            // a compressed stub. If we don't, installing the system package fails
19891            // during scan [scanning checks the disabled packages]. We will reverse
19892            // this later, after we've "installed" the stub.
19893            // Reinstate the old system package
19894            enableSystemPackageLPw(disabledPs.pkg);
19895            // Remove any native libraries from the upgraded package.
19896            removeNativeBinariesLI(deletedPs);
19897        }
19898
19899        // Install the system package
19900        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19901        try {
19902            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
19903                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
19904        } catch (PackageManagerException e) {
19905            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19906                    + e.getMessage());
19907            return false;
19908        } finally {
19909            if (disabledPs.pkg.isStub) {
19910                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
19911            }
19912        }
19913        return true;
19914    }
19915
19916    /**
19917     * Installs a package that's already on the system partition.
19918     */
19919    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
19920            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
19921            @Nullable PermissionsState origPermissionState, boolean writeSettings)
19922                    throws PackageManagerException {
19923        int parseFlags = mDefParseFlags
19924                | PackageParser.PARSE_MUST_BE_APK
19925                | PackageParser.PARSE_IS_SYSTEM
19926                | PackageParser.PARSE_IS_SYSTEM_DIR;
19927        if (isPrivileged || locationIsPrivileged(codePath)) {
19928            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19929        }
19930
19931        final PackageParser.Package newPkg =
19932                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
19933
19934        try {
19935            // update shared libraries for the newly re-installed system package
19936            updateSharedLibrariesLPr(newPkg, null);
19937        } catch (PackageManagerException e) {
19938            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19939        }
19940
19941        prepareAppDataAfterInstallLIF(newPkg);
19942
19943        // writer
19944        synchronized (mPackages) {
19945            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19946
19947            // Propagate the permissions state as we do not want to drop on the floor
19948            // runtime permissions. The update permissions method below will take
19949            // care of removing obsolete permissions and grant install permissions.
19950            if (origPermissionState != null) {
19951                ps.getPermissionsState().copyFrom(origPermissionState);
19952            }
19953            updatePermissionsLPw(newPkg.packageName, newPkg,
19954                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19955
19956            final boolean applyUserRestrictions
19957                    = (allUserHandles != null) && (origUserHandles != null);
19958            if (applyUserRestrictions) {
19959                boolean installedStateChanged = false;
19960                if (DEBUG_REMOVE) {
19961                    Slog.d(TAG, "Propagating install state across reinstall");
19962                }
19963                for (int userId : allUserHandles) {
19964                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
19965                    if (DEBUG_REMOVE) {
19966                        Slog.d(TAG, "    user " + userId + " => " + installed);
19967                    }
19968                    if (installed != ps.getInstalled(userId)) {
19969                        installedStateChanged = true;
19970                    }
19971                    ps.setInstalled(installed, userId);
19972
19973                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19974                }
19975                // Regardless of writeSettings we need to ensure that this restriction
19976                // state propagation is persisted
19977                mSettings.writeAllUsersPackageRestrictionsLPr();
19978                if (installedStateChanged) {
19979                    mSettings.writeKernelMappingLPr(ps);
19980                }
19981            }
19982            // can downgrade to reader here
19983            if (writeSettings) {
19984                mSettings.writeLPr();
19985            }
19986        }
19987        return newPkg;
19988    }
19989
19990    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19991            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19992            PackageRemovedInfo outInfo, boolean writeSettings,
19993            PackageParser.Package replacingPackage) {
19994        synchronized (mPackages) {
19995            if (outInfo != null) {
19996                outInfo.uid = ps.appId;
19997            }
19998
19999            if (outInfo != null && outInfo.removedChildPackages != null) {
20000                final int childCount = (ps.childPackageNames != null)
20001                        ? ps.childPackageNames.size() : 0;
20002                for (int i = 0; i < childCount; i++) {
20003                    String childPackageName = ps.childPackageNames.get(i);
20004                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
20005                    if (childPs == null) {
20006                        return false;
20007                    }
20008                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
20009                            childPackageName);
20010                    if (childInfo != null) {
20011                        childInfo.uid = childPs.appId;
20012                    }
20013                }
20014            }
20015        }
20016
20017        // Delete package data from internal structures and also remove data if flag is set
20018        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
20019
20020        // Delete the child packages data
20021        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
20022        for (int i = 0; i < childCount; i++) {
20023            PackageSetting childPs;
20024            synchronized (mPackages) {
20025                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
20026            }
20027            if (childPs != null) {
20028                PackageRemovedInfo childOutInfo = (outInfo != null
20029                        && outInfo.removedChildPackages != null)
20030                        ? outInfo.removedChildPackages.get(childPs.name) : null;
20031                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
20032                        && (replacingPackage != null
20033                        && !replacingPackage.hasChildPackage(childPs.name))
20034                        ? flags & ~DELETE_KEEP_DATA : flags;
20035                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
20036                        deleteFlags, writeSettings);
20037            }
20038        }
20039
20040        // Delete application code and resources only for parent packages
20041        if (ps.parentPackageName == null) {
20042            if (deleteCodeAndResources && (outInfo != null)) {
20043                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
20044                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
20045                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
20046            }
20047        }
20048
20049        return true;
20050    }
20051
20052    @Override
20053    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
20054            int userId) {
20055        mContext.enforceCallingOrSelfPermission(
20056                android.Manifest.permission.DELETE_PACKAGES, null);
20057        synchronized (mPackages) {
20058            // Cannot block uninstall of static shared libs as they are
20059            // considered a part of the using app (emulating static linking).
20060            // Also static libs are installed always on internal storage.
20061            PackageParser.Package pkg = mPackages.get(packageName);
20062            if (pkg != null && pkg.staticSharedLibName != null) {
20063                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
20064                        + " providing static shared library: " + pkg.staticSharedLibName);
20065                return false;
20066            }
20067            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
20068            mSettings.writePackageRestrictionsLPr(userId);
20069        }
20070        return true;
20071    }
20072
20073    @Override
20074    public boolean getBlockUninstallForUser(String packageName, int userId) {
20075        synchronized (mPackages) {
20076            final PackageSetting ps = mSettings.mPackages.get(packageName);
20077            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
20078                return false;
20079            }
20080            return mSettings.getBlockUninstallLPr(userId, packageName);
20081        }
20082    }
20083
20084    @Override
20085    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
20086        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
20087        synchronized (mPackages) {
20088            PackageSetting ps = mSettings.mPackages.get(packageName);
20089            if (ps == null) {
20090                Log.w(TAG, "Package doesn't exist: " + packageName);
20091                return false;
20092            }
20093            if (systemUserApp) {
20094                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20095            } else {
20096                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20097            }
20098            mSettings.writeLPr();
20099        }
20100        return true;
20101    }
20102
20103    /*
20104     * This method handles package deletion in general
20105     */
20106    private boolean deletePackageLIF(String packageName, UserHandle user,
20107            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
20108            PackageRemovedInfo outInfo, boolean writeSettings,
20109            PackageParser.Package replacingPackage) {
20110        if (packageName == null) {
20111            Slog.w(TAG, "Attempt to delete null packageName.");
20112            return false;
20113        }
20114
20115        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
20116
20117        PackageSetting ps;
20118        synchronized (mPackages) {
20119            ps = mSettings.mPackages.get(packageName);
20120            if (ps == null) {
20121                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20122                return false;
20123            }
20124
20125            if (ps.parentPackageName != null && (!isSystemApp(ps)
20126                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
20127                if (DEBUG_REMOVE) {
20128                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
20129                            + ((user == null) ? UserHandle.USER_ALL : user));
20130                }
20131                final int removedUserId = (user != null) ? user.getIdentifier()
20132                        : UserHandle.USER_ALL;
20133                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
20134                    return false;
20135                }
20136                markPackageUninstalledForUserLPw(ps, user);
20137                scheduleWritePackageRestrictionsLocked(user);
20138                return true;
20139            }
20140        }
20141
20142        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
20143                && user.getIdentifier() != UserHandle.USER_ALL)) {
20144            // The caller is asking that the package only be deleted for a single
20145            // user.  To do this, we just mark its uninstalled state and delete
20146            // its data. If this is a system app, we only allow this to happen if
20147            // they have set the special DELETE_SYSTEM_APP which requests different
20148            // semantics than normal for uninstalling system apps.
20149            markPackageUninstalledForUserLPw(ps, user);
20150
20151            if (!isSystemApp(ps)) {
20152                // Do not uninstall the APK if an app should be cached
20153                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
20154                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
20155                    // Other user still have this package installed, so all
20156                    // we need to do is clear this user's data and save that
20157                    // it is uninstalled.
20158                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
20159                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20160                        return false;
20161                    }
20162                    scheduleWritePackageRestrictionsLocked(user);
20163                    return true;
20164                } else {
20165                    // We need to set it back to 'installed' so the uninstall
20166                    // broadcasts will be sent correctly.
20167                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
20168                    ps.setInstalled(true, user.getIdentifier());
20169                    mSettings.writeKernelMappingLPr(ps);
20170                }
20171            } else {
20172                // This is a system app, so we assume that the
20173                // other users still have this package installed, so all
20174                // we need to do is clear this user's data and save that
20175                // it is uninstalled.
20176                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
20177                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20178                    return false;
20179                }
20180                scheduleWritePackageRestrictionsLocked(user);
20181                return true;
20182            }
20183        }
20184
20185        // If we are deleting a composite package for all users, keep track
20186        // of result for each child.
20187        if (ps.childPackageNames != null && outInfo != null) {
20188            synchronized (mPackages) {
20189                final int childCount = ps.childPackageNames.size();
20190                outInfo.removedChildPackages = new ArrayMap<>(childCount);
20191                for (int i = 0; i < childCount; i++) {
20192                    String childPackageName = ps.childPackageNames.get(i);
20193                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
20194                    childInfo.removedPackage = childPackageName;
20195                    childInfo.installerPackageName = ps.installerPackageName;
20196                    outInfo.removedChildPackages.put(childPackageName, childInfo);
20197                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20198                    if (childPs != null) {
20199                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
20200                    }
20201                }
20202            }
20203        }
20204
20205        boolean ret = false;
20206        if (isSystemApp(ps)) {
20207            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
20208            // When an updated system application is deleted we delete the existing resources
20209            // as well and fall back to existing code in system partition
20210            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
20211        } else {
20212            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
20213            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
20214                    outInfo, writeSettings, replacingPackage);
20215        }
20216
20217        // Take a note whether we deleted the package for all users
20218        if (outInfo != null) {
20219            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
20220            if (outInfo.removedChildPackages != null) {
20221                synchronized (mPackages) {
20222                    final int childCount = outInfo.removedChildPackages.size();
20223                    for (int i = 0; i < childCount; i++) {
20224                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
20225                        if (childInfo != null) {
20226                            childInfo.removedForAllUsers = mPackages.get(
20227                                    childInfo.removedPackage) == null;
20228                        }
20229                    }
20230                }
20231            }
20232            // If we uninstalled an update to a system app there may be some
20233            // child packages that appeared as they are declared in the system
20234            // app but were not declared in the update.
20235            if (isSystemApp(ps)) {
20236                synchronized (mPackages) {
20237                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
20238                    final int childCount = (updatedPs.childPackageNames != null)
20239                            ? updatedPs.childPackageNames.size() : 0;
20240                    for (int i = 0; i < childCount; i++) {
20241                        String childPackageName = updatedPs.childPackageNames.get(i);
20242                        if (outInfo.removedChildPackages == null
20243                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
20244                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20245                            if (childPs == null) {
20246                                continue;
20247                            }
20248                            PackageInstalledInfo installRes = new PackageInstalledInfo();
20249                            installRes.name = childPackageName;
20250                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
20251                            installRes.pkg = mPackages.get(childPackageName);
20252                            installRes.uid = childPs.pkg.applicationInfo.uid;
20253                            if (outInfo.appearedChildPackages == null) {
20254                                outInfo.appearedChildPackages = new ArrayMap<>();
20255                            }
20256                            outInfo.appearedChildPackages.put(childPackageName, installRes);
20257                        }
20258                    }
20259                }
20260            }
20261        }
20262
20263        return ret;
20264    }
20265
20266    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
20267        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
20268                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
20269        for (int nextUserId : userIds) {
20270            if (DEBUG_REMOVE) {
20271                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
20272            }
20273            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
20274                    false /*installed*/,
20275                    true /*stopped*/,
20276                    true /*notLaunched*/,
20277                    false /*hidden*/,
20278                    false /*suspended*/,
20279                    false /*instantApp*/,
20280                    false /*virtualPreload*/,
20281                    null /*lastDisableAppCaller*/,
20282                    null /*enabledComponents*/,
20283                    null /*disabledComponents*/,
20284                    ps.readUserState(nextUserId).domainVerificationStatus,
20285                    0, PackageManager.INSTALL_REASON_UNKNOWN);
20286        }
20287        mSettings.writeKernelMappingLPr(ps);
20288    }
20289
20290    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
20291            PackageRemovedInfo outInfo) {
20292        final PackageParser.Package pkg;
20293        synchronized (mPackages) {
20294            pkg = mPackages.get(ps.name);
20295        }
20296
20297        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20298                : new int[] {userId};
20299        for (int nextUserId : userIds) {
20300            if (DEBUG_REMOVE) {
20301                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20302                        + nextUserId);
20303            }
20304
20305            destroyAppDataLIF(pkg, userId,
20306                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20307            destroyAppProfilesLIF(pkg, userId);
20308            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20309            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20310            schedulePackageCleaning(ps.name, nextUserId, false);
20311            synchronized (mPackages) {
20312                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20313                    scheduleWritePackageRestrictionsLocked(nextUserId);
20314                }
20315                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20316            }
20317        }
20318
20319        if (outInfo != null) {
20320            outInfo.removedPackage = ps.name;
20321            outInfo.installerPackageName = ps.installerPackageName;
20322            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20323            outInfo.removedAppId = ps.appId;
20324            outInfo.removedUsers = userIds;
20325            outInfo.broadcastUsers = userIds;
20326        }
20327
20328        return true;
20329    }
20330
20331    private final class ClearStorageConnection implements ServiceConnection {
20332        IMediaContainerService mContainerService;
20333
20334        @Override
20335        public void onServiceConnected(ComponentName name, IBinder service) {
20336            synchronized (this) {
20337                mContainerService = IMediaContainerService.Stub
20338                        .asInterface(Binder.allowBlocking(service));
20339                notifyAll();
20340            }
20341        }
20342
20343        @Override
20344        public void onServiceDisconnected(ComponentName name) {
20345        }
20346    }
20347
20348    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20349        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20350
20351        final boolean mounted;
20352        if (Environment.isExternalStorageEmulated()) {
20353            mounted = true;
20354        } else {
20355            final String status = Environment.getExternalStorageState();
20356
20357            mounted = status.equals(Environment.MEDIA_MOUNTED)
20358                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20359        }
20360
20361        if (!mounted) {
20362            return;
20363        }
20364
20365        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20366        int[] users;
20367        if (userId == UserHandle.USER_ALL) {
20368            users = sUserManager.getUserIds();
20369        } else {
20370            users = new int[] { userId };
20371        }
20372        final ClearStorageConnection conn = new ClearStorageConnection();
20373        if (mContext.bindServiceAsUser(
20374                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20375            try {
20376                for (int curUser : users) {
20377                    long timeout = SystemClock.uptimeMillis() + 5000;
20378                    synchronized (conn) {
20379                        long now;
20380                        while (conn.mContainerService == null &&
20381                                (now = SystemClock.uptimeMillis()) < timeout) {
20382                            try {
20383                                conn.wait(timeout - now);
20384                            } catch (InterruptedException e) {
20385                            }
20386                        }
20387                    }
20388                    if (conn.mContainerService == null) {
20389                        return;
20390                    }
20391
20392                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20393                    clearDirectory(conn.mContainerService,
20394                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20395                    if (allData) {
20396                        clearDirectory(conn.mContainerService,
20397                                userEnv.buildExternalStorageAppDataDirs(packageName));
20398                        clearDirectory(conn.mContainerService,
20399                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20400                    }
20401                }
20402            } finally {
20403                mContext.unbindService(conn);
20404            }
20405        }
20406    }
20407
20408    @Override
20409    public void clearApplicationProfileData(String packageName) {
20410        enforceSystemOrRoot("Only the system can clear all profile data");
20411
20412        final PackageParser.Package pkg;
20413        synchronized (mPackages) {
20414            pkg = mPackages.get(packageName);
20415        }
20416
20417        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20418            synchronized (mInstallLock) {
20419                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20420            }
20421        }
20422    }
20423
20424    @Override
20425    public void clearApplicationUserData(final String packageName,
20426            final IPackageDataObserver observer, final int userId) {
20427        mContext.enforceCallingOrSelfPermission(
20428                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20429
20430        final int callingUid = Binder.getCallingUid();
20431        enforceCrossUserPermission(callingUid, userId,
20432                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20433
20434        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20435        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
20436        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20437            throw new SecurityException("Cannot clear data for a protected package: "
20438                    + packageName);
20439        }
20440        // Queue up an async operation since the package deletion may take a little while.
20441        mHandler.post(new Runnable() {
20442            public void run() {
20443                mHandler.removeCallbacks(this);
20444                final boolean succeeded;
20445                if (!filterApp) {
20446                    try (PackageFreezer freezer = freezePackage(packageName,
20447                            "clearApplicationUserData")) {
20448                        synchronized (mInstallLock) {
20449                            succeeded = clearApplicationUserDataLIF(packageName, userId);
20450                        }
20451                        clearExternalStorageDataSync(packageName, userId, true);
20452                        synchronized (mPackages) {
20453                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20454                                    packageName, userId);
20455                        }
20456                    }
20457                    if (succeeded) {
20458                        // invoke DeviceStorageMonitor's update method to clear any notifications
20459                        DeviceStorageMonitorInternal dsm = LocalServices
20460                                .getService(DeviceStorageMonitorInternal.class);
20461                        if (dsm != null) {
20462                            dsm.checkMemory();
20463                        }
20464                    }
20465                } else {
20466                    succeeded = false;
20467                }
20468                if (observer != null) {
20469                    try {
20470                        observer.onRemoveCompleted(packageName, succeeded);
20471                    } catch (RemoteException e) {
20472                        Log.i(TAG, "Observer no longer exists.");
20473                    }
20474                } //end if observer
20475            } //end run
20476        });
20477    }
20478
20479    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20480        if (packageName == null) {
20481            Slog.w(TAG, "Attempt to delete null packageName.");
20482            return false;
20483        }
20484
20485        // Try finding details about the requested package
20486        PackageParser.Package pkg;
20487        synchronized (mPackages) {
20488            pkg = mPackages.get(packageName);
20489            if (pkg == null) {
20490                final PackageSetting ps = mSettings.mPackages.get(packageName);
20491                if (ps != null) {
20492                    pkg = ps.pkg;
20493                }
20494            }
20495
20496            if (pkg == null) {
20497                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20498                return false;
20499            }
20500
20501            PackageSetting ps = (PackageSetting) pkg.mExtras;
20502            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20503        }
20504
20505        clearAppDataLIF(pkg, userId,
20506                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20507
20508        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20509        removeKeystoreDataIfNeeded(userId, appId);
20510
20511        UserManagerInternal umInternal = getUserManagerInternal();
20512        final int flags;
20513        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20514            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20515        } else if (umInternal.isUserRunning(userId)) {
20516            flags = StorageManager.FLAG_STORAGE_DE;
20517        } else {
20518            flags = 0;
20519        }
20520        prepareAppDataContentsLIF(pkg, userId, flags);
20521
20522        return true;
20523    }
20524
20525    /**
20526     * Reverts user permission state changes (permissions and flags) in
20527     * all packages for a given user.
20528     *
20529     * @param userId The device user for which to do a reset.
20530     */
20531    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20532        final int packageCount = mPackages.size();
20533        for (int i = 0; i < packageCount; i++) {
20534            PackageParser.Package pkg = mPackages.valueAt(i);
20535            PackageSetting ps = (PackageSetting) pkg.mExtras;
20536            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20537        }
20538    }
20539
20540    private void resetNetworkPolicies(int userId) {
20541        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20542    }
20543
20544    /**
20545     * Reverts user permission state changes (permissions and flags).
20546     *
20547     * @param ps The package for which to reset.
20548     * @param userId The device user for which to do a reset.
20549     */
20550    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20551            final PackageSetting ps, final int userId) {
20552        if (ps.pkg == null) {
20553            return;
20554        }
20555
20556        // These are flags that can change base on user actions.
20557        final int userSettableMask = FLAG_PERMISSION_USER_SET
20558                | FLAG_PERMISSION_USER_FIXED
20559                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20560                | FLAG_PERMISSION_REVIEW_REQUIRED;
20561
20562        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20563                | FLAG_PERMISSION_POLICY_FIXED;
20564
20565        boolean writeInstallPermissions = false;
20566        boolean writeRuntimePermissions = false;
20567
20568        final int permissionCount = ps.pkg.requestedPermissions.size();
20569        for (int i = 0; i < permissionCount; i++) {
20570            String permission = ps.pkg.requestedPermissions.get(i);
20571
20572            BasePermission bp = mSettings.mPermissions.get(permission);
20573            if (bp == null) {
20574                continue;
20575            }
20576
20577            // If shared user we just reset the state to which only this app contributed.
20578            if (ps.sharedUser != null) {
20579                boolean used = false;
20580                final int packageCount = ps.sharedUser.packages.size();
20581                for (int j = 0; j < packageCount; j++) {
20582                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20583                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20584                            && pkg.pkg.requestedPermissions.contains(permission)) {
20585                        used = true;
20586                        break;
20587                    }
20588                }
20589                if (used) {
20590                    continue;
20591                }
20592            }
20593
20594            PermissionsState permissionsState = ps.getPermissionsState();
20595
20596            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20597
20598            // Always clear the user settable flags.
20599            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20600                    bp.name) != null;
20601            // If permission review is enabled and this is a legacy app, mark the
20602            // permission as requiring a review as this is the initial state.
20603            int flags = 0;
20604            if (mPermissionReviewRequired
20605                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20606                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20607            }
20608            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20609                if (hasInstallState) {
20610                    writeInstallPermissions = true;
20611                } else {
20612                    writeRuntimePermissions = true;
20613                }
20614            }
20615
20616            // Below is only runtime permission handling.
20617            if (!bp.isRuntime()) {
20618                continue;
20619            }
20620
20621            // Never clobber system or policy.
20622            if ((oldFlags & policyOrSystemFlags) != 0) {
20623                continue;
20624            }
20625
20626            // If this permission was granted by default, make sure it is.
20627            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20628                if (permissionsState.grantRuntimePermission(bp, userId)
20629                        != PERMISSION_OPERATION_FAILURE) {
20630                    writeRuntimePermissions = true;
20631                }
20632            // If permission review is enabled the permissions for a legacy apps
20633            // are represented as constantly granted runtime ones, so don't revoke.
20634            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20635                // Otherwise, reset the permission.
20636                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20637                switch (revokeResult) {
20638                    case PERMISSION_OPERATION_SUCCESS:
20639                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20640                        writeRuntimePermissions = true;
20641                        final int appId = ps.appId;
20642                        mHandler.post(new Runnable() {
20643                            @Override
20644                            public void run() {
20645                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20646                            }
20647                        });
20648                    } break;
20649                }
20650            }
20651        }
20652
20653        // Synchronously write as we are taking permissions away.
20654        if (writeRuntimePermissions) {
20655            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20656        }
20657
20658        // Synchronously write as we are taking permissions away.
20659        if (writeInstallPermissions) {
20660            mSettings.writeLPr();
20661        }
20662    }
20663
20664    /**
20665     * Remove entries from the keystore daemon. Will only remove it if the
20666     * {@code appId} is valid.
20667     */
20668    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20669        if (appId < 0) {
20670            return;
20671        }
20672
20673        final KeyStore keyStore = KeyStore.getInstance();
20674        if (keyStore != null) {
20675            if (userId == UserHandle.USER_ALL) {
20676                for (final int individual : sUserManager.getUserIds()) {
20677                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20678                }
20679            } else {
20680                keyStore.clearUid(UserHandle.getUid(userId, appId));
20681            }
20682        } else {
20683            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20684        }
20685    }
20686
20687    @Override
20688    public void deleteApplicationCacheFiles(final String packageName,
20689            final IPackageDataObserver observer) {
20690        final int userId = UserHandle.getCallingUserId();
20691        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20692    }
20693
20694    @Override
20695    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20696            final IPackageDataObserver observer) {
20697        final int callingUid = Binder.getCallingUid();
20698        mContext.enforceCallingOrSelfPermission(
20699                android.Manifest.permission.DELETE_CACHE_FILES, null);
20700        enforceCrossUserPermission(callingUid, userId,
20701                /* requireFullPermission= */ true, /* checkShell= */ false,
20702                "delete application cache files");
20703        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20704                android.Manifest.permission.ACCESS_INSTANT_APPS);
20705
20706        final PackageParser.Package pkg;
20707        synchronized (mPackages) {
20708            pkg = mPackages.get(packageName);
20709        }
20710
20711        // Queue up an async operation since the package deletion may take a little while.
20712        mHandler.post(new Runnable() {
20713            public void run() {
20714                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20715                boolean doClearData = true;
20716                if (ps != null) {
20717                    final boolean targetIsInstantApp =
20718                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20719                    doClearData = !targetIsInstantApp
20720                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20721                }
20722                if (doClearData) {
20723                    synchronized (mInstallLock) {
20724                        final int flags = StorageManager.FLAG_STORAGE_DE
20725                                | StorageManager.FLAG_STORAGE_CE;
20726                        // We're only clearing cache files, so we don't care if the
20727                        // app is unfrozen and still able to run
20728                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20729                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20730                    }
20731                    clearExternalStorageDataSync(packageName, userId, false);
20732                }
20733                if (observer != null) {
20734                    try {
20735                        observer.onRemoveCompleted(packageName, true);
20736                    } catch (RemoteException e) {
20737                        Log.i(TAG, "Observer no longer exists.");
20738                    }
20739                }
20740            }
20741        });
20742    }
20743
20744    @Override
20745    public void getPackageSizeInfo(final String packageName, int userHandle,
20746            final IPackageStatsObserver observer) {
20747        throw new UnsupportedOperationException(
20748                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20749    }
20750
20751    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20752        final PackageSetting ps;
20753        synchronized (mPackages) {
20754            ps = mSettings.mPackages.get(packageName);
20755            if (ps == null) {
20756                Slog.w(TAG, "Failed to find settings for " + packageName);
20757                return false;
20758            }
20759        }
20760
20761        final String[] packageNames = { packageName };
20762        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20763        final String[] codePaths = { ps.codePathString };
20764
20765        try {
20766            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20767                    ps.appId, ceDataInodes, codePaths, stats);
20768
20769            // For now, ignore code size of packages on system partition
20770            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20771                stats.codeSize = 0;
20772            }
20773
20774            // External clients expect these to be tracked separately
20775            stats.dataSize -= stats.cacheSize;
20776
20777        } catch (InstallerException e) {
20778            Slog.w(TAG, String.valueOf(e));
20779            return false;
20780        }
20781
20782        return true;
20783    }
20784
20785    private int getUidTargetSdkVersionLockedLPr(int uid) {
20786        Object obj = mSettings.getUserIdLPr(uid);
20787        if (obj instanceof SharedUserSetting) {
20788            final SharedUserSetting sus = (SharedUserSetting) obj;
20789            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20790            final Iterator<PackageSetting> it = sus.packages.iterator();
20791            while (it.hasNext()) {
20792                final PackageSetting ps = it.next();
20793                if (ps.pkg != null) {
20794                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20795                    if (v < vers) vers = v;
20796                }
20797            }
20798            return vers;
20799        } else if (obj instanceof PackageSetting) {
20800            final PackageSetting ps = (PackageSetting) obj;
20801            if (ps.pkg != null) {
20802                return ps.pkg.applicationInfo.targetSdkVersion;
20803            }
20804        }
20805        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20806    }
20807
20808    @Override
20809    public void addPreferredActivity(IntentFilter filter, int match,
20810            ComponentName[] set, ComponentName activity, int userId) {
20811        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20812                "Adding preferred");
20813    }
20814
20815    private void addPreferredActivityInternal(IntentFilter filter, int match,
20816            ComponentName[] set, ComponentName activity, boolean always, int userId,
20817            String opname) {
20818        // writer
20819        int callingUid = Binder.getCallingUid();
20820        enforceCrossUserPermission(callingUid, userId,
20821                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20822        if (filter.countActions() == 0) {
20823            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20824            return;
20825        }
20826        synchronized (mPackages) {
20827            if (mContext.checkCallingOrSelfPermission(
20828                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20829                    != PackageManager.PERMISSION_GRANTED) {
20830                if (getUidTargetSdkVersionLockedLPr(callingUid)
20831                        < Build.VERSION_CODES.FROYO) {
20832                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20833                            + callingUid);
20834                    return;
20835                }
20836                mContext.enforceCallingOrSelfPermission(
20837                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20838            }
20839
20840            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20841            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20842                    + userId + ":");
20843            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20844            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20845            scheduleWritePackageRestrictionsLocked(userId);
20846            postPreferredActivityChangedBroadcast(userId);
20847        }
20848    }
20849
20850    private void postPreferredActivityChangedBroadcast(int userId) {
20851        mHandler.post(() -> {
20852            final IActivityManager am = ActivityManager.getService();
20853            if (am == null) {
20854                return;
20855            }
20856
20857            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20858            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20859            try {
20860                am.broadcastIntent(null, intent, null, null,
20861                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20862                        null, false, false, userId);
20863            } catch (RemoteException e) {
20864            }
20865        });
20866    }
20867
20868    @Override
20869    public void replacePreferredActivity(IntentFilter filter, int match,
20870            ComponentName[] set, ComponentName activity, int userId) {
20871        if (filter.countActions() != 1) {
20872            throw new IllegalArgumentException(
20873                    "replacePreferredActivity expects filter to have only 1 action.");
20874        }
20875        if (filter.countDataAuthorities() != 0
20876                || filter.countDataPaths() != 0
20877                || filter.countDataSchemes() > 1
20878                || filter.countDataTypes() != 0) {
20879            throw new IllegalArgumentException(
20880                    "replacePreferredActivity expects filter to have no data authorities, " +
20881                    "paths, or types; and at most one scheme.");
20882        }
20883
20884        final int callingUid = Binder.getCallingUid();
20885        enforceCrossUserPermission(callingUid, userId,
20886                true /* requireFullPermission */, false /* checkShell */,
20887                "replace preferred activity");
20888        synchronized (mPackages) {
20889            if (mContext.checkCallingOrSelfPermission(
20890                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20891                    != PackageManager.PERMISSION_GRANTED) {
20892                if (getUidTargetSdkVersionLockedLPr(callingUid)
20893                        < Build.VERSION_CODES.FROYO) {
20894                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20895                            + Binder.getCallingUid());
20896                    return;
20897                }
20898                mContext.enforceCallingOrSelfPermission(
20899                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20900            }
20901
20902            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20903            if (pir != null) {
20904                // Get all of the existing entries that exactly match this filter.
20905                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20906                if (existing != null && existing.size() == 1) {
20907                    PreferredActivity cur = existing.get(0);
20908                    if (DEBUG_PREFERRED) {
20909                        Slog.i(TAG, "Checking replace of preferred:");
20910                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20911                        if (!cur.mPref.mAlways) {
20912                            Slog.i(TAG, "  -- CUR; not mAlways!");
20913                        } else {
20914                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20915                            Slog.i(TAG, "  -- CUR: mSet="
20916                                    + Arrays.toString(cur.mPref.mSetComponents));
20917                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20918                            Slog.i(TAG, "  -- NEW: mMatch="
20919                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20920                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20921                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20922                        }
20923                    }
20924                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20925                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20926                            && cur.mPref.sameSet(set)) {
20927                        // Setting the preferred activity to what it happens to be already
20928                        if (DEBUG_PREFERRED) {
20929                            Slog.i(TAG, "Replacing with same preferred activity "
20930                                    + cur.mPref.mShortComponent + " for user "
20931                                    + userId + ":");
20932                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20933                        }
20934                        return;
20935                    }
20936                }
20937
20938                if (existing != null) {
20939                    if (DEBUG_PREFERRED) {
20940                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20941                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20942                    }
20943                    for (int i = 0; i < existing.size(); i++) {
20944                        PreferredActivity pa = existing.get(i);
20945                        if (DEBUG_PREFERRED) {
20946                            Slog.i(TAG, "Removing existing preferred activity "
20947                                    + pa.mPref.mComponent + ":");
20948                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20949                        }
20950                        pir.removeFilter(pa);
20951                    }
20952                }
20953            }
20954            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20955                    "Replacing preferred");
20956        }
20957    }
20958
20959    @Override
20960    public void clearPackagePreferredActivities(String packageName) {
20961        final int callingUid = Binder.getCallingUid();
20962        if (getInstantAppPackageName(callingUid) != null) {
20963            return;
20964        }
20965        // writer
20966        synchronized (mPackages) {
20967            PackageParser.Package pkg = mPackages.get(packageName);
20968            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20969                if (mContext.checkCallingOrSelfPermission(
20970                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20971                        != PackageManager.PERMISSION_GRANTED) {
20972                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20973                            < Build.VERSION_CODES.FROYO) {
20974                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20975                                + callingUid);
20976                        return;
20977                    }
20978                    mContext.enforceCallingOrSelfPermission(
20979                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20980                }
20981            }
20982            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20983            if (ps != null
20984                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20985                return;
20986            }
20987            int user = UserHandle.getCallingUserId();
20988            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20989                scheduleWritePackageRestrictionsLocked(user);
20990            }
20991        }
20992    }
20993
20994    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20995    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20996        ArrayList<PreferredActivity> removed = null;
20997        boolean changed = false;
20998        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20999            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
21000            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21001            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
21002                continue;
21003            }
21004            Iterator<PreferredActivity> it = pir.filterIterator();
21005            while (it.hasNext()) {
21006                PreferredActivity pa = it.next();
21007                // Mark entry for removal only if it matches the package name
21008                // and the entry is of type "always".
21009                if (packageName == null ||
21010                        (pa.mPref.mComponent.getPackageName().equals(packageName)
21011                                && pa.mPref.mAlways)) {
21012                    if (removed == null) {
21013                        removed = new ArrayList<PreferredActivity>();
21014                    }
21015                    removed.add(pa);
21016                }
21017            }
21018            if (removed != null) {
21019                for (int j=0; j<removed.size(); j++) {
21020                    PreferredActivity pa = removed.get(j);
21021                    pir.removeFilter(pa);
21022                }
21023                changed = true;
21024            }
21025        }
21026        if (changed) {
21027            postPreferredActivityChangedBroadcast(userId);
21028        }
21029        return changed;
21030    }
21031
21032    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
21033    private void clearIntentFilterVerificationsLPw(int userId) {
21034        final int packageCount = mPackages.size();
21035        for (int i = 0; i < packageCount; i++) {
21036            PackageParser.Package pkg = mPackages.valueAt(i);
21037            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
21038        }
21039    }
21040
21041    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
21042    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
21043        if (userId == UserHandle.USER_ALL) {
21044            if (mSettings.removeIntentFilterVerificationLPw(packageName,
21045                    sUserManager.getUserIds())) {
21046                for (int oneUserId : sUserManager.getUserIds()) {
21047                    scheduleWritePackageRestrictionsLocked(oneUserId);
21048                }
21049            }
21050        } else {
21051            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
21052                scheduleWritePackageRestrictionsLocked(userId);
21053            }
21054        }
21055    }
21056
21057    /** Clears state for all users, and touches intent filter verification policy */
21058    void clearDefaultBrowserIfNeeded(String packageName) {
21059        for (int oneUserId : sUserManager.getUserIds()) {
21060            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
21061        }
21062    }
21063
21064    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
21065        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
21066        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
21067            if (packageName.equals(defaultBrowserPackageName)) {
21068                setDefaultBrowserPackageName(null, userId);
21069            }
21070        }
21071    }
21072
21073    @Override
21074    public void resetApplicationPreferences(int userId) {
21075        mContext.enforceCallingOrSelfPermission(
21076                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
21077        final long identity = Binder.clearCallingIdentity();
21078        // writer
21079        try {
21080            synchronized (mPackages) {
21081                clearPackagePreferredActivitiesLPw(null, userId);
21082                mSettings.applyDefaultPreferredAppsLPw(this, userId);
21083                // TODO: We have to reset the default SMS and Phone. This requires
21084                // significant refactoring to keep all default apps in the package
21085                // manager (cleaner but more work) or have the services provide
21086                // callbacks to the package manager to request a default app reset.
21087                applyFactoryDefaultBrowserLPw(userId);
21088                clearIntentFilterVerificationsLPw(userId);
21089                primeDomainVerificationsLPw(userId);
21090                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
21091                scheduleWritePackageRestrictionsLocked(userId);
21092            }
21093            resetNetworkPolicies(userId);
21094        } finally {
21095            Binder.restoreCallingIdentity(identity);
21096        }
21097    }
21098
21099    @Override
21100    public int getPreferredActivities(List<IntentFilter> outFilters,
21101            List<ComponentName> outActivities, String packageName) {
21102        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21103            return 0;
21104        }
21105        int num = 0;
21106        final int userId = UserHandle.getCallingUserId();
21107        // reader
21108        synchronized (mPackages) {
21109            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
21110            if (pir != null) {
21111                final Iterator<PreferredActivity> it = pir.filterIterator();
21112                while (it.hasNext()) {
21113                    final PreferredActivity pa = it.next();
21114                    if (packageName == null
21115                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
21116                                    && pa.mPref.mAlways)) {
21117                        if (outFilters != null) {
21118                            outFilters.add(new IntentFilter(pa));
21119                        }
21120                        if (outActivities != null) {
21121                            outActivities.add(pa.mPref.mComponent);
21122                        }
21123                    }
21124                }
21125            }
21126        }
21127
21128        return num;
21129    }
21130
21131    @Override
21132    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
21133            int userId) {
21134        int callingUid = Binder.getCallingUid();
21135        if (callingUid != Process.SYSTEM_UID) {
21136            throw new SecurityException(
21137                    "addPersistentPreferredActivity can only be run by the system");
21138        }
21139        if (filter.countActions() == 0) {
21140            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
21141            return;
21142        }
21143        synchronized (mPackages) {
21144            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
21145                    ":");
21146            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
21147            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
21148                    new PersistentPreferredActivity(filter, activity));
21149            scheduleWritePackageRestrictionsLocked(userId);
21150            postPreferredActivityChangedBroadcast(userId);
21151        }
21152    }
21153
21154    @Override
21155    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
21156        int callingUid = Binder.getCallingUid();
21157        if (callingUid != Process.SYSTEM_UID) {
21158            throw new SecurityException(
21159                    "clearPackagePersistentPreferredActivities can only be run by the system");
21160        }
21161        ArrayList<PersistentPreferredActivity> removed = null;
21162        boolean changed = false;
21163        synchronized (mPackages) {
21164            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
21165                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
21166                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
21167                        .valueAt(i);
21168                if (userId != thisUserId) {
21169                    continue;
21170                }
21171                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
21172                while (it.hasNext()) {
21173                    PersistentPreferredActivity ppa = it.next();
21174                    // Mark entry for removal only if it matches the package name.
21175                    if (ppa.mComponent.getPackageName().equals(packageName)) {
21176                        if (removed == null) {
21177                            removed = new ArrayList<PersistentPreferredActivity>();
21178                        }
21179                        removed.add(ppa);
21180                    }
21181                }
21182                if (removed != null) {
21183                    for (int j=0; j<removed.size(); j++) {
21184                        PersistentPreferredActivity ppa = removed.get(j);
21185                        ppir.removeFilter(ppa);
21186                    }
21187                    changed = true;
21188                }
21189            }
21190
21191            if (changed) {
21192                scheduleWritePackageRestrictionsLocked(userId);
21193                postPreferredActivityChangedBroadcast(userId);
21194            }
21195        }
21196    }
21197
21198    /**
21199     * Common machinery for picking apart a restored XML blob and passing
21200     * it to a caller-supplied functor to be applied to the running system.
21201     */
21202    private void restoreFromXml(XmlPullParser parser, int userId,
21203            String expectedStartTag, BlobXmlRestorer functor)
21204            throws IOException, XmlPullParserException {
21205        int type;
21206        while ((type = parser.next()) != XmlPullParser.START_TAG
21207                && type != XmlPullParser.END_DOCUMENT) {
21208        }
21209        if (type != XmlPullParser.START_TAG) {
21210            // oops didn't find a start tag?!
21211            if (DEBUG_BACKUP) {
21212                Slog.e(TAG, "Didn't find start tag during restore");
21213            }
21214            return;
21215        }
21216Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
21217        // this is supposed to be TAG_PREFERRED_BACKUP
21218        if (!expectedStartTag.equals(parser.getName())) {
21219            if (DEBUG_BACKUP) {
21220                Slog.e(TAG, "Found unexpected tag " + parser.getName());
21221            }
21222            return;
21223        }
21224
21225        // skip interfering stuff, then we're aligned with the backing implementation
21226        while ((type = parser.next()) == XmlPullParser.TEXT) { }
21227Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
21228        functor.apply(parser, userId);
21229    }
21230
21231    private interface BlobXmlRestorer {
21232        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
21233    }
21234
21235    /**
21236     * Non-Binder method, support for the backup/restore mechanism: write the
21237     * full set of preferred activities in its canonical XML format.  Returns the
21238     * XML output as a byte array, or null if there is none.
21239     */
21240    @Override
21241    public byte[] getPreferredActivityBackup(int userId) {
21242        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21243            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
21244        }
21245
21246        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21247        try {
21248            final XmlSerializer serializer = new FastXmlSerializer();
21249            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21250            serializer.startDocument(null, true);
21251            serializer.startTag(null, TAG_PREFERRED_BACKUP);
21252
21253            synchronized (mPackages) {
21254                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
21255            }
21256
21257            serializer.endTag(null, TAG_PREFERRED_BACKUP);
21258            serializer.endDocument();
21259            serializer.flush();
21260        } catch (Exception e) {
21261            if (DEBUG_BACKUP) {
21262                Slog.e(TAG, "Unable to write preferred activities for backup", e);
21263            }
21264            return null;
21265        }
21266
21267        return dataStream.toByteArray();
21268    }
21269
21270    @Override
21271    public void restorePreferredActivities(byte[] backup, int userId) {
21272        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21273            throw new SecurityException("Only the system may call restorePreferredActivities()");
21274        }
21275
21276        try {
21277            final XmlPullParser parser = Xml.newPullParser();
21278            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21279            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
21280                    new BlobXmlRestorer() {
21281                        @Override
21282                        public void apply(XmlPullParser parser, int userId)
21283                                throws XmlPullParserException, IOException {
21284                            synchronized (mPackages) {
21285                                mSettings.readPreferredActivitiesLPw(parser, userId);
21286                            }
21287                        }
21288                    } );
21289        } catch (Exception e) {
21290            if (DEBUG_BACKUP) {
21291                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21292            }
21293        }
21294    }
21295
21296    /**
21297     * Non-Binder method, support for the backup/restore mechanism: write the
21298     * default browser (etc) settings in its canonical XML format.  Returns the default
21299     * browser XML representation as a byte array, or null if there is none.
21300     */
21301    @Override
21302    public byte[] getDefaultAppsBackup(int userId) {
21303        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21304            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21305        }
21306
21307        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21308        try {
21309            final XmlSerializer serializer = new FastXmlSerializer();
21310            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21311            serializer.startDocument(null, true);
21312            serializer.startTag(null, TAG_DEFAULT_APPS);
21313
21314            synchronized (mPackages) {
21315                mSettings.writeDefaultAppsLPr(serializer, userId);
21316            }
21317
21318            serializer.endTag(null, TAG_DEFAULT_APPS);
21319            serializer.endDocument();
21320            serializer.flush();
21321        } catch (Exception e) {
21322            if (DEBUG_BACKUP) {
21323                Slog.e(TAG, "Unable to write default apps for backup", e);
21324            }
21325            return null;
21326        }
21327
21328        return dataStream.toByteArray();
21329    }
21330
21331    @Override
21332    public void restoreDefaultApps(byte[] backup, int userId) {
21333        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21334            throw new SecurityException("Only the system may call restoreDefaultApps()");
21335        }
21336
21337        try {
21338            final XmlPullParser parser = Xml.newPullParser();
21339            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21340            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21341                    new BlobXmlRestorer() {
21342                        @Override
21343                        public void apply(XmlPullParser parser, int userId)
21344                                throws XmlPullParserException, IOException {
21345                            synchronized (mPackages) {
21346                                mSettings.readDefaultAppsLPw(parser, userId);
21347                            }
21348                        }
21349                    } );
21350        } catch (Exception e) {
21351            if (DEBUG_BACKUP) {
21352                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21353            }
21354        }
21355    }
21356
21357    @Override
21358    public byte[] getIntentFilterVerificationBackup(int userId) {
21359        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21360            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21361        }
21362
21363        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21364        try {
21365            final XmlSerializer serializer = new FastXmlSerializer();
21366            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21367            serializer.startDocument(null, true);
21368            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21369
21370            synchronized (mPackages) {
21371                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21372            }
21373
21374            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21375            serializer.endDocument();
21376            serializer.flush();
21377        } catch (Exception e) {
21378            if (DEBUG_BACKUP) {
21379                Slog.e(TAG, "Unable to write default apps for backup", e);
21380            }
21381            return null;
21382        }
21383
21384        return dataStream.toByteArray();
21385    }
21386
21387    @Override
21388    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21389        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21390            throw new SecurityException("Only the system may call restorePreferredActivities()");
21391        }
21392
21393        try {
21394            final XmlPullParser parser = Xml.newPullParser();
21395            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21396            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21397                    new BlobXmlRestorer() {
21398                        @Override
21399                        public void apply(XmlPullParser parser, int userId)
21400                                throws XmlPullParserException, IOException {
21401                            synchronized (mPackages) {
21402                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21403                                mSettings.writeLPr();
21404                            }
21405                        }
21406                    } );
21407        } catch (Exception e) {
21408            if (DEBUG_BACKUP) {
21409                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21410            }
21411        }
21412    }
21413
21414    @Override
21415    public byte[] getPermissionGrantBackup(int userId) {
21416        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21417            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21418        }
21419
21420        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21421        try {
21422            final XmlSerializer serializer = new FastXmlSerializer();
21423            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21424            serializer.startDocument(null, true);
21425            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21426
21427            synchronized (mPackages) {
21428                serializeRuntimePermissionGrantsLPr(serializer, userId);
21429            }
21430
21431            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21432            serializer.endDocument();
21433            serializer.flush();
21434        } catch (Exception e) {
21435            if (DEBUG_BACKUP) {
21436                Slog.e(TAG, "Unable to write default apps for backup", e);
21437            }
21438            return null;
21439        }
21440
21441        return dataStream.toByteArray();
21442    }
21443
21444    @Override
21445    public void restorePermissionGrants(byte[] backup, int userId) {
21446        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21447            throw new SecurityException("Only the system may call restorePermissionGrants()");
21448        }
21449
21450        try {
21451            final XmlPullParser parser = Xml.newPullParser();
21452            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21453            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21454                    new BlobXmlRestorer() {
21455                        @Override
21456                        public void apply(XmlPullParser parser, int userId)
21457                                throws XmlPullParserException, IOException {
21458                            synchronized (mPackages) {
21459                                processRestoredPermissionGrantsLPr(parser, userId);
21460                            }
21461                        }
21462                    } );
21463        } catch (Exception e) {
21464            if (DEBUG_BACKUP) {
21465                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21466            }
21467        }
21468    }
21469
21470    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21471            throws IOException {
21472        serializer.startTag(null, TAG_ALL_GRANTS);
21473
21474        final int N = mSettings.mPackages.size();
21475        for (int i = 0; i < N; i++) {
21476            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21477            boolean pkgGrantsKnown = false;
21478
21479            PermissionsState packagePerms = ps.getPermissionsState();
21480
21481            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21482                final int grantFlags = state.getFlags();
21483                // only look at grants that are not system/policy fixed
21484                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21485                    final boolean isGranted = state.isGranted();
21486                    // And only back up the user-twiddled state bits
21487                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21488                        final String packageName = mSettings.mPackages.keyAt(i);
21489                        if (!pkgGrantsKnown) {
21490                            serializer.startTag(null, TAG_GRANT);
21491                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21492                            pkgGrantsKnown = true;
21493                        }
21494
21495                        final boolean userSet =
21496                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21497                        final boolean userFixed =
21498                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21499                        final boolean revoke =
21500                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21501
21502                        serializer.startTag(null, TAG_PERMISSION);
21503                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21504                        if (isGranted) {
21505                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21506                        }
21507                        if (userSet) {
21508                            serializer.attribute(null, ATTR_USER_SET, "true");
21509                        }
21510                        if (userFixed) {
21511                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21512                        }
21513                        if (revoke) {
21514                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21515                        }
21516                        serializer.endTag(null, TAG_PERMISSION);
21517                    }
21518                }
21519            }
21520
21521            if (pkgGrantsKnown) {
21522                serializer.endTag(null, TAG_GRANT);
21523            }
21524        }
21525
21526        serializer.endTag(null, TAG_ALL_GRANTS);
21527    }
21528
21529    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21530            throws XmlPullParserException, IOException {
21531        String pkgName = null;
21532        int outerDepth = parser.getDepth();
21533        int type;
21534        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21535                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21536            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21537                continue;
21538            }
21539
21540            final String tagName = parser.getName();
21541            if (tagName.equals(TAG_GRANT)) {
21542                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21543                if (DEBUG_BACKUP) {
21544                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21545                }
21546            } else if (tagName.equals(TAG_PERMISSION)) {
21547
21548                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21549                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21550
21551                int newFlagSet = 0;
21552                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21553                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21554                }
21555                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21556                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21557                }
21558                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21559                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21560                }
21561                if (DEBUG_BACKUP) {
21562                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21563                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21564                }
21565                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21566                if (ps != null) {
21567                    // Already installed so we apply the grant immediately
21568                    if (DEBUG_BACKUP) {
21569                        Slog.v(TAG, "        + already installed; applying");
21570                    }
21571                    PermissionsState perms = ps.getPermissionsState();
21572                    BasePermission bp = mSettings.mPermissions.get(permName);
21573                    if (bp != null) {
21574                        if (isGranted) {
21575                            perms.grantRuntimePermission(bp, userId);
21576                        }
21577                        if (newFlagSet != 0) {
21578                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21579                        }
21580                    }
21581                } else {
21582                    // Need to wait for post-restore install to apply the grant
21583                    if (DEBUG_BACKUP) {
21584                        Slog.v(TAG, "        - not yet installed; saving for later");
21585                    }
21586                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21587                            isGranted, newFlagSet, userId);
21588                }
21589            } else {
21590                PackageManagerService.reportSettingsProblem(Log.WARN,
21591                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21592                XmlUtils.skipCurrentTag(parser);
21593            }
21594        }
21595
21596        scheduleWriteSettingsLocked();
21597        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21598    }
21599
21600    @Override
21601    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21602            int sourceUserId, int targetUserId, int flags) {
21603        mContext.enforceCallingOrSelfPermission(
21604                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21605        int callingUid = Binder.getCallingUid();
21606        enforceOwnerRights(ownerPackage, callingUid);
21607        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21608        if (intentFilter.countActions() == 0) {
21609            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21610            return;
21611        }
21612        synchronized (mPackages) {
21613            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21614                    ownerPackage, targetUserId, flags);
21615            CrossProfileIntentResolver resolver =
21616                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21617            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21618            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21619            if (existing != null) {
21620                int size = existing.size();
21621                for (int i = 0; i < size; i++) {
21622                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21623                        return;
21624                    }
21625                }
21626            }
21627            resolver.addFilter(newFilter);
21628            scheduleWritePackageRestrictionsLocked(sourceUserId);
21629        }
21630    }
21631
21632    @Override
21633    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21634        mContext.enforceCallingOrSelfPermission(
21635                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21636        final int callingUid = Binder.getCallingUid();
21637        enforceOwnerRights(ownerPackage, callingUid);
21638        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21639        synchronized (mPackages) {
21640            CrossProfileIntentResolver resolver =
21641                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21642            ArraySet<CrossProfileIntentFilter> set =
21643                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21644            for (CrossProfileIntentFilter filter : set) {
21645                if (filter.getOwnerPackage().equals(ownerPackage)) {
21646                    resolver.removeFilter(filter);
21647                }
21648            }
21649            scheduleWritePackageRestrictionsLocked(sourceUserId);
21650        }
21651    }
21652
21653    // Enforcing that callingUid is owning pkg on userId
21654    private void enforceOwnerRights(String pkg, int callingUid) {
21655        // The system owns everything.
21656        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21657            return;
21658        }
21659        final int callingUserId = UserHandle.getUserId(callingUid);
21660        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21661        if (pi == null) {
21662            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21663                    + callingUserId);
21664        }
21665        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21666            throw new SecurityException("Calling uid " + callingUid
21667                    + " does not own package " + pkg);
21668        }
21669    }
21670
21671    @Override
21672    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21673        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21674            return null;
21675        }
21676        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21677    }
21678
21679    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21680        UserManagerService ums = UserManagerService.getInstance();
21681        if (ums != null) {
21682            final UserInfo parent = ums.getProfileParent(userId);
21683            final int launcherUid = (parent != null) ? parent.id : userId;
21684            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21685            if (launcherComponent != null) {
21686                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21687                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21688                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21689                        .setPackage(launcherComponent.getPackageName());
21690                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21691            }
21692        }
21693    }
21694
21695    /**
21696     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21697     * then reports the most likely home activity or null if there are more than one.
21698     */
21699    private ComponentName getDefaultHomeActivity(int userId) {
21700        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21701        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21702        if (cn != null) {
21703            return cn;
21704        }
21705
21706        // Find the launcher with the highest priority and return that component if there are no
21707        // other home activity with the same priority.
21708        int lastPriority = Integer.MIN_VALUE;
21709        ComponentName lastComponent = null;
21710        final int size = allHomeCandidates.size();
21711        for (int i = 0; i < size; i++) {
21712            final ResolveInfo ri = allHomeCandidates.get(i);
21713            if (ri.priority > lastPriority) {
21714                lastComponent = ri.activityInfo.getComponentName();
21715                lastPriority = ri.priority;
21716            } else if (ri.priority == lastPriority) {
21717                // Two components found with same priority.
21718                lastComponent = null;
21719            }
21720        }
21721        return lastComponent;
21722    }
21723
21724    private Intent getHomeIntent() {
21725        Intent intent = new Intent(Intent.ACTION_MAIN);
21726        intent.addCategory(Intent.CATEGORY_HOME);
21727        intent.addCategory(Intent.CATEGORY_DEFAULT);
21728        return intent;
21729    }
21730
21731    private IntentFilter getHomeFilter() {
21732        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21733        filter.addCategory(Intent.CATEGORY_HOME);
21734        filter.addCategory(Intent.CATEGORY_DEFAULT);
21735        return filter;
21736    }
21737
21738    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21739            int userId) {
21740        Intent intent  = getHomeIntent();
21741        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21742                PackageManager.GET_META_DATA, userId);
21743        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21744                true, false, false, userId);
21745
21746        allHomeCandidates.clear();
21747        if (list != null) {
21748            for (ResolveInfo ri : list) {
21749                allHomeCandidates.add(ri);
21750            }
21751        }
21752        return (preferred == null || preferred.activityInfo == null)
21753                ? null
21754                : new ComponentName(preferred.activityInfo.packageName,
21755                        preferred.activityInfo.name);
21756    }
21757
21758    @Override
21759    public void setHomeActivity(ComponentName comp, int userId) {
21760        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21761            return;
21762        }
21763        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21764        getHomeActivitiesAsUser(homeActivities, userId);
21765
21766        boolean found = false;
21767
21768        final int size = homeActivities.size();
21769        final ComponentName[] set = new ComponentName[size];
21770        for (int i = 0; i < size; i++) {
21771            final ResolveInfo candidate = homeActivities.get(i);
21772            final ActivityInfo info = candidate.activityInfo;
21773            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21774            set[i] = activityName;
21775            if (!found && activityName.equals(comp)) {
21776                found = true;
21777            }
21778        }
21779        if (!found) {
21780            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21781                    + userId);
21782        }
21783        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21784                set, comp, userId);
21785    }
21786
21787    private @Nullable String getSetupWizardPackageName() {
21788        final Intent intent = new Intent(Intent.ACTION_MAIN);
21789        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21790
21791        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21792                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21793                        | MATCH_DISABLED_COMPONENTS,
21794                UserHandle.myUserId());
21795        if (matches.size() == 1) {
21796            return matches.get(0).getComponentInfo().packageName;
21797        } else {
21798            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21799                    + ": matches=" + matches);
21800            return null;
21801        }
21802    }
21803
21804    private @Nullable String getStorageManagerPackageName() {
21805        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21806
21807        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21808                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21809                        | MATCH_DISABLED_COMPONENTS,
21810                UserHandle.myUserId());
21811        if (matches.size() == 1) {
21812            return matches.get(0).getComponentInfo().packageName;
21813        } else {
21814            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21815                    + matches.size() + ": matches=" + matches);
21816            return null;
21817        }
21818    }
21819
21820    @Override
21821    public void setApplicationEnabledSetting(String appPackageName,
21822            int newState, int flags, int userId, String callingPackage) {
21823        if (!sUserManager.exists(userId)) return;
21824        if (callingPackage == null) {
21825            callingPackage = Integer.toString(Binder.getCallingUid());
21826        }
21827        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21828    }
21829
21830    @Override
21831    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21832        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21833        synchronized (mPackages) {
21834            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21835            if (pkgSetting != null) {
21836                pkgSetting.setUpdateAvailable(updateAvailable);
21837            }
21838        }
21839    }
21840
21841    @Override
21842    public void setComponentEnabledSetting(ComponentName componentName,
21843            int newState, int flags, int userId) {
21844        if (!sUserManager.exists(userId)) return;
21845        setEnabledSetting(componentName.getPackageName(),
21846                componentName.getClassName(), newState, flags, userId, null);
21847    }
21848
21849    private void setEnabledSetting(final String packageName, String className, int newState,
21850            final int flags, int userId, String callingPackage) {
21851        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21852              || newState == COMPONENT_ENABLED_STATE_ENABLED
21853              || newState == COMPONENT_ENABLED_STATE_DISABLED
21854              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21855              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21856            throw new IllegalArgumentException("Invalid new component state: "
21857                    + newState);
21858        }
21859        PackageSetting pkgSetting;
21860        final int callingUid = Binder.getCallingUid();
21861        final int permission;
21862        if (callingUid == Process.SYSTEM_UID) {
21863            permission = PackageManager.PERMISSION_GRANTED;
21864        } else {
21865            permission = mContext.checkCallingOrSelfPermission(
21866                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21867        }
21868        enforceCrossUserPermission(callingUid, userId,
21869                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21870        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21871        boolean sendNow = false;
21872        boolean isApp = (className == null);
21873        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21874        String componentName = isApp ? packageName : className;
21875        int packageUid = -1;
21876        ArrayList<String> components;
21877
21878        // reader
21879        synchronized (mPackages) {
21880            pkgSetting = mSettings.mPackages.get(packageName);
21881            if (pkgSetting == null) {
21882                if (!isCallerInstantApp) {
21883                    if (className == null) {
21884                        throw new IllegalArgumentException("Unknown package: " + packageName);
21885                    }
21886                    throw new IllegalArgumentException(
21887                            "Unknown component: " + packageName + "/" + className);
21888                } else {
21889                    // throw SecurityException to prevent leaking package information
21890                    throw new SecurityException(
21891                            "Attempt to change component state; "
21892                            + "pid=" + Binder.getCallingPid()
21893                            + ", uid=" + callingUid
21894                            + (className == null
21895                                    ? ", package=" + packageName
21896                                    : ", component=" + packageName + "/" + className));
21897                }
21898            }
21899        }
21900
21901        // Limit who can change which apps
21902        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21903            // Don't allow apps that don't have permission to modify other apps
21904            if (!allowedByPermission
21905                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21906                throw new SecurityException(
21907                        "Attempt to change component state; "
21908                        + "pid=" + Binder.getCallingPid()
21909                        + ", uid=" + callingUid
21910                        + (className == null
21911                                ? ", package=" + packageName
21912                                : ", component=" + packageName + "/" + className));
21913            }
21914            // Don't allow changing protected packages.
21915            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21916                throw new SecurityException("Cannot disable a protected package: " + packageName);
21917            }
21918        }
21919
21920        synchronized (mPackages) {
21921            if (callingUid == Process.SHELL_UID
21922                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21923                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21924                // unless it is a test package.
21925                int oldState = pkgSetting.getEnabled(userId);
21926                if (className == null
21927                        &&
21928                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21929                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21930                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21931                        &&
21932                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21933                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
21934                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21935                    // ok
21936                } else {
21937                    throw new SecurityException(
21938                            "Shell cannot change component state for " + packageName + "/"
21939                                    + className + " to " + newState);
21940                }
21941            }
21942        }
21943        if (className == null) {
21944            // We're dealing with an application/package level state change
21945            synchronized (mPackages) {
21946                if (pkgSetting.getEnabled(userId) == newState) {
21947                    // Nothing to do
21948                    return;
21949                }
21950            }
21951            // If we're enabling a system stub, there's a little more work to do.
21952            // Prior to enabling the package, we need to decompress the APK(s) to the
21953            // data partition and then replace the version on the system partition.
21954            final PackageParser.Package deletedPkg = pkgSetting.pkg;
21955            final boolean isSystemStub = deletedPkg.isStub
21956                    && deletedPkg.isSystemApp();
21957            if (isSystemStub
21958                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21959                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
21960                final File codePath = decompressPackage(deletedPkg);
21961                if (codePath == null) {
21962                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
21963                    return;
21964                }
21965                // TODO remove direct parsing of the package object during internal cleanup
21966                // of scan package
21967                // We need to call parse directly here for no other reason than we need
21968                // the new package in order to disable the old one [we use the information
21969                // for some internal optimization to optionally create a new package setting
21970                // object on replace]. However, we can't get the package from the scan
21971                // because the scan modifies live structures and we need to remove the
21972                // old [system] package from the system before a scan can be attempted.
21973                // Once scan is indempotent we can remove this parse and use the package
21974                // object we scanned, prior to adding it to package settings.
21975                final PackageParser pp = new PackageParser();
21976                pp.setSeparateProcesses(mSeparateProcesses);
21977                pp.setDisplayMetrics(mMetrics);
21978                pp.setCallback(mPackageParserCallback);
21979                final PackageParser.Package tmpPkg;
21980                try {
21981                    final int parseFlags = mDefParseFlags
21982                            | PackageParser.PARSE_MUST_BE_APK
21983                            | PackageParser.PARSE_IS_SYSTEM
21984                            | PackageParser.PARSE_IS_SYSTEM_DIR;
21985                    tmpPkg = pp.parsePackage(codePath, parseFlags);
21986                } catch (PackageParserException e) {
21987                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
21988                    return;
21989                }
21990                synchronized (mInstallLock) {
21991                    // Disable the stub and remove any package entries
21992                    removePackageLI(deletedPkg, true);
21993                    synchronized (mPackages) {
21994                        disableSystemPackageLPw(deletedPkg, tmpPkg);
21995                    }
21996                    final PackageParser.Package newPkg;
21997                    try (PackageFreezer freezer =
21998                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21999                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
22000                                | PackageParser.PARSE_ENFORCE_CODE;
22001                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
22002                                0 /*currentTime*/, null /*user*/);
22003                        prepareAppDataAfterInstallLIF(newPkg);
22004                        synchronized (mPackages) {
22005                            try {
22006                                updateSharedLibrariesLPr(newPkg, null);
22007                            } catch (PackageManagerException e) {
22008                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
22009                            }
22010                            updatePermissionsLPw(newPkg.packageName, newPkg,
22011                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
22012                            mSettings.writeLPr();
22013                        }
22014                    } catch (PackageManagerException e) {
22015                        // Whoops! Something went wrong; try to roll back to the stub
22016                        Slog.w(TAG, "Failed to install compressed system package:"
22017                                + pkgSetting.name, e);
22018                        // Remove the failed install
22019                        removeCodePathLI(codePath);
22020
22021                        // Install the system package
22022                        try (PackageFreezer freezer =
22023                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
22024                            synchronized (mPackages) {
22025                                // NOTE: The system package always needs to be enabled; even
22026                                // if it's for a compressed stub. If we don't, installing the
22027                                // system package fails during scan [scanning checks the disabled
22028                                // packages]. We will reverse this later, after we've "installed"
22029                                // the stub.
22030                                // This leaves us in a fragile state; the stub should never be
22031                                // enabled, so, cross your fingers and hope nothing goes wrong
22032                                // until we can disable the package later.
22033                                enableSystemPackageLPw(deletedPkg);
22034                            }
22035                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
22036                                    false /*isPrivileged*/, null /*allUserHandles*/,
22037                                    null /*origUserHandles*/, null /*origPermissionsState*/,
22038                                    true /*writeSettings*/);
22039                        } catch (PackageManagerException pme) {
22040                            Slog.w(TAG, "Failed to restore system package:"
22041                                    + deletedPkg.packageName, pme);
22042                        } finally {
22043                            synchronized (mPackages) {
22044                                mSettings.disableSystemPackageLPw(
22045                                        deletedPkg.packageName, true /*replaced*/);
22046                                mSettings.writeLPr();
22047                            }
22048                        }
22049                        return;
22050                    }
22051                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
22052                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22053                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
22054                    mDexManager.notifyPackageUpdated(newPkg.packageName,
22055                            newPkg.baseCodePath, newPkg.splitCodePaths);
22056                }
22057            }
22058            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
22059                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
22060                // Don't care about who enables an app.
22061                callingPackage = null;
22062            }
22063            synchronized (mPackages) {
22064                pkgSetting.setEnabled(newState, userId, callingPackage);
22065            }
22066        } else {
22067            synchronized (mPackages) {
22068                // We're dealing with a component level state change
22069                // First, verify that this is a valid class name.
22070                PackageParser.Package pkg = pkgSetting.pkg;
22071                if (pkg == null || !pkg.hasComponentClassName(className)) {
22072                    if (pkg != null &&
22073                            pkg.applicationInfo.targetSdkVersion >=
22074                                    Build.VERSION_CODES.JELLY_BEAN) {
22075                        throw new IllegalArgumentException("Component class " + className
22076                                + " does not exist in " + packageName);
22077                    } else {
22078                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
22079                                + className + " does not exist in " + packageName);
22080                    }
22081                }
22082                switch (newState) {
22083                    case COMPONENT_ENABLED_STATE_ENABLED:
22084                        if (!pkgSetting.enableComponentLPw(className, userId)) {
22085                            return;
22086                        }
22087                        break;
22088                    case COMPONENT_ENABLED_STATE_DISABLED:
22089                        if (!pkgSetting.disableComponentLPw(className, userId)) {
22090                            return;
22091                        }
22092                        break;
22093                    case COMPONENT_ENABLED_STATE_DEFAULT:
22094                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
22095                            return;
22096                        }
22097                        break;
22098                    default:
22099                        Slog.e(TAG, "Invalid new component state: " + newState);
22100                        return;
22101                }
22102            }
22103        }
22104        synchronized (mPackages) {
22105            scheduleWritePackageRestrictionsLocked(userId);
22106            updateSequenceNumberLP(pkgSetting, new int[] { userId });
22107            final long callingId = Binder.clearCallingIdentity();
22108            try {
22109                updateInstantAppInstallerLocked(packageName);
22110            } finally {
22111                Binder.restoreCallingIdentity(callingId);
22112            }
22113            components = mPendingBroadcasts.get(userId, packageName);
22114            final boolean newPackage = components == null;
22115            if (newPackage) {
22116                components = new ArrayList<String>();
22117            }
22118            if (!components.contains(componentName)) {
22119                components.add(componentName);
22120            }
22121            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
22122                sendNow = true;
22123                // Purge entry from pending broadcast list if another one exists already
22124                // since we are sending one right away.
22125                mPendingBroadcasts.remove(userId, packageName);
22126            } else {
22127                if (newPackage) {
22128                    mPendingBroadcasts.put(userId, packageName, components);
22129                }
22130                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
22131                    // Schedule a message
22132                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
22133                }
22134            }
22135        }
22136
22137        long callingId = Binder.clearCallingIdentity();
22138        try {
22139            if (sendNow) {
22140                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
22141                sendPackageChangedBroadcast(packageName,
22142                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
22143            }
22144        } finally {
22145            Binder.restoreCallingIdentity(callingId);
22146        }
22147    }
22148
22149    @Override
22150    public void flushPackageRestrictionsAsUser(int userId) {
22151        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22152            return;
22153        }
22154        if (!sUserManager.exists(userId)) {
22155            return;
22156        }
22157        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
22158                false /* checkShell */, "flushPackageRestrictions");
22159        synchronized (mPackages) {
22160            mSettings.writePackageRestrictionsLPr(userId);
22161            mDirtyUsers.remove(userId);
22162            if (mDirtyUsers.isEmpty()) {
22163                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
22164            }
22165        }
22166    }
22167
22168    private void sendPackageChangedBroadcast(String packageName,
22169            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
22170        if (DEBUG_INSTALL)
22171            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
22172                    + componentNames);
22173        Bundle extras = new Bundle(4);
22174        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
22175        String nameList[] = new String[componentNames.size()];
22176        componentNames.toArray(nameList);
22177        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
22178        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
22179        extras.putInt(Intent.EXTRA_UID, packageUid);
22180        // If this is not reporting a change of the overall package, then only send it
22181        // to registered receivers.  We don't want to launch a swath of apps for every
22182        // little component state change.
22183        final int flags = !componentNames.contains(packageName)
22184                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
22185        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
22186                new int[] {UserHandle.getUserId(packageUid)});
22187    }
22188
22189    @Override
22190    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
22191        if (!sUserManager.exists(userId)) return;
22192        final int callingUid = Binder.getCallingUid();
22193        if (getInstantAppPackageName(callingUid) != null) {
22194            return;
22195        }
22196        final int permission = mContext.checkCallingOrSelfPermission(
22197                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
22198        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
22199        enforceCrossUserPermission(callingUid, userId,
22200                true /* requireFullPermission */, true /* checkShell */, "stop package");
22201        // writer
22202        synchronized (mPackages) {
22203            final PackageSetting ps = mSettings.mPackages.get(packageName);
22204            if (!filterAppAccessLPr(ps, callingUid, userId)
22205                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
22206                            allowedByPermission, callingUid, userId)) {
22207                scheduleWritePackageRestrictionsLocked(userId);
22208            }
22209        }
22210    }
22211
22212    @Override
22213    public String getInstallerPackageName(String packageName) {
22214        final int callingUid = Binder.getCallingUid();
22215        if (getInstantAppPackageName(callingUid) != null) {
22216            return null;
22217        }
22218        // reader
22219        synchronized (mPackages) {
22220            final PackageSetting ps = mSettings.mPackages.get(packageName);
22221            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
22222                return null;
22223            }
22224            return mSettings.getInstallerPackageNameLPr(packageName);
22225        }
22226    }
22227
22228    public boolean isOrphaned(String packageName) {
22229        // reader
22230        synchronized (mPackages) {
22231            return mSettings.isOrphaned(packageName);
22232        }
22233    }
22234
22235    @Override
22236    public int getApplicationEnabledSetting(String packageName, int userId) {
22237        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22238        int callingUid = Binder.getCallingUid();
22239        enforceCrossUserPermission(callingUid, userId,
22240                false /* requireFullPermission */, false /* checkShell */, "get enabled");
22241        // reader
22242        synchronized (mPackages) {
22243            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
22244                return COMPONENT_ENABLED_STATE_DISABLED;
22245            }
22246            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
22247        }
22248    }
22249
22250    @Override
22251    public int getComponentEnabledSetting(ComponentName component, int userId) {
22252        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22253        int callingUid = Binder.getCallingUid();
22254        enforceCrossUserPermission(callingUid, userId,
22255                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
22256        synchronized (mPackages) {
22257            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
22258                    component, TYPE_UNKNOWN, userId)) {
22259                return COMPONENT_ENABLED_STATE_DISABLED;
22260            }
22261            return mSettings.getComponentEnabledSettingLPr(component, userId);
22262        }
22263    }
22264
22265    @Override
22266    public void enterSafeMode() {
22267        enforceSystemOrRoot("Only the system can request entering safe mode");
22268
22269        if (!mSystemReady) {
22270            mSafeMode = true;
22271        }
22272    }
22273
22274    @Override
22275    public void systemReady() {
22276        enforceSystemOrRoot("Only the system can claim the system is ready");
22277
22278        mSystemReady = true;
22279        final ContentResolver resolver = mContext.getContentResolver();
22280        ContentObserver co = new ContentObserver(mHandler) {
22281            @Override
22282            public void onChange(boolean selfChange) {
22283                mEphemeralAppsDisabled =
22284                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
22285                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
22286            }
22287        };
22288        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22289                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
22290                false, co, UserHandle.USER_SYSTEM);
22291        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22292                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
22293        co.onChange(true);
22294
22295        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
22296        // disabled after already being started.
22297        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
22298                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
22299
22300        // Read the compatibilty setting when the system is ready.
22301        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
22302                mContext.getContentResolver(),
22303                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
22304        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
22305        if (DEBUG_SETTINGS) {
22306            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
22307        }
22308
22309        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
22310
22311        synchronized (mPackages) {
22312            // Verify that all of the preferred activity components actually
22313            // exist.  It is possible for applications to be updated and at
22314            // that point remove a previously declared activity component that
22315            // had been set as a preferred activity.  We try to clean this up
22316            // the next time we encounter that preferred activity, but it is
22317            // possible for the user flow to never be able to return to that
22318            // situation so here we do a sanity check to make sure we haven't
22319            // left any junk around.
22320            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
22321            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22322                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22323                removed.clear();
22324                for (PreferredActivity pa : pir.filterSet()) {
22325                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
22326                        removed.add(pa);
22327                    }
22328                }
22329                if (removed.size() > 0) {
22330                    for (int r=0; r<removed.size(); r++) {
22331                        PreferredActivity pa = removed.get(r);
22332                        Slog.w(TAG, "Removing dangling preferred activity: "
22333                                + pa.mPref.mComponent);
22334                        pir.removeFilter(pa);
22335                    }
22336                    mSettings.writePackageRestrictionsLPr(
22337                            mSettings.mPreferredActivities.keyAt(i));
22338                }
22339            }
22340
22341            for (int userId : UserManagerService.getInstance().getUserIds()) {
22342                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
22343                    grantPermissionsUserIds = ArrayUtils.appendInt(
22344                            grantPermissionsUserIds, userId);
22345                }
22346            }
22347        }
22348        sUserManager.systemReady();
22349
22350        // If we upgraded grant all default permissions before kicking off.
22351        for (int userId : grantPermissionsUserIds) {
22352            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22353        }
22354
22355        // If we did not grant default permissions, we preload from this the
22356        // default permission exceptions lazily to ensure we don't hit the
22357        // disk on a new user creation.
22358        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
22359            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
22360        }
22361
22362        // Kick off any messages waiting for system ready
22363        if (mPostSystemReadyMessages != null) {
22364            for (Message msg : mPostSystemReadyMessages) {
22365                msg.sendToTarget();
22366            }
22367            mPostSystemReadyMessages = null;
22368        }
22369
22370        // Watch for external volumes that come and go over time
22371        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22372        storage.registerListener(mStorageListener);
22373
22374        mInstallerService.systemReady();
22375        mPackageDexOptimizer.systemReady();
22376
22377        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22378                StorageManagerInternal.class);
22379        StorageManagerInternal.addExternalStoragePolicy(
22380                new StorageManagerInternal.ExternalStorageMountPolicy() {
22381            @Override
22382            public int getMountMode(int uid, String packageName) {
22383                if (Process.isIsolated(uid)) {
22384                    return Zygote.MOUNT_EXTERNAL_NONE;
22385                }
22386                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22387                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22388                }
22389                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22390                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22391                }
22392                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22393                    return Zygote.MOUNT_EXTERNAL_READ;
22394                }
22395                return Zygote.MOUNT_EXTERNAL_WRITE;
22396            }
22397
22398            @Override
22399            public boolean hasExternalStorage(int uid, String packageName) {
22400                return true;
22401            }
22402        });
22403
22404        // Now that we're mostly running, clean up stale users and apps
22405        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22406        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22407
22408        if (mPrivappPermissionsViolations != null) {
22409            Slog.wtf(TAG,"Signature|privileged permissions not in "
22410                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22411            mPrivappPermissionsViolations = null;
22412        }
22413    }
22414
22415    public void waitForAppDataPrepared() {
22416        if (mPrepareAppDataFuture == null) {
22417            return;
22418        }
22419        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22420        mPrepareAppDataFuture = null;
22421    }
22422
22423    @Override
22424    public boolean isSafeMode() {
22425        // allow instant applications
22426        return mSafeMode;
22427    }
22428
22429    @Override
22430    public boolean hasSystemUidErrors() {
22431        // allow instant applications
22432        return mHasSystemUidErrors;
22433    }
22434
22435    static String arrayToString(int[] array) {
22436        StringBuffer buf = new StringBuffer(128);
22437        buf.append('[');
22438        if (array != null) {
22439            for (int i=0; i<array.length; i++) {
22440                if (i > 0) buf.append(", ");
22441                buf.append(array[i]);
22442            }
22443        }
22444        buf.append(']');
22445        return buf.toString();
22446    }
22447
22448    static class DumpState {
22449        public static final int DUMP_LIBS = 1 << 0;
22450        public static final int DUMP_FEATURES = 1 << 1;
22451        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22452        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22453        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22454        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22455        public static final int DUMP_PERMISSIONS = 1 << 6;
22456        public static final int DUMP_PACKAGES = 1 << 7;
22457        public static final int DUMP_SHARED_USERS = 1 << 8;
22458        public static final int DUMP_MESSAGES = 1 << 9;
22459        public static final int DUMP_PROVIDERS = 1 << 10;
22460        public static final int DUMP_VERIFIERS = 1 << 11;
22461        public static final int DUMP_PREFERRED = 1 << 12;
22462        public static final int DUMP_PREFERRED_XML = 1 << 13;
22463        public static final int DUMP_KEYSETS = 1 << 14;
22464        public static final int DUMP_VERSION = 1 << 15;
22465        public static final int DUMP_INSTALLS = 1 << 16;
22466        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22467        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22468        public static final int DUMP_FROZEN = 1 << 19;
22469        public static final int DUMP_DEXOPT = 1 << 20;
22470        public static final int DUMP_COMPILER_STATS = 1 << 21;
22471        public static final int DUMP_CHANGES = 1 << 22;
22472        public static final int DUMP_VOLUMES = 1 << 23;
22473
22474        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22475
22476        private int mTypes;
22477
22478        private int mOptions;
22479
22480        private boolean mTitlePrinted;
22481
22482        private SharedUserSetting mSharedUser;
22483
22484        public boolean isDumping(int type) {
22485            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22486                return true;
22487            }
22488
22489            return (mTypes & type) != 0;
22490        }
22491
22492        public void setDump(int type) {
22493            mTypes |= type;
22494        }
22495
22496        public boolean isOptionEnabled(int option) {
22497            return (mOptions & option) != 0;
22498        }
22499
22500        public void setOptionEnabled(int option) {
22501            mOptions |= option;
22502        }
22503
22504        public boolean onTitlePrinted() {
22505            final boolean printed = mTitlePrinted;
22506            mTitlePrinted = true;
22507            return printed;
22508        }
22509
22510        public boolean getTitlePrinted() {
22511            return mTitlePrinted;
22512        }
22513
22514        public void setTitlePrinted(boolean enabled) {
22515            mTitlePrinted = enabled;
22516        }
22517
22518        public SharedUserSetting getSharedUser() {
22519            return mSharedUser;
22520        }
22521
22522        public void setSharedUser(SharedUserSetting user) {
22523            mSharedUser = user;
22524        }
22525    }
22526
22527    @Override
22528    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22529            FileDescriptor err, String[] args, ShellCallback callback,
22530            ResultReceiver resultReceiver) {
22531        (new PackageManagerShellCommand(this)).exec(
22532                this, in, out, err, args, callback, resultReceiver);
22533    }
22534
22535    @Override
22536    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22537        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22538
22539        DumpState dumpState = new DumpState();
22540        boolean fullPreferred = false;
22541        boolean checkin = false;
22542
22543        String packageName = null;
22544        ArraySet<String> permissionNames = null;
22545
22546        int opti = 0;
22547        while (opti < args.length) {
22548            String opt = args[opti];
22549            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22550                break;
22551            }
22552            opti++;
22553
22554            if ("-a".equals(opt)) {
22555                // Right now we only know how to print all.
22556            } else if ("-h".equals(opt)) {
22557                pw.println("Package manager dump options:");
22558                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22559                pw.println("    --checkin: dump for a checkin");
22560                pw.println("    -f: print details of intent filters");
22561                pw.println("    -h: print this help");
22562                pw.println("  cmd may be one of:");
22563                pw.println("    l[ibraries]: list known shared libraries");
22564                pw.println("    f[eatures]: list device features");
22565                pw.println("    k[eysets]: print known keysets");
22566                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22567                pw.println("    perm[issions]: dump permissions");
22568                pw.println("    permission [name ...]: dump declaration and use of given permission");
22569                pw.println("    pref[erred]: print preferred package settings");
22570                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22571                pw.println("    prov[iders]: dump content providers");
22572                pw.println("    p[ackages]: dump installed packages");
22573                pw.println("    s[hared-users]: dump shared user IDs");
22574                pw.println("    m[essages]: print collected runtime messages");
22575                pw.println("    v[erifiers]: print package verifier info");
22576                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22577                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22578                pw.println("    version: print database version info");
22579                pw.println("    write: write current settings now");
22580                pw.println("    installs: details about install sessions");
22581                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22582                pw.println("    dexopt: dump dexopt state");
22583                pw.println("    compiler-stats: dump compiler statistics");
22584                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22585                pw.println("    <package.name>: info about given package");
22586                return;
22587            } else if ("--checkin".equals(opt)) {
22588                checkin = true;
22589            } else if ("-f".equals(opt)) {
22590                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22591            } else if ("--proto".equals(opt)) {
22592                dumpProto(fd);
22593                return;
22594            } else {
22595                pw.println("Unknown argument: " + opt + "; use -h for help");
22596            }
22597        }
22598
22599        // Is the caller requesting to dump a particular piece of data?
22600        if (opti < args.length) {
22601            String cmd = args[opti];
22602            opti++;
22603            // Is this a package name?
22604            if ("android".equals(cmd) || cmd.contains(".")) {
22605                packageName = cmd;
22606                // When dumping a single package, we always dump all of its
22607                // filter information since the amount of data will be reasonable.
22608                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22609            } else if ("check-permission".equals(cmd)) {
22610                if (opti >= args.length) {
22611                    pw.println("Error: check-permission missing permission argument");
22612                    return;
22613                }
22614                String perm = args[opti];
22615                opti++;
22616                if (opti >= args.length) {
22617                    pw.println("Error: check-permission missing package argument");
22618                    return;
22619                }
22620
22621                String pkg = args[opti];
22622                opti++;
22623                int user = UserHandle.getUserId(Binder.getCallingUid());
22624                if (opti < args.length) {
22625                    try {
22626                        user = Integer.parseInt(args[opti]);
22627                    } catch (NumberFormatException e) {
22628                        pw.println("Error: check-permission user argument is not a number: "
22629                                + args[opti]);
22630                        return;
22631                    }
22632                }
22633
22634                // Normalize package name to handle renamed packages and static libs
22635                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22636
22637                pw.println(checkPermission(perm, pkg, user));
22638                return;
22639            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22640                dumpState.setDump(DumpState.DUMP_LIBS);
22641            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22642                dumpState.setDump(DumpState.DUMP_FEATURES);
22643            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22644                if (opti >= args.length) {
22645                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22646                            | DumpState.DUMP_SERVICE_RESOLVERS
22647                            | DumpState.DUMP_RECEIVER_RESOLVERS
22648                            | DumpState.DUMP_CONTENT_RESOLVERS);
22649                } else {
22650                    while (opti < args.length) {
22651                        String name = args[opti];
22652                        if ("a".equals(name) || "activity".equals(name)) {
22653                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22654                        } else if ("s".equals(name) || "service".equals(name)) {
22655                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22656                        } else if ("r".equals(name) || "receiver".equals(name)) {
22657                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22658                        } else if ("c".equals(name) || "content".equals(name)) {
22659                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22660                        } else {
22661                            pw.println("Error: unknown resolver table type: " + name);
22662                            return;
22663                        }
22664                        opti++;
22665                    }
22666                }
22667            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22668                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22669            } else if ("permission".equals(cmd)) {
22670                if (opti >= args.length) {
22671                    pw.println("Error: permission requires permission name");
22672                    return;
22673                }
22674                permissionNames = new ArraySet<>();
22675                while (opti < args.length) {
22676                    permissionNames.add(args[opti]);
22677                    opti++;
22678                }
22679                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22680                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22681            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22682                dumpState.setDump(DumpState.DUMP_PREFERRED);
22683            } else if ("preferred-xml".equals(cmd)) {
22684                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22685                if (opti < args.length && "--full".equals(args[opti])) {
22686                    fullPreferred = true;
22687                    opti++;
22688                }
22689            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22690                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22691            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22692                dumpState.setDump(DumpState.DUMP_PACKAGES);
22693            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22694                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22695            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22696                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22697            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22698                dumpState.setDump(DumpState.DUMP_MESSAGES);
22699            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22700                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22701            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22702                    || "intent-filter-verifiers".equals(cmd)) {
22703                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22704            } else if ("version".equals(cmd)) {
22705                dumpState.setDump(DumpState.DUMP_VERSION);
22706            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22707                dumpState.setDump(DumpState.DUMP_KEYSETS);
22708            } else if ("installs".equals(cmd)) {
22709                dumpState.setDump(DumpState.DUMP_INSTALLS);
22710            } else if ("frozen".equals(cmd)) {
22711                dumpState.setDump(DumpState.DUMP_FROZEN);
22712            } else if ("volumes".equals(cmd)) {
22713                dumpState.setDump(DumpState.DUMP_VOLUMES);
22714            } else if ("dexopt".equals(cmd)) {
22715                dumpState.setDump(DumpState.DUMP_DEXOPT);
22716            } else if ("compiler-stats".equals(cmd)) {
22717                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22718            } else if ("changes".equals(cmd)) {
22719                dumpState.setDump(DumpState.DUMP_CHANGES);
22720            } else if ("write".equals(cmd)) {
22721                synchronized (mPackages) {
22722                    mSettings.writeLPr();
22723                    pw.println("Settings written.");
22724                    return;
22725                }
22726            }
22727        }
22728
22729        if (checkin) {
22730            pw.println("vers,1");
22731        }
22732
22733        // reader
22734        synchronized (mPackages) {
22735            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22736                if (!checkin) {
22737                    if (dumpState.onTitlePrinted())
22738                        pw.println();
22739                    pw.println("Database versions:");
22740                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22741                }
22742            }
22743
22744            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22745                if (!checkin) {
22746                    if (dumpState.onTitlePrinted())
22747                        pw.println();
22748                    pw.println("Verifiers:");
22749                    pw.print("  Required: ");
22750                    pw.print(mRequiredVerifierPackage);
22751                    pw.print(" (uid=");
22752                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22753                            UserHandle.USER_SYSTEM));
22754                    pw.println(")");
22755                } else if (mRequiredVerifierPackage != null) {
22756                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22757                    pw.print(",");
22758                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22759                            UserHandle.USER_SYSTEM));
22760                }
22761            }
22762
22763            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22764                    packageName == null) {
22765                if (mIntentFilterVerifierComponent != null) {
22766                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22767                    if (!checkin) {
22768                        if (dumpState.onTitlePrinted())
22769                            pw.println();
22770                        pw.println("Intent Filter Verifier:");
22771                        pw.print("  Using: ");
22772                        pw.print(verifierPackageName);
22773                        pw.print(" (uid=");
22774                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22775                                UserHandle.USER_SYSTEM));
22776                        pw.println(")");
22777                    } else if (verifierPackageName != null) {
22778                        pw.print("ifv,"); pw.print(verifierPackageName);
22779                        pw.print(",");
22780                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22781                                UserHandle.USER_SYSTEM));
22782                    }
22783                } else {
22784                    pw.println();
22785                    pw.println("No Intent Filter Verifier available!");
22786                }
22787            }
22788
22789            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22790                boolean printedHeader = false;
22791                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22792                while (it.hasNext()) {
22793                    String libName = it.next();
22794                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22795                    if (versionedLib == null) {
22796                        continue;
22797                    }
22798                    final int versionCount = versionedLib.size();
22799                    for (int i = 0; i < versionCount; i++) {
22800                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22801                        if (!checkin) {
22802                            if (!printedHeader) {
22803                                if (dumpState.onTitlePrinted())
22804                                    pw.println();
22805                                pw.println("Libraries:");
22806                                printedHeader = true;
22807                            }
22808                            pw.print("  ");
22809                        } else {
22810                            pw.print("lib,");
22811                        }
22812                        pw.print(libEntry.info.getName());
22813                        if (libEntry.info.isStatic()) {
22814                            pw.print(" version=" + libEntry.info.getVersion());
22815                        }
22816                        if (!checkin) {
22817                            pw.print(" -> ");
22818                        }
22819                        if (libEntry.path != null) {
22820                            pw.print(" (jar) ");
22821                            pw.print(libEntry.path);
22822                        } else {
22823                            pw.print(" (apk) ");
22824                            pw.print(libEntry.apk);
22825                        }
22826                        pw.println();
22827                    }
22828                }
22829            }
22830
22831            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22832                if (dumpState.onTitlePrinted())
22833                    pw.println();
22834                if (!checkin) {
22835                    pw.println("Features:");
22836                }
22837
22838                synchronized (mAvailableFeatures) {
22839                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22840                        if (checkin) {
22841                            pw.print("feat,");
22842                            pw.print(feat.name);
22843                            pw.print(",");
22844                            pw.println(feat.version);
22845                        } else {
22846                            pw.print("  ");
22847                            pw.print(feat.name);
22848                            if (feat.version > 0) {
22849                                pw.print(" version=");
22850                                pw.print(feat.version);
22851                            }
22852                            pw.println();
22853                        }
22854                    }
22855                }
22856            }
22857
22858            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22859                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22860                        : "Activity Resolver Table:", "  ", packageName,
22861                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22862                    dumpState.setTitlePrinted(true);
22863                }
22864            }
22865            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22866                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22867                        : "Receiver Resolver Table:", "  ", packageName,
22868                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22869                    dumpState.setTitlePrinted(true);
22870                }
22871            }
22872            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22873                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22874                        : "Service Resolver Table:", "  ", packageName,
22875                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22876                    dumpState.setTitlePrinted(true);
22877                }
22878            }
22879            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22880                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22881                        : "Provider Resolver Table:", "  ", packageName,
22882                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22883                    dumpState.setTitlePrinted(true);
22884                }
22885            }
22886
22887            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22888                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22889                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22890                    int user = mSettings.mPreferredActivities.keyAt(i);
22891                    if (pir.dump(pw,
22892                            dumpState.getTitlePrinted()
22893                                ? "\nPreferred Activities User " + user + ":"
22894                                : "Preferred Activities User " + user + ":", "  ",
22895                            packageName, true, false)) {
22896                        dumpState.setTitlePrinted(true);
22897                    }
22898                }
22899            }
22900
22901            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22902                pw.flush();
22903                FileOutputStream fout = new FileOutputStream(fd);
22904                BufferedOutputStream str = new BufferedOutputStream(fout);
22905                XmlSerializer serializer = new FastXmlSerializer();
22906                try {
22907                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22908                    serializer.startDocument(null, true);
22909                    serializer.setFeature(
22910                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22911                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22912                    serializer.endDocument();
22913                    serializer.flush();
22914                } catch (IllegalArgumentException e) {
22915                    pw.println("Failed writing: " + e);
22916                } catch (IllegalStateException e) {
22917                    pw.println("Failed writing: " + e);
22918                } catch (IOException e) {
22919                    pw.println("Failed writing: " + e);
22920                }
22921            }
22922
22923            if (!checkin
22924                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22925                    && packageName == null) {
22926                pw.println();
22927                int count = mSettings.mPackages.size();
22928                if (count == 0) {
22929                    pw.println("No applications!");
22930                    pw.println();
22931                } else {
22932                    final String prefix = "  ";
22933                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22934                    if (allPackageSettings.size() == 0) {
22935                        pw.println("No domain preferred apps!");
22936                        pw.println();
22937                    } else {
22938                        pw.println("App verification status:");
22939                        pw.println();
22940                        count = 0;
22941                        for (PackageSetting ps : allPackageSettings) {
22942                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22943                            if (ivi == null || ivi.getPackageName() == null) continue;
22944                            pw.println(prefix + "Package: " + ivi.getPackageName());
22945                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22946                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22947                            pw.println();
22948                            count++;
22949                        }
22950                        if (count == 0) {
22951                            pw.println(prefix + "No app verification established.");
22952                            pw.println();
22953                        }
22954                        for (int userId : sUserManager.getUserIds()) {
22955                            pw.println("App linkages for user " + userId + ":");
22956                            pw.println();
22957                            count = 0;
22958                            for (PackageSetting ps : allPackageSettings) {
22959                                final long status = ps.getDomainVerificationStatusForUser(userId);
22960                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22961                                        && !DEBUG_DOMAIN_VERIFICATION) {
22962                                    continue;
22963                                }
22964                                pw.println(prefix + "Package: " + ps.name);
22965                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22966                                String statusStr = IntentFilterVerificationInfo.
22967                                        getStatusStringFromValue(status);
22968                                pw.println(prefix + "Status:  " + statusStr);
22969                                pw.println();
22970                                count++;
22971                            }
22972                            if (count == 0) {
22973                                pw.println(prefix + "No configured app linkages.");
22974                                pw.println();
22975                            }
22976                        }
22977                    }
22978                }
22979            }
22980
22981            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22982                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22983                if (packageName == null && permissionNames == null) {
22984                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22985                        if (iperm == 0) {
22986                            if (dumpState.onTitlePrinted())
22987                                pw.println();
22988                            pw.println("AppOp Permissions:");
22989                        }
22990                        pw.print("  AppOp Permission ");
22991                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22992                        pw.println(":");
22993                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22994                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22995                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22996                        }
22997                    }
22998                }
22999            }
23000
23001            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
23002                boolean printedSomething = false;
23003                for (PackageParser.Provider p : mProviders.mProviders.values()) {
23004                    if (packageName != null && !packageName.equals(p.info.packageName)) {
23005                        continue;
23006                    }
23007                    if (!printedSomething) {
23008                        if (dumpState.onTitlePrinted())
23009                            pw.println();
23010                        pw.println("Registered ContentProviders:");
23011                        printedSomething = true;
23012                    }
23013                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
23014                    pw.print("    "); pw.println(p.toString());
23015                }
23016                printedSomething = false;
23017                for (Map.Entry<String, PackageParser.Provider> entry :
23018                        mProvidersByAuthority.entrySet()) {
23019                    PackageParser.Provider p = entry.getValue();
23020                    if (packageName != null && !packageName.equals(p.info.packageName)) {
23021                        continue;
23022                    }
23023                    if (!printedSomething) {
23024                        if (dumpState.onTitlePrinted())
23025                            pw.println();
23026                        pw.println("ContentProvider Authorities:");
23027                        printedSomething = true;
23028                    }
23029                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
23030                    pw.print("    "); pw.println(p.toString());
23031                    if (p.info != null && p.info.applicationInfo != null) {
23032                        final String appInfo = p.info.applicationInfo.toString();
23033                        pw.print("      applicationInfo="); pw.println(appInfo);
23034                    }
23035                }
23036            }
23037
23038            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
23039                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
23040            }
23041
23042            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
23043                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
23044            }
23045
23046            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
23047                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
23048            }
23049
23050            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
23051                if (dumpState.onTitlePrinted()) pw.println();
23052                pw.println("Package Changes:");
23053                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
23054                final int K = mChangedPackages.size();
23055                for (int i = 0; i < K; i++) {
23056                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
23057                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
23058                    final int N = changes.size();
23059                    if (N == 0) {
23060                        pw.print("    "); pw.println("No packages changed");
23061                    } else {
23062                        for (int j = 0; j < N; j++) {
23063                            final String pkgName = changes.valueAt(j);
23064                            final int sequenceNumber = changes.keyAt(j);
23065                            pw.print("    ");
23066                            pw.print("seq=");
23067                            pw.print(sequenceNumber);
23068                            pw.print(", package=");
23069                            pw.println(pkgName);
23070                        }
23071                    }
23072                }
23073            }
23074
23075            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
23076                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
23077            }
23078
23079            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
23080                // XXX should handle packageName != null by dumping only install data that
23081                // the given package is involved with.
23082                if (dumpState.onTitlePrinted()) pw.println();
23083
23084                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23085                ipw.println();
23086                ipw.println("Frozen packages:");
23087                ipw.increaseIndent();
23088                if (mFrozenPackages.size() == 0) {
23089                    ipw.println("(none)");
23090                } else {
23091                    for (int i = 0; i < mFrozenPackages.size(); i++) {
23092                        ipw.println(mFrozenPackages.valueAt(i));
23093                    }
23094                }
23095                ipw.decreaseIndent();
23096            }
23097
23098            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
23099                if (dumpState.onTitlePrinted()) pw.println();
23100
23101                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23102                ipw.println();
23103                ipw.println("Loaded volumes:");
23104                ipw.increaseIndent();
23105                if (mLoadedVolumes.size() == 0) {
23106                    ipw.println("(none)");
23107                } else {
23108                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
23109                        ipw.println(mLoadedVolumes.valueAt(i));
23110                    }
23111                }
23112                ipw.decreaseIndent();
23113            }
23114
23115            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
23116                if (dumpState.onTitlePrinted()) pw.println();
23117                dumpDexoptStateLPr(pw, packageName);
23118            }
23119
23120            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
23121                if (dumpState.onTitlePrinted()) pw.println();
23122                dumpCompilerStatsLPr(pw, packageName);
23123            }
23124
23125            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
23126                if (dumpState.onTitlePrinted()) pw.println();
23127                mSettings.dumpReadMessagesLPr(pw, dumpState);
23128
23129                pw.println();
23130                pw.println("Package warning messages:");
23131                BufferedReader in = null;
23132                String line = null;
23133                try {
23134                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23135                    while ((line = in.readLine()) != null) {
23136                        if (line.contains("ignored: updated version")) continue;
23137                        pw.println(line);
23138                    }
23139                } catch (IOException ignored) {
23140                } finally {
23141                    IoUtils.closeQuietly(in);
23142                }
23143            }
23144
23145            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
23146                BufferedReader in = null;
23147                String line = null;
23148                try {
23149                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23150                    while ((line = in.readLine()) != null) {
23151                        if (line.contains("ignored: updated version")) continue;
23152                        pw.print("msg,");
23153                        pw.println(line);
23154                    }
23155                } catch (IOException ignored) {
23156                } finally {
23157                    IoUtils.closeQuietly(in);
23158                }
23159            }
23160        }
23161
23162        // PackageInstaller should be called outside of mPackages lock
23163        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
23164            // XXX should handle packageName != null by dumping only install data that
23165            // the given package is involved with.
23166            if (dumpState.onTitlePrinted()) pw.println();
23167            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
23168        }
23169    }
23170
23171    private void dumpProto(FileDescriptor fd) {
23172        final ProtoOutputStream proto = new ProtoOutputStream(fd);
23173
23174        synchronized (mPackages) {
23175            final long requiredVerifierPackageToken =
23176                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
23177            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
23178            proto.write(
23179                    PackageServiceDumpProto.PackageShortProto.UID,
23180                    getPackageUid(
23181                            mRequiredVerifierPackage,
23182                            MATCH_DEBUG_TRIAGED_MISSING,
23183                            UserHandle.USER_SYSTEM));
23184            proto.end(requiredVerifierPackageToken);
23185
23186            if (mIntentFilterVerifierComponent != null) {
23187                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
23188                final long verifierPackageToken =
23189                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
23190                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
23191                proto.write(
23192                        PackageServiceDumpProto.PackageShortProto.UID,
23193                        getPackageUid(
23194                                verifierPackageName,
23195                                MATCH_DEBUG_TRIAGED_MISSING,
23196                                UserHandle.USER_SYSTEM));
23197                proto.end(verifierPackageToken);
23198            }
23199
23200            dumpSharedLibrariesProto(proto);
23201            dumpFeaturesProto(proto);
23202            mSettings.dumpPackagesProto(proto);
23203            mSettings.dumpSharedUsersProto(proto);
23204            dumpMessagesProto(proto);
23205        }
23206        proto.flush();
23207    }
23208
23209    private void dumpMessagesProto(ProtoOutputStream proto) {
23210        BufferedReader in = null;
23211        String line = null;
23212        try {
23213            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23214            while ((line = in.readLine()) != null) {
23215                if (line.contains("ignored: updated version")) continue;
23216                proto.write(PackageServiceDumpProto.MESSAGES, line);
23217            }
23218        } catch (IOException ignored) {
23219        } finally {
23220            IoUtils.closeQuietly(in);
23221        }
23222    }
23223
23224    private void dumpFeaturesProto(ProtoOutputStream proto) {
23225        synchronized (mAvailableFeatures) {
23226            final int count = mAvailableFeatures.size();
23227            for (int i = 0; i < count; i++) {
23228                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
23229                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
23230                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
23231                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
23232                proto.end(featureToken);
23233            }
23234        }
23235    }
23236
23237    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
23238        final int count = mSharedLibraries.size();
23239        for (int i = 0; i < count; i++) {
23240            final String libName = mSharedLibraries.keyAt(i);
23241            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
23242            if (versionedLib == null) {
23243                continue;
23244            }
23245            final int versionCount = versionedLib.size();
23246            for (int j = 0; j < versionCount; j++) {
23247                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
23248                final long sharedLibraryToken =
23249                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
23250                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
23251                final boolean isJar = (libEntry.path != null);
23252                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
23253                if (isJar) {
23254                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
23255                } else {
23256                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
23257                }
23258                proto.end(sharedLibraryToken);
23259            }
23260        }
23261    }
23262
23263    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
23264        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23265        ipw.println();
23266        ipw.println("Dexopt state:");
23267        ipw.increaseIndent();
23268        Collection<PackageParser.Package> packages = null;
23269        if (packageName != null) {
23270            PackageParser.Package targetPackage = mPackages.get(packageName);
23271            if (targetPackage != null) {
23272                packages = Collections.singletonList(targetPackage);
23273            } else {
23274                ipw.println("Unable to find package: " + packageName);
23275                return;
23276            }
23277        } else {
23278            packages = mPackages.values();
23279        }
23280
23281        for (PackageParser.Package pkg : packages) {
23282            ipw.println("[" + pkg.packageName + "]");
23283            ipw.increaseIndent();
23284            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
23285                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
23286            ipw.decreaseIndent();
23287        }
23288    }
23289
23290    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
23291        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23292        ipw.println();
23293        ipw.println("Compiler stats:");
23294        ipw.increaseIndent();
23295        Collection<PackageParser.Package> packages = null;
23296        if (packageName != null) {
23297            PackageParser.Package targetPackage = mPackages.get(packageName);
23298            if (targetPackage != null) {
23299                packages = Collections.singletonList(targetPackage);
23300            } else {
23301                ipw.println("Unable to find package: " + packageName);
23302                return;
23303            }
23304        } else {
23305            packages = mPackages.values();
23306        }
23307
23308        for (PackageParser.Package pkg : packages) {
23309            ipw.println("[" + pkg.packageName + "]");
23310            ipw.increaseIndent();
23311
23312            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
23313            if (stats == null) {
23314                ipw.println("(No recorded stats)");
23315            } else {
23316                stats.dump(ipw);
23317            }
23318            ipw.decreaseIndent();
23319        }
23320    }
23321
23322    private String dumpDomainString(String packageName) {
23323        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
23324                .getList();
23325        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
23326
23327        ArraySet<String> result = new ArraySet<>();
23328        if (iviList.size() > 0) {
23329            for (IntentFilterVerificationInfo ivi : iviList) {
23330                for (String host : ivi.getDomains()) {
23331                    result.add(host);
23332                }
23333            }
23334        }
23335        if (filters != null && filters.size() > 0) {
23336            for (IntentFilter filter : filters) {
23337                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
23338                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
23339                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
23340                    result.addAll(filter.getHostsList());
23341                }
23342            }
23343        }
23344
23345        StringBuilder sb = new StringBuilder(result.size() * 16);
23346        for (String domain : result) {
23347            if (sb.length() > 0) sb.append(" ");
23348            sb.append(domain);
23349        }
23350        return sb.toString();
23351    }
23352
23353    // ------- apps on sdcard specific code -------
23354    static final boolean DEBUG_SD_INSTALL = false;
23355
23356    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
23357
23358    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
23359
23360    private boolean mMediaMounted = false;
23361
23362    static String getEncryptKey() {
23363        try {
23364            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
23365                    SD_ENCRYPTION_KEYSTORE_NAME);
23366            if (sdEncKey == null) {
23367                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23368                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23369                if (sdEncKey == null) {
23370                    Slog.e(TAG, "Failed to create encryption keys");
23371                    return null;
23372                }
23373            }
23374            return sdEncKey;
23375        } catch (NoSuchAlgorithmException nsae) {
23376            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23377            return null;
23378        } catch (IOException ioe) {
23379            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23380            return null;
23381        }
23382    }
23383
23384    /*
23385     * Update media status on PackageManager.
23386     */
23387    @Override
23388    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
23389        enforceSystemOrRoot("Media status can only be updated by the system");
23390        // reader; this apparently protects mMediaMounted, but should probably
23391        // be a different lock in that case.
23392        synchronized (mPackages) {
23393            Log.i(TAG, "Updating external media status from "
23394                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
23395                    + (mediaStatus ? "mounted" : "unmounted"));
23396            if (DEBUG_SD_INSTALL)
23397                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
23398                        + ", mMediaMounted=" + mMediaMounted);
23399            if (mediaStatus == mMediaMounted) {
23400                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
23401                        : 0, -1);
23402                mHandler.sendMessage(msg);
23403                return;
23404            }
23405            mMediaMounted = mediaStatus;
23406        }
23407        // Queue up an async operation since the package installation may take a
23408        // little while.
23409        mHandler.post(new Runnable() {
23410            public void run() {
23411                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23412            }
23413        });
23414    }
23415
23416    /**
23417     * Called by StorageManagerService when the initial ASECs to scan are available.
23418     * Should block until all the ASEC containers are finished being scanned.
23419     */
23420    public void scanAvailableAsecs() {
23421        updateExternalMediaStatusInner(true, false, false);
23422    }
23423
23424    /*
23425     * Collect information of applications on external media, map them against
23426     * existing containers and update information based on current mount status.
23427     * Please note that we always have to report status if reportStatus has been
23428     * set to true especially when unloading packages.
23429     */
23430    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23431            boolean externalStorage) {
23432        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23433        int[] uidArr = EmptyArray.INT;
23434
23435        final String[] list = PackageHelper.getSecureContainerList();
23436        if (ArrayUtils.isEmpty(list)) {
23437            Log.i(TAG, "No secure containers found");
23438        } else {
23439            // Process list of secure containers and categorize them
23440            // as active or stale based on their package internal state.
23441
23442            // reader
23443            synchronized (mPackages) {
23444                for (String cid : list) {
23445                    // Leave stages untouched for now; installer service owns them
23446                    if (PackageInstallerService.isStageName(cid)) continue;
23447
23448                    if (DEBUG_SD_INSTALL)
23449                        Log.i(TAG, "Processing container " + cid);
23450                    String pkgName = getAsecPackageName(cid);
23451                    if (pkgName == null) {
23452                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23453                        continue;
23454                    }
23455                    if (DEBUG_SD_INSTALL)
23456                        Log.i(TAG, "Looking for pkg : " + pkgName);
23457
23458                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23459                    if (ps == null) {
23460                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23461                        continue;
23462                    }
23463
23464                    /*
23465                     * Skip packages that are not external if we're unmounting
23466                     * external storage.
23467                     */
23468                    if (externalStorage && !isMounted && !isExternal(ps)) {
23469                        continue;
23470                    }
23471
23472                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23473                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23474                    // The package status is changed only if the code path
23475                    // matches between settings and the container id.
23476                    if (ps.codePathString != null
23477                            && ps.codePathString.startsWith(args.getCodePath())) {
23478                        if (DEBUG_SD_INSTALL) {
23479                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23480                                    + " at code path: " + ps.codePathString);
23481                        }
23482
23483                        // We do have a valid package installed on sdcard
23484                        processCids.put(args, ps.codePathString);
23485                        final int uid = ps.appId;
23486                        if (uid != -1) {
23487                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23488                        }
23489                    } else {
23490                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23491                                + ps.codePathString);
23492                    }
23493                }
23494            }
23495
23496            Arrays.sort(uidArr);
23497        }
23498
23499        // Process packages with valid entries.
23500        if (isMounted) {
23501            if (DEBUG_SD_INSTALL)
23502                Log.i(TAG, "Loading packages");
23503            loadMediaPackages(processCids, uidArr, externalStorage);
23504            startCleaningPackages();
23505            mInstallerService.onSecureContainersAvailable();
23506        } else {
23507            if (DEBUG_SD_INSTALL)
23508                Log.i(TAG, "Unloading packages");
23509            unloadMediaPackages(processCids, uidArr, reportStatus);
23510        }
23511    }
23512
23513    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23514            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23515        final int size = infos.size();
23516        final String[] packageNames = new String[size];
23517        final int[] packageUids = new int[size];
23518        for (int i = 0; i < size; i++) {
23519            final ApplicationInfo info = infos.get(i);
23520            packageNames[i] = info.packageName;
23521            packageUids[i] = info.uid;
23522        }
23523        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23524                finishedReceiver);
23525    }
23526
23527    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23528            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23529        sendResourcesChangedBroadcast(mediaStatus, replacing,
23530                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23531    }
23532
23533    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23534            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23535        int size = pkgList.length;
23536        if (size > 0) {
23537            // Send broadcasts here
23538            Bundle extras = new Bundle();
23539            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23540            if (uidArr != null) {
23541                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23542            }
23543            if (replacing) {
23544                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23545            }
23546            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23547                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23548            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23549        }
23550    }
23551
23552   /*
23553     * Look at potentially valid container ids from processCids If package
23554     * information doesn't match the one on record or package scanning fails,
23555     * the cid is added to list of removeCids. We currently don't delete stale
23556     * containers.
23557     */
23558    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23559            boolean externalStorage) {
23560        ArrayList<String> pkgList = new ArrayList<String>();
23561        Set<AsecInstallArgs> keys = processCids.keySet();
23562
23563        for (AsecInstallArgs args : keys) {
23564            String codePath = processCids.get(args);
23565            if (DEBUG_SD_INSTALL)
23566                Log.i(TAG, "Loading container : " + args.cid);
23567            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23568            try {
23569                // Make sure there are no container errors first.
23570                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23571                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23572                            + " when installing from sdcard");
23573                    continue;
23574                }
23575                // Check code path here.
23576                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23577                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23578                            + " does not match one in settings " + codePath);
23579                    continue;
23580                }
23581                // Parse package
23582                int parseFlags = mDefParseFlags;
23583                if (args.isExternalAsec()) {
23584                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23585                }
23586                if (args.isFwdLocked()) {
23587                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23588                }
23589
23590                synchronized (mInstallLock) {
23591                    PackageParser.Package pkg = null;
23592                    try {
23593                        // Sadly we don't know the package name yet to freeze it
23594                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23595                                SCAN_IGNORE_FROZEN, 0, null);
23596                    } catch (PackageManagerException e) {
23597                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23598                    }
23599                    // Scan the package
23600                    if (pkg != null) {
23601                        /*
23602                         * TODO why is the lock being held? doPostInstall is
23603                         * called in other places without the lock. This needs
23604                         * to be straightened out.
23605                         */
23606                        // writer
23607                        synchronized (mPackages) {
23608                            retCode = PackageManager.INSTALL_SUCCEEDED;
23609                            pkgList.add(pkg.packageName);
23610                            // Post process args
23611                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23612                                    pkg.applicationInfo.uid);
23613                        }
23614                    } else {
23615                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23616                    }
23617                }
23618
23619            } finally {
23620                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23621                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23622                }
23623            }
23624        }
23625        // writer
23626        synchronized (mPackages) {
23627            // If the platform SDK has changed since the last time we booted,
23628            // we need to re-grant app permission to catch any new ones that
23629            // appear. This is really a hack, and means that apps can in some
23630            // cases get permissions that the user didn't initially explicitly
23631            // allow... it would be nice to have some better way to handle
23632            // this situation.
23633            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23634                    : mSettings.getInternalVersion();
23635            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23636                    : StorageManager.UUID_PRIVATE_INTERNAL;
23637
23638            int updateFlags = UPDATE_PERMISSIONS_ALL;
23639            if (ver.sdkVersion != mSdkVersion) {
23640                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23641                        + mSdkVersion + "; regranting permissions for external");
23642                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23643            }
23644            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23645
23646            // Yay, everything is now upgraded
23647            ver.forceCurrent();
23648
23649            // can downgrade to reader
23650            // Persist settings
23651            mSettings.writeLPr();
23652        }
23653        // Send a broadcast to let everyone know we are done processing
23654        if (pkgList.size() > 0) {
23655            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23656        }
23657    }
23658
23659   /*
23660     * Utility method to unload a list of specified containers
23661     */
23662    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23663        // Just unmount all valid containers.
23664        for (AsecInstallArgs arg : cidArgs) {
23665            synchronized (mInstallLock) {
23666                arg.doPostDeleteLI(false);
23667           }
23668       }
23669   }
23670
23671    /*
23672     * Unload packages mounted on external media. This involves deleting package
23673     * data from internal structures, sending broadcasts about disabled packages,
23674     * gc'ing to free up references, unmounting all secure containers
23675     * corresponding to packages on external media, and posting a
23676     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23677     * that we always have to post this message if status has been requested no
23678     * matter what.
23679     */
23680    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23681            final boolean reportStatus) {
23682        if (DEBUG_SD_INSTALL)
23683            Log.i(TAG, "unloading media packages");
23684        ArrayList<String> pkgList = new ArrayList<String>();
23685        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23686        final Set<AsecInstallArgs> keys = processCids.keySet();
23687        for (AsecInstallArgs args : keys) {
23688            String pkgName = args.getPackageName();
23689            if (DEBUG_SD_INSTALL)
23690                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23691            // Delete package internally
23692            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23693            synchronized (mInstallLock) {
23694                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23695                final boolean res;
23696                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23697                        "unloadMediaPackages")) {
23698                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23699                            null);
23700                }
23701                if (res) {
23702                    pkgList.add(pkgName);
23703                } else {
23704                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23705                    failedList.add(args);
23706                }
23707            }
23708        }
23709
23710        // reader
23711        synchronized (mPackages) {
23712            // We didn't update the settings after removing each package;
23713            // write them now for all packages.
23714            mSettings.writeLPr();
23715        }
23716
23717        // We have to absolutely send UPDATED_MEDIA_STATUS only
23718        // after confirming that all the receivers processed the ordered
23719        // broadcast when packages get disabled, force a gc to clean things up.
23720        // and unload all the containers.
23721        if (pkgList.size() > 0) {
23722            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23723                    new IIntentReceiver.Stub() {
23724                public void performReceive(Intent intent, int resultCode, String data,
23725                        Bundle extras, boolean ordered, boolean sticky,
23726                        int sendingUser) throws RemoteException {
23727                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23728                            reportStatus ? 1 : 0, 1, keys);
23729                    mHandler.sendMessage(msg);
23730                }
23731            });
23732        } else {
23733            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23734                    keys);
23735            mHandler.sendMessage(msg);
23736        }
23737    }
23738
23739    private void loadPrivatePackages(final VolumeInfo vol) {
23740        mHandler.post(new Runnable() {
23741            @Override
23742            public void run() {
23743                loadPrivatePackagesInner(vol);
23744            }
23745        });
23746    }
23747
23748    private void loadPrivatePackagesInner(VolumeInfo vol) {
23749        final String volumeUuid = vol.fsUuid;
23750        if (TextUtils.isEmpty(volumeUuid)) {
23751            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23752            return;
23753        }
23754
23755        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23756        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23757        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23758
23759        final VersionInfo ver;
23760        final List<PackageSetting> packages;
23761        synchronized (mPackages) {
23762            ver = mSettings.findOrCreateVersion(volumeUuid);
23763            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23764        }
23765
23766        for (PackageSetting ps : packages) {
23767            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23768            synchronized (mInstallLock) {
23769                final PackageParser.Package pkg;
23770                try {
23771                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23772                    loaded.add(pkg.applicationInfo);
23773
23774                } catch (PackageManagerException e) {
23775                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23776                }
23777
23778                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23779                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23780                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23781                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23782                }
23783            }
23784        }
23785
23786        // Reconcile app data for all started/unlocked users
23787        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23788        final UserManager um = mContext.getSystemService(UserManager.class);
23789        UserManagerInternal umInternal = getUserManagerInternal();
23790        for (UserInfo user : um.getUsers()) {
23791            final int flags;
23792            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23793                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23794            } else if (umInternal.isUserRunning(user.id)) {
23795                flags = StorageManager.FLAG_STORAGE_DE;
23796            } else {
23797                continue;
23798            }
23799
23800            try {
23801                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23802                synchronized (mInstallLock) {
23803                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23804                }
23805            } catch (IllegalStateException e) {
23806                // Device was probably ejected, and we'll process that event momentarily
23807                Slog.w(TAG, "Failed to prepare storage: " + e);
23808            }
23809        }
23810
23811        synchronized (mPackages) {
23812            int updateFlags = UPDATE_PERMISSIONS_ALL;
23813            if (ver.sdkVersion != mSdkVersion) {
23814                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23815                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23816                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23817            }
23818            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23819
23820            // Yay, everything is now upgraded
23821            ver.forceCurrent();
23822
23823            mSettings.writeLPr();
23824        }
23825
23826        for (PackageFreezer freezer : freezers) {
23827            freezer.close();
23828        }
23829
23830        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23831        sendResourcesChangedBroadcast(true, false, loaded, null);
23832        mLoadedVolumes.add(vol.getId());
23833    }
23834
23835    private void unloadPrivatePackages(final VolumeInfo vol) {
23836        mHandler.post(new Runnable() {
23837            @Override
23838            public void run() {
23839                unloadPrivatePackagesInner(vol);
23840            }
23841        });
23842    }
23843
23844    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23845        final String volumeUuid = vol.fsUuid;
23846        if (TextUtils.isEmpty(volumeUuid)) {
23847            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23848            return;
23849        }
23850
23851        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23852        synchronized (mInstallLock) {
23853        synchronized (mPackages) {
23854            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23855            for (PackageSetting ps : packages) {
23856                if (ps.pkg == null) continue;
23857
23858                final ApplicationInfo info = ps.pkg.applicationInfo;
23859                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23860                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23861
23862                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23863                        "unloadPrivatePackagesInner")) {
23864                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23865                            false, null)) {
23866                        unloaded.add(info);
23867                    } else {
23868                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23869                    }
23870                }
23871
23872                // Try very hard to release any references to this package
23873                // so we don't risk the system server being killed due to
23874                // open FDs
23875                AttributeCache.instance().removePackage(ps.name);
23876            }
23877
23878            mSettings.writeLPr();
23879        }
23880        }
23881
23882        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23883        sendResourcesChangedBroadcast(false, false, unloaded, null);
23884        mLoadedVolumes.remove(vol.getId());
23885
23886        // Try very hard to release any references to this path so we don't risk
23887        // the system server being killed due to open FDs
23888        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23889
23890        for (int i = 0; i < 3; i++) {
23891            System.gc();
23892            System.runFinalization();
23893        }
23894    }
23895
23896    private void assertPackageKnown(String volumeUuid, String packageName)
23897            throws PackageManagerException {
23898        synchronized (mPackages) {
23899            // Normalize package name to handle renamed packages
23900            packageName = normalizePackageNameLPr(packageName);
23901
23902            final PackageSetting ps = mSettings.mPackages.get(packageName);
23903            if (ps == null) {
23904                throw new PackageManagerException("Package " + packageName + " is unknown");
23905            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23906                throw new PackageManagerException(
23907                        "Package " + packageName + " found on unknown volume " + volumeUuid
23908                                + "; expected volume " + ps.volumeUuid);
23909            }
23910        }
23911    }
23912
23913    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23914            throws PackageManagerException {
23915        synchronized (mPackages) {
23916            // Normalize package name to handle renamed packages
23917            packageName = normalizePackageNameLPr(packageName);
23918
23919            final PackageSetting ps = mSettings.mPackages.get(packageName);
23920            if (ps == null) {
23921                throw new PackageManagerException("Package " + packageName + " is unknown");
23922            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23923                throw new PackageManagerException(
23924                        "Package " + packageName + " found on unknown volume " + volumeUuid
23925                                + "; expected volume " + ps.volumeUuid);
23926            } else if (!ps.getInstalled(userId)) {
23927                throw new PackageManagerException(
23928                        "Package " + packageName + " not installed for user " + userId);
23929            }
23930        }
23931    }
23932
23933    private List<String> collectAbsoluteCodePaths() {
23934        synchronized (mPackages) {
23935            List<String> codePaths = new ArrayList<>();
23936            final int packageCount = mSettings.mPackages.size();
23937            for (int i = 0; i < packageCount; i++) {
23938                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23939                codePaths.add(ps.codePath.getAbsolutePath());
23940            }
23941            return codePaths;
23942        }
23943    }
23944
23945    /**
23946     * Examine all apps present on given mounted volume, and destroy apps that
23947     * aren't expected, either due to uninstallation or reinstallation on
23948     * another volume.
23949     */
23950    private void reconcileApps(String volumeUuid) {
23951        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23952        List<File> filesToDelete = null;
23953
23954        final File[] files = FileUtils.listFilesOrEmpty(
23955                Environment.getDataAppDirectory(volumeUuid));
23956        for (File file : files) {
23957            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23958                    && !PackageInstallerService.isStageName(file.getName());
23959            if (!isPackage) {
23960                // Ignore entries which are not packages
23961                continue;
23962            }
23963
23964            String absolutePath = file.getAbsolutePath();
23965
23966            boolean pathValid = false;
23967            final int absoluteCodePathCount = absoluteCodePaths.size();
23968            for (int i = 0; i < absoluteCodePathCount; i++) {
23969                String absoluteCodePath = absoluteCodePaths.get(i);
23970                if (absolutePath.startsWith(absoluteCodePath)) {
23971                    pathValid = true;
23972                    break;
23973                }
23974            }
23975
23976            if (!pathValid) {
23977                if (filesToDelete == null) {
23978                    filesToDelete = new ArrayList<>();
23979                }
23980                filesToDelete.add(file);
23981            }
23982        }
23983
23984        if (filesToDelete != null) {
23985            final int fileToDeleteCount = filesToDelete.size();
23986            for (int i = 0; i < fileToDeleteCount; i++) {
23987                File fileToDelete = filesToDelete.get(i);
23988                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23989                synchronized (mInstallLock) {
23990                    removeCodePathLI(fileToDelete);
23991                }
23992            }
23993        }
23994    }
23995
23996    /**
23997     * Reconcile all app data for the given user.
23998     * <p>
23999     * Verifies that directories exist and that ownership and labeling is
24000     * correct for all installed apps on all mounted volumes.
24001     */
24002    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
24003        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24004        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
24005            final String volumeUuid = vol.getFsUuid();
24006            synchronized (mInstallLock) {
24007                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
24008            }
24009        }
24010    }
24011
24012    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
24013            boolean migrateAppData) {
24014        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
24015    }
24016
24017    /**
24018     * Reconcile all app data on given mounted volume.
24019     * <p>
24020     * Destroys app data that isn't expected, either due to uninstallation or
24021     * reinstallation on another volume.
24022     * <p>
24023     * Verifies that directories exist and that ownership and labeling is
24024     * correct for all installed apps.
24025     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
24026     */
24027    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
24028            boolean migrateAppData, boolean onlyCoreApps) {
24029        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
24030                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
24031        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
24032
24033        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
24034        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
24035
24036        // First look for stale data that doesn't belong, and check if things
24037        // have changed since we did our last restorecon
24038        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24039            if (StorageManager.isFileEncryptedNativeOrEmulated()
24040                    && !StorageManager.isUserKeyUnlocked(userId)) {
24041                throw new RuntimeException(
24042                        "Yikes, someone asked us to reconcile CE storage while " + userId
24043                                + " was still locked; this would have caused massive data loss!");
24044            }
24045
24046            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
24047            for (File file : files) {
24048                final String packageName = file.getName();
24049                try {
24050                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
24051                } catch (PackageManagerException e) {
24052                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
24053                    try {
24054                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
24055                                StorageManager.FLAG_STORAGE_CE, 0);
24056                    } catch (InstallerException e2) {
24057                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
24058                    }
24059                }
24060            }
24061        }
24062        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
24063            final File[] files = FileUtils.listFilesOrEmpty(deDir);
24064            for (File file : files) {
24065                final String packageName = file.getName();
24066                try {
24067                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
24068                } catch (PackageManagerException e) {
24069                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
24070                    try {
24071                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
24072                                StorageManager.FLAG_STORAGE_DE, 0);
24073                    } catch (InstallerException e2) {
24074                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
24075                    }
24076                }
24077            }
24078        }
24079
24080        // Ensure that data directories are ready to roll for all packages
24081        // installed for this volume and user
24082        final List<PackageSetting> packages;
24083        synchronized (mPackages) {
24084            packages = mSettings.getVolumePackagesLPr(volumeUuid);
24085        }
24086        int preparedCount = 0;
24087        for (PackageSetting ps : packages) {
24088            final String packageName = ps.name;
24089            if (ps.pkg == null) {
24090                Slog.w(TAG, "Odd, missing scanned package " + packageName);
24091                // TODO: might be due to legacy ASEC apps; we should circle back
24092                // and reconcile again once they're scanned
24093                continue;
24094            }
24095            // Skip non-core apps if requested
24096            if (onlyCoreApps && !ps.pkg.coreApp) {
24097                result.add(packageName);
24098                continue;
24099            }
24100
24101            if (ps.getInstalled(userId)) {
24102                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
24103                preparedCount++;
24104            }
24105        }
24106
24107        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
24108        return result;
24109    }
24110
24111    /**
24112     * Prepare app data for the given app just after it was installed or
24113     * upgraded. This method carefully only touches users that it's installed
24114     * for, and it forces a restorecon to handle any seinfo changes.
24115     * <p>
24116     * Verifies that directories exist and that ownership and labeling is
24117     * correct for all installed apps. If there is an ownership mismatch, it
24118     * will try recovering system apps by wiping data; third-party app data is
24119     * left intact.
24120     * <p>
24121     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
24122     */
24123    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
24124        final PackageSetting ps;
24125        synchronized (mPackages) {
24126            ps = mSettings.mPackages.get(pkg.packageName);
24127            mSettings.writeKernelMappingLPr(ps);
24128        }
24129
24130        final UserManager um = mContext.getSystemService(UserManager.class);
24131        UserManagerInternal umInternal = getUserManagerInternal();
24132        for (UserInfo user : um.getUsers()) {
24133            final int flags;
24134            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
24135                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
24136            } else if (umInternal.isUserRunning(user.id)) {
24137                flags = StorageManager.FLAG_STORAGE_DE;
24138            } else {
24139                continue;
24140            }
24141
24142            if (ps.getInstalled(user.id)) {
24143                // TODO: when user data is locked, mark that we're still dirty
24144                prepareAppDataLIF(pkg, user.id, flags);
24145            }
24146        }
24147    }
24148
24149    /**
24150     * Prepare app data for the given app.
24151     * <p>
24152     * Verifies that directories exist and that ownership and labeling is
24153     * correct for all installed apps. If there is an ownership mismatch, this
24154     * will try recovering system apps by wiping data; third-party app data is
24155     * left intact.
24156     */
24157    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
24158        if (pkg == null) {
24159            Slog.wtf(TAG, "Package was null!", new Throwable());
24160            return;
24161        }
24162        prepareAppDataLeafLIF(pkg, userId, flags);
24163        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24164        for (int i = 0; i < childCount; i++) {
24165            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
24166        }
24167    }
24168
24169    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
24170            boolean maybeMigrateAppData) {
24171        prepareAppDataLIF(pkg, userId, flags);
24172
24173        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
24174            // We may have just shuffled around app data directories, so
24175            // prepare them one more time
24176            prepareAppDataLIF(pkg, userId, flags);
24177        }
24178    }
24179
24180    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24181        if (DEBUG_APP_DATA) {
24182            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
24183                    + Integer.toHexString(flags));
24184        }
24185
24186        final String volumeUuid = pkg.volumeUuid;
24187        final String packageName = pkg.packageName;
24188        final ApplicationInfo app = pkg.applicationInfo;
24189        final int appId = UserHandle.getAppId(app.uid);
24190
24191        Preconditions.checkNotNull(app.seInfo);
24192
24193        long ceDataInode = -1;
24194        try {
24195            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24196                    appId, app.seInfo, app.targetSdkVersion);
24197        } catch (InstallerException e) {
24198            if (app.isSystemApp()) {
24199                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
24200                        + ", but trying to recover: " + e);
24201                destroyAppDataLeafLIF(pkg, userId, flags);
24202                try {
24203                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24204                            appId, app.seInfo, app.targetSdkVersion);
24205                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
24206                } catch (InstallerException e2) {
24207                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
24208                }
24209            } else {
24210                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
24211            }
24212        }
24213
24214        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
24215            // TODO: mark this structure as dirty so we persist it!
24216            synchronized (mPackages) {
24217                final PackageSetting ps = mSettings.mPackages.get(packageName);
24218                if (ps != null) {
24219                    ps.setCeDataInode(ceDataInode, userId);
24220                }
24221            }
24222        }
24223
24224        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24225    }
24226
24227    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
24228        if (pkg == null) {
24229            Slog.wtf(TAG, "Package was null!", new Throwable());
24230            return;
24231        }
24232        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24233        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24234        for (int i = 0; i < childCount; i++) {
24235            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
24236        }
24237    }
24238
24239    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24240        final String volumeUuid = pkg.volumeUuid;
24241        final String packageName = pkg.packageName;
24242        final ApplicationInfo app = pkg.applicationInfo;
24243
24244        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24245            // Create a native library symlink only if we have native libraries
24246            // and if the native libraries are 32 bit libraries. We do not provide
24247            // this symlink for 64 bit libraries.
24248            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
24249                final String nativeLibPath = app.nativeLibraryDir;
24250                try {
24251                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
24252                            nativeLibPath, userId);
24253                } catch (InstallerException e) {
24254                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
24255                }
24256            }
24257        }
24258    }
24259
24260    /**
24261     * For system apps on non-FBE devices, this method migrates any existing
24262     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
24263     * requested by the app.
24264     */
24265    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
24266        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
24267                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
24268            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
24269                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
24270            try {
24271                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
24272                        storageTarget);
24273            } catch (InstallerException e) {
24274                logCriticalInfo(Log.WARN,
24275                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
24276            }
24277            return true;
24278        } else {
24279            return false;
24280        }
24281    }
24282
24283    public PackageFreezer freezePackage(String packageName, String killReason) {
24284        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
24285    }
24286
24287    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
24288        return new PackageFreezer(packageName, userId, killReason);
24289    }
24290
24291    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
24292            String killReason) {
24293        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
24294    }
24295
24296    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
24297            String killReason) {
24298        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
24299            return new PackageFreezer();
24300        } else {
24301            return freezePackage(packageName, userId, killReason);
24302        }
24303    }
24304
24305    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
24306            String killReason) {
24307        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
24308    }
24309
24310    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
24311            String killReason) {
24312        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
24313            return new PackageFreezer();
24314        } else {
24315            return freezePackage(packageName, userId, killReason);
24316        }
24317    }
24318
24319    /**
24320     * Class that freezes and kills the given package upon creation, and
24321     * unfreezes it upon closing. This is typically used when doing surgery on
24322     * app code/data to prevent the app from running while you're working.
24323     */
24324    private class PackageFreezer implements AutoCloseable {
24325        private final String mPackageName;
24326        private final PackageFreezer[] mChildren;
24327
24328        private final boolean mWeFroze;
24329
24330        private final AtomicBoolean mClosed = new AtomicBoolean();
24331        private final CloseGuard mCloseGuard = CloseGuard.get();
24332
24333        /**
24334         * Create and return a stub freezer that doesn't actually do anything,
24335         * typically used when someone requested
24336         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
24337         * {@link PackageManager#DELETE_DONT_KILL_APP}.
24338         */
24339        public PackageFreezer() {
24340            mPackageName = null;
24341            mChildren = null;
24342            mWeFroze = false;
24343            mCloseGuard.open("close");
24344        }
24345
24346        public PackageFreezer(String packageName, int userId, String killReason) {
24347            synchronized (mPackages) {
24348                mPackageName = packageName;
24349                mWeFroze = mFrozenPackages.add(mPackageName);
24350
24351                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
24352                if (ps != null) {
24353                    killApplication(ps.name, ps.appId, userId, killReason);
24354                }
24355
24356                final PackageParser.Package p = mPackages.get(packageName);
24357                if (p != null && p.childPackages != null) {
24358                    final int N = p.childPackages.size();
24359                    mChildren = new PackageFreezer[N];
24360                    for (int i = 0; i < N; i++) {
24361                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
24362                                userId, killReason);
24363                    }
24364                } else {
24365                    mChildren = null;
24366                }
24367            }
24368            mCloseGuard.open("close");
24369        }
24370
24371        @Override
24372        protected void finalize() throws Throwable {
24373            try {
24374                if (mCloseGuard != null) {
24375                    mCloseGuard.warnIfOpen();
24376                }
24377
24378                close();
24379            } finally {
24380                super.finalize();
24381            }
24382        }
24383
24384        @Override
24385        public void close() {
24386            mCloseGuard.close();
24387            if (mClosed.compareAndSet(false, true)) {
24388                synchronized (mPackages) {
24389                    if (mWeFroze) {
24390                        mFrozenPackages.remove(mPackageName);
24391                    }
24392
24393                    if (mChildren != null) {
24394                        for (PackageFreezer freezer : mChildren) {
24395                            freezer.close();
24396                        }
24397                    }
24398                }
24399            }
24400        }
24401    }
24402
24403    /**
24404     * Verify that given package is currently frozen.
24405     */
24406    private void checkPackageFrozen(String packageName) {
24407        synchronized (mPackages) {
24408            if (!mFrozenPackages.contains(packageName)) {
24409                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24410            }
24411        }
24412    }
24413
24414    @Override
24415    public int movePackage(final String packageName, final String volumeUuid) {
24416        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24417
24418        final int callingUid = Binder.getCallingUid();
24419        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24420        final int moveId = mNextMoveId.getAndIncrement();
24421        mHandler.post(new Runnable() {
24422            @Override
24423            public void run() {
24424                try {
24425                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24426                } catch (PackageManagerException e) {
24427                    Slog.w(TAG, "Failed to move " + packageName, e);
24428                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24429                }
24430            }
24431        });
24432        return moveId;
24433    }
24434
24435    private void movePackageInternal(final String packageName, final String volumeUuid,
24436            final int moveId, final int callingUid, UserHandle user)
24437                    throws PackageManagerException {
24438        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24439        final PackageManager pm = mContext.getPackageManager();
24440
24441        final boolean currentAsec;
24442        final String currentVolumeUuid;
24443        final File codeFile;
24444        final String installerPackageName;
24445        final String packageAbiOverride;
24446        final int appId;
24447        final String seinfo;
24448        final String label;
24449        final int targetSdkVersion;
24450        final PackageFreezer freezer;
24451        final int[] installedUserIds;
24452
24453        // reader
24454        synchronized (mPackages) {
24455            final PackageParser.Package pkg = mPackages.get(packageName);
24456            final PackageSetting ps = mSettings.mPackages.get(packageName);
24457            if (pkg == null
24458                    || ps == null
24459                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24460                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24461            }
24462            if (pkg.applicationInfo.isSystemApp()) {
24463                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24464                        "Cannot move system application");
24465            }
24466
24467            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24468            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24469                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24470            if (isInternalStorage && !allow3rdPartyOnInternal) {
24471                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24472                        "3rd party apps are not allowed on internal storage");
24473            }
24474
24475            if (pkg.applicationInfo.isExternalAsec()) {
24476                currentAsec = true;
24477                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24478            } else if (pkg.applicationInfo.isForwardLocked()) {
24479                currentAsec = true;
24480                currentVolumeUuid = "forward_locked";
24481            } else {
24482                currentAsec = false;
24483                currentVolumeUuid = ps.volumeUuid;
24484
24485                final File probe = new File(pkg.codePath);
24486                final File probeOat = new File(probe, "oat");
24487                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24488                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24489                            "Move only supported for modern cluster style installs");
24490                }
24491            }
24492
24493            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24494                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24495                        "Package already moved to " + volumeUuid);
24496            }
24497            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24498                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24499                        "Device admin cannot be moved");
24500            }
24501
24502            if (mFrozenPackages.contains(packageName)) {
24503                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24504                        "Failed to move already frozen package");
24505            }
24506
24507            codeFile = new File(pkg.codePath);
24508            installerPackageName = ps.installerPackageName;
24509            packageAbiOverride = ps.cpuAbiOverrideString;
24510            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24511            seinfo = pkg.applicationInfo.seInfo;
24512            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24513            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24514            freezer = freezePackage(packageName, "movePackageInternal");
24515            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24516        }
24517
24518        final Bundle extras = new Bundle();
24519        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24520        extras.putString(Intent.EXTRA_TITLE, label);
24521        mMoveCallbacks.notifyCreated(moveId, extras);
24522
24523        int installFlags;
24524        final boolean moveCompleteApp;
24525        final File measurePath;
24526
24527        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24528            installFlags = INSTALL_INTERNAL;
24529            moveCompleteApp = !currentAsec;
24530            measurePath = Environment.getDataAppDirectory(volumeUuid);
24531        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24532            installFlags = INSTALL_EXTERNAL;
24533            moveCompleteApp = false;
24534            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24535        } else {
24536            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24537            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24538                    || !volume.isMountedWritable()) {
24539                freezer.close();
24540                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24541                        "Move location not mounted private volume");
24542            }
24543
24544            Preconditions.checkState(!currentAsec);
24545
24546            installFlags = INSTALL_INTERNAL;
24547            moveCompleteApp = true;
24548            measurePath = Environment.getDataAppDirectory(volumeUuid);
24549        }
24550
24551        // If we're moving app data around, we need all the users unlocked
24552        if (moveCompleteApp) {
24553            for (int userId : installedUserIds) {
24554                if (StorageManager.isFileEncryptedNativeOrEmulated()
24555                        && !StorageManager.isUserKeyUnlocked(userId)) {
24556                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24557                            "User " + userId + " must be unlocked");
24558                }
24559            }
24560        }
24561
24562        final PackageStats stats = new PackageStats(null, -1);
24563        synchronized (mInstaller) {
24564            for (int userId : installedUserIds) {
24565                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24566                    freezer.close();
24567                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24568                            "Failed to measure package size");
24569                }
24570            }
24571        }
24572
24573        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24574                + stats.dataSize);
24575
24576        final long startFreeBytes = measurePath.getUsableSpace();
24577        final long sizeBytes;
24578        if (moveCompleteApp) {
24579            sizeBytes = stats.codeSize + stats.dataSize;
24580        } else {
24581            sizeBytes = stats.codeSize;
24582        }
24583
24584        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24585            freezer.close();
24586            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24587                    "Not enough free space to move");
24588        }
24589
24590        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24591
24592        final CountDownLatch installedLatch = new CountDownLatch(1);
24593        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24594            @Override
24595            public void onUserActionRequired(Intent intent) throws RemoteException {
24596                throw new IllegalStateException();
24597            }
24598
24599            @Override
24600            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24601                    Bundle extras) throws RemoteException {
24602                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24603                        + PackageManager.installStatusToString(returnCode, msg));
24604
24605                installedLatch.countDown();
24606                freezer.close();
24607
24608                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24609                switch (status) {
24610                    case PackageInstaller.STATUS_SUCCESS:
24611                        mMoveCallbacks.notifyStatusChanged(moveId,
24612                                PackageManager.MOVE_SUCCEEDED);
24613                        break;
24614                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24615                        mMoveCallbacks.notifyStatusChanged(moveId,
24616                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24617                        break;
24618                    default:
24619                        mMoveCallbacks.notifyStatusChanged(moveId,
24620                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24621                        break;
24622                }
24623            }
24624        };
24625
24626        final MoveInfo move;
24627        if (moveCompleteApp) {
24628            // Kick off a thread to report progress estimates
24629            new Thread() {
24630                @Override
24631                public void run() {
24632                    while (true) {
24633                        try {
24634                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24635                                break;
24636                            }
24637                        } catch (InterruptedException ignored) {
24638                        }
24639
24640                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24641                        final int progress = 10 + (int) MathUtils.constrain(
24642                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24643                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24644                    }
24645                }
24646            }.start();
24647
24648            final String dataAppName = codeFile.getName();
24649            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24650                    dataAppName, appId, seinfo, targetSdkVersion);
24651        } else {
24652            move = null;
24653        }
24654
24655        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24656
24657        final Message msg = mHandler.obtainMessage(INIT_COPY);
24658        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24659        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24660                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24661                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24662                PackageManager.INSTALL_REASON_UNKNOWN);
24663        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24664        msg.obj = params;
24665
24666        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24667                System.identityHashCode(msg.obj));
24668        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24669                System.identityHashCode(msg.obj));
24670
24671        mHandler.sendMessage(msg);
24672    }
24673
24674    @Override
24675    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24676        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24677
24678        final int realMoveId = mNextMoveId.getAndIncrement();
24679        final Bundle extras = new Bundle();
24680        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24681        mMoveCallbacks.notifyCreated(realMoveId, extras);
24682
24683        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24684            @Override
24685            public void onCreated(int moveId, Bundle extras) {
24686                // Ignored
24687            }
24688
24689            @Override
24690            public void onStatusChanged(int moveId, int status, long estMillis) {
24691                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24692            }
24693        };
24694
24695        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24696        storage.setPrimaryStorageUuid(volumeUuid, callback);
24697        return realMoveId;
24698    }
24699
24700    @Override
24701    public int getMoveStatus(int moveId) {
24702        mContext.enforceCallingOrSelfPermission(
24703                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24704        return mMoveCallbacks.mLastStatus.get(moveId);
24705    }
24706
24707    @Override
24708    public void registerMoveCallback(IPackageMoveObserver callback) {
24709        mContext.enforceCallingOrSelfPermission(
24710                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24711        mMoveCallbacks.register(callback);
24712    }
24713
24714    @Override
24715    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24716        mContext.enforceCallingOrSelfPermission(
24717                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24718        mMoveCallbacks.unregister(callback);
24719    }
24720
24721    @Override
24722    public boolean setInstallLocation(int loc) {
24723        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24724                null);
24725        if (getInstallLocation() == loc) {
24726            return true;
24727        }
24728        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24729                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24730            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24731                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24732            return true;
24733        }
24734        return false;
24735   }
24736
24737    @Override
24738    public int getInstallLocation() {
24739        // allow instant app access
24740        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24741                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24742                PackageHelper.APP_INSTALL_AUTO);
24743    }
24744
24745    /** Called by UserManagerService */
24746    void cleanUpUser(UserManagerService userManager, int userHandle) {
24747        synchronized (mPackages) {
24748            mDirtyUsers.remove(userHandle);
24749            mUserNeedsBadging.delete(userHandle);
24750            mSettings.removeUserLPw(userHandle);
24751            mPendingBroadcasts.remove(userHandle);
24752            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24753            removeUnusedPackagesLPw(userManager, userHandle);
24754        }
24755    }
24756
24757    /**
24758     * We're removing userHandle and would like to remove any downloaded packages
24759     * that are no longer in use by any other user.
24760     * @param userHandle the user being removed
24761     */
24762    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24763        final boolean DEBUG_CLEAN_APKS = false;
24764        int [] users = userManager.getUserIds();
24765        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24766        while (psit.hasNext()) {
24767            PackageSetting ps = psit.next();
24768            if (ps.pkg == null) {
24769                continue;
24770            }
24771            final String packageName = ps.pkg.packageName;
24772            // Skip over if system app
24773            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24774                continue;
24775            }
24776            if (DEBUG_CLEAN_APKS) {
24777                Slog.i(TAG, "Checking package " + packageName);
24778            }
24779            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24780            if (keep) {
24781                if (DEBUG_CLEAN_APKS) {
24782                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24783                }
24784            } else {
24785                for (int i = 0; i < users.length; i++) {
24786                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24787                        keep = true;
24788                        if (DEBUG_CLEAN_APKS) {
24789                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24790                                    + users[i]);
24791                        }
24792                        break;
24793                    }
24794                }
24795            }
24796            if (!keep) {
24797                if (DEBUG_CLEAN_APKS) {
24798                    Slog.i(TAG, "  Removing package " + packageName);
24799                }
24800                mHandler.post(new Runnable() {
24801                    public void run() {
24802                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24803                                userHandle, 0);
24804                    } //end run
24805                });
24806            }
24807        }
24808    }
24809
24810    /** Called by UserManagerService */
24811    void createNewUser(int userId, String[] disallowedPackages) {
24812        synchronized (mInstallLock) {
24813            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24814        }
24815        synchronized (mPackages) {
24816            scheduleWritePackageRestrictionsLocked(userId);
24817            scheduleWritePackageListLocked(userId);
24818            applyFactoryDefaultBrowserLPw(userId);
24819            primeDomainVerificationsLPw(userId);
24820        }
24821    }
24822
24823    void onNewUserCreated(final int userId) {
24824        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24825        // If permission review for legacy apps is required, we represent
24826        // dagerous permissions for such apps as always granted runtime
24827        // permissions to keep per user flag state whether review is needed.
24828        // Hence, if a new user is added we have to propagate dangerous
24829        // permission grants for these legacy apps.
24830        if (mPermissionReviewRequired) {
24831            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24832                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24833        }
24834    }
24835
24836    @Override
24837    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24838        mContext.enforceCallingOrSelfPermission(
24839                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24840                "Only package verification agents can read the verifier device identity");
24841
24842        synchronized (mPackages) {
24843            return mSettings.getVerifierDeviceIdentityLPw();
24844        }
24845    }
24846
24847    @Override
24848    public void setPermissionEnforced(String permission, boolean enforced) {
24849        // TODO: Now that we no longer change GID for storage, this should to away.
24850        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24851                "setPermissionEnforced");
24852        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24853            synchronized (mPackages) {
24854                if (mSettings.mReadExternalStorageEnforced == null
24855                        || mSettings.mReadExternalStorageEnforced != enforced) {
24856                    mSettings.mReadExternalStorageEnforced = enforced;
24857                    mSettings.writeLPr();
24858                }
24859            }
24860            // kill any non-foreground processes so we restart them and
24861            // grant/revoke the GID.
24862            final IActivityManager am = ActivityManager.getService();
24863            if (am != null) {
24864                final long token = Binder.clearCallingIdentity();
24865                try {
24866                    am.killProcessesBelowForeground("setPermissionEnforcement");
24867                } catch (RemoteException e) {
24868                } finally {
24869                    Binder.restoreCallingIdentity(token);
24870                }
24871            }
24872        } else {
24873            throw new IllegalArgumentException("No selective enforcement for " + permission);
24874        }
24875    }
24876
24877    @Override
24878    @Deprecated
24879    public boolean isPermissionEnforced(String permission) {
24880        // allow instant applications
24881        return true;
24882    }
24883
24884    @Override
24885    public boolean isStorageLow() {
24886        // allow instant applications
24887        final long token = Binder.clearCallingIdentity();
24888        try {
24889            final DeviceStorageMonitorInternal
24890                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24891            if (dsm != null) {
24892                return dsm.isMemoryLow();
24893            } else {
24894                return false;
24895            }
24896        } finally {
24897            Binder.restoreCallingIdentity(token);
24898        }
24899    }
24900
24901    @Override
24902    public IPackageInstaller getPackageInstaller() {
24903        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24904            return null;
24905        }
24906        return mInstallerService;
24907    }
24908
24909    private boolean userNeedsBadging(int userId) {
24910        int index = mUserNeedsBadging.indexOfKey(userId);
24911        if (index < 0) {
24912            final UserInfo userInfo;
24913            final long token = Binder.clearCallingIdentity();
24914            try {
24915                userInfo = sUserManager.getUserInfo(userId);
24916            } finally {
24917                Binder.restoreCallingIdentity(token);
24918            }
24919            final boolean b;
24920            if (userInfo != null && userInfo.isManagedProfile()) {
24921                b = true;
24922            } else {
24923                b = false;
24924            }
24925            mUserNeedsBadging.put(userId, b);
24926            return b;
24927        }
24928        return mUserNeedsBadging.valueAt(index);
24929    }
24930
24931    @Override
24932    public KeySet getKeySetByAlias(String packageName, String alias) {
24933        if (packageName == null || alias == null) {
24934            return null;
24935        }
24936        synchronized(mPackages) {
24937            final PackageParser.Package pkg = mPackages.get(packageName);
24938            if (pkg == null) {
24939                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24940                throw new IllegalArgumentException("Unknown package: " + packageName);
24941            }
24942            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24943            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24944                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24945                throw new IllegalArgumentException("Unknown package: " + packageName);
24946            }
24947            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24948            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24949        }
24950    }
24951
24952    @Override
24953    public KeySet getSigningKeySet(String packageName) {
24954        if (packageName == null) {
24955            return null;
24956        }
24957        synchronized(mPackages) {
24958            final int callingUid = Binder.getCallingUid();
24959            final int callingUserId = UserHandle.getUserId(callingUid);
24960            final PackageParser.Package pkg = mPackages.get(packageName);
24961            if (pkg == null) {
24962                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24963                throw new IllegalArgumentException("Unknown package: " + packageName);
24964            }
24965            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24966            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24967                // filter and pretend the package doesn't exist
24968                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24969                        + ", uid:" + callingUid);
24970                throw new IllegalArgumentException("Unknown package: " + packageName);
24971            }
24972            if (pkg.applicationInfo.uid != callingUid
24973                    && Process.SYSTEM_UID != callingUid) {
24974                throw new SecurityException("May not access signing KeySet of other apps.");
24975            }
24976            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24977            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24978        }
24979    }
24980
24981    @Override
24982    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24983        final int callingUid = Binder.getCallingUid();
24984        if (getInstantAppPackageName(callingUid) != null) {
24985            return false;
24986        }
24987        if (packageName == null || ks == null) {
24988            return false;
24989        }
24990        synchronized(mPackages) {
24991            final PackageParser.Package pkg = mPackages.get(packageName);
24992            if (pkg == null
24993                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24994                            UserHandle.getUserId(callingUid))) {
24995                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24996                throw new IllegalArgumentException("Unknown package: " + packageName);
24997            }
24998            IBinder ksh = ks.getToken();
24999            if (ksh instanceof KeySetHandle) {
25000                KeySetManagerService ksms = mSettings.mKeySetManagerService;
25001                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
25002            }
25003            return false;
25004        }
25005    }
25006
25007    @Override
25008    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
25009        final int callingUid = Binder.getCallingUid();
25010        if (getInstantAppPackageName(callingUid) != null) {
25011            return false;
25012        }
25013        if (packageName == null || ks == null) {
25014            return false;
25015        }
25016        synchronized(mPackages) {
25017            final PackageParser.Package pkg = mPackages.get(packageName);
25018            if (pkg == null
25019                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
25020                            UserHandle.getUserId(callingUid))) {
25021                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
25022                throw new IllegalArgumentException("Unknown package: " + packageName);
25023            }
25024            IBinder ksh = ks.getToken();
25025            if (ksh instanceof KeySetHandle) {
25026                KeySetManagerService ksms = mSettings.mKeySetManagerService;
25027                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
25028            }
25029            return false;
25030        }
25031    }
25032
25033    private void deletePackageIfUnusedLPr(final String packageName) {
25034        PackageSetting ps = mSettings.mPackages.get(packageName);
25035        if (ps == null) {
25036            return;
25037        }
25038        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
25039            // TODO Implement atomic delete if package is unused
25040            // It is currently possible that the package will be deleted even if it is installed
25041            // after this method returns.
25042            mHandler.post(new Runnable() {
25043                public void run() {
25044                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
25045                            0, PackageManager.DELETE_ALL_USERS);
25046                }
25047            });
25048        }
25049    }
25050
25051    /**
25052     * Check and throw if the given before/after packages would be considered a
25053     * downgrade.
25054     */
25055    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
25056            throws PackageManagerException {
25057        if (after.versionCode < before.mVersionCode) {
25058            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25059                    "Update version code " + after.versionCode + " is older than current "
25060                    + before.mVersionCode);
25061        } else if (after.versionCode == before.mVersionCode) {
25062            if (after.baseRevisionCode < before.baseRevisionCode) {
25063                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25064                        "Update base revision code " + after.baseRevisionCode
25065                        + " is older than current " + before.baseRevisionCode);
25066            }
25067
25068            if (!ArrayUtils.isEmpty(after.splitNames)) {
25069                for (int i = 0; i < after.splitNames.length; i++) {
25070                    final String splitName = after.splitNames[i];
25071                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
25072                    if (j != -1) {
25073                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
25074                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25075                                    "Update split " + splitName + " revision code "
25076                                    + after.splitRevisionCodes[i] + " is older than current "
25077                                    + before.splitRevisionCodes[j]);
25078                        }
25079                    }
25080                }
25081            }
25082        }
25083    }
25084
25085    private static class MoveCallbacks extends Handler {
25086        private static final int MSG_CREATED = 1;
25087        private static final int MSG_STATUS_CHANGED = 2;
25088
25089        private final RemoteCallbackList<IPackageMoveObserver>
25090                mCallbacks = new RemoteCallbackList<>();
25091
25092        private final SparseIntArray mLastStatus = new SparseIntArray();
25093
25094        public MoveCallbacks(Looper looper) {
25095            super(looper);
25096        }
25097
25098        public void register(IPackageMoveObserver callback) {
25099            mCallbacks.register(callback);
25100        }
25101
25102        public void unregister(IPackageMoveObserver callback) {
25103            mCallbacks.unregister(callback);
25104        }
25105
25106        @Override
25107        public void handleMessage(Message msg) {
25108            final SomeArgs args = (SomeArgs) msg.obj;
25109            final int n = mCallbacks.beginBroadcast();
25110            for (int i = 0; i < n; i++) {
25111                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
25112                try {
25113                    invokeCallback(callback, msg.what, args);
25114                } catch (RemoteException ignored) {
25115                }
25116            }
25117            mCallbacks.finishBroadcast();
25118            args.recycle();
25119        }
25120
25121        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
25122                throws RemoteException {
25123            switch (what) {
25124                case MSG_CREATED: {
25125                    callback.onCreated(args.argi1, (Bundle) args.arg2);
25126                    break;
25127                }
25128                case MSG_STATUS_CHANGED: {
25129                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
25130                    break;
25131                }
25132            }
25133        }
25134
25135        private void notifyCreated(int moveId, Bundle extras) {
25136            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
25137
25138            final SomeArgs args = SomeArgs.obtain();
25139            args.argi1 = moveId;
25140            args.arg2 = extras;
25141            obtainMessage(MSG_CREATED, args).sendToTarget();
25142        }
25143
25144        private void notifyStatusChanged(int moveId, int status) {
25145            notifyStatusChanged(moveId, status, -1);
25146        }
25147
25148        private void notifyStatusChanged(int moveId, int status, long estMillis) {
25149            Slog.v(TAG, "Move " + moveId + " status " + status);
25150
25151            final SomeArgs args = SomeArgs.obtain();
25152            args.argi1 = moveId;
25153            args.argi2 = status;
25154            args.arg3 = estMillis;
25155            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
25156
25157            synchronized (mLastStatus) {
25158                mLastStatus.put(moveId, status);
25159            }
25160        }
25161    }
25162
25163    private final static class OnPermissionChangeListeners extends Handler {
25164        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
25165
25166        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
25167                new RemoteCallbackList<>();
25168
25169        public OnPermissionChangeListeners(Looper looper) {
25170            super(looper);
25171        }
25172
25173        @Override
25174        public void handleMessage(Message msg) {
25175            switch (msg.what) {
25176                case MSG_ON_PERMISSIONS_CHANGED: {
25177                    final int uid = msg.arg1;
25178                    handleOnPermissionsChanged(uid);
25179                } break;
25180            }
25181        }
25182
25183        public void addListenerLocked(IOnPermissionsChangeListener listener) {
25184            mPermissionListeners.register(listener);
25185
25186        }
25187
25188        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
25189            mPermissionListeners.unregister(listener);
25190        }
25191
25192        public void onPermissionsChanged(int uid) {
25193            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
25194                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
25195            }
25196        }
25197
25198        private void handleOnPermissionsChanged(int uid) {
25199            final int count = mPermissionListeners.beginBroadcast();
25200            try {
25201                for (int i = 0; i < count; i++) {
25202                    IOnPermissionsChangeListener callback = mPermissionListeners
25203                            .getBroadcastItem(i);
25204                    try {
25205                        callback.onPermissionsChanged(uid);
25206                    } catch (RemoteException e) {
25207                        Log.e(TAG, "Permission listener is dead", e);
25208                    }
25209                }
25210            } finally {
25211                mPermissionListeners.finishBroadcast();
25212            }
25213        }
25214    }
25215
25216    private class PackageManagerNative extends IPackageManagerNative.Stub {
25217        @Override
25218        public String[] getNamesForUids(int[] uids) throws RemoteException {
25219            final String[] results = PackageManagerService.this.getNamesForUids(uids);
25220            // massage results so they can be parsed by the native binder
25221            for (int i = results.length - 1; i >= 0; --i) {
25222                if (results[i] == null) {
25223                    results[i] = "";
25224                }
25225            }
25226            return results;
25227        }
25228
25229        // NB: this differentiates between preloads and sideloads
25230        @Override
25231        public String getInstallerForPackage(String packageName) throws RemoteException {
25232            final String installerName = getInstallerPackageName(packageName);
25233            if (!TextUtils.isEmpty(installerName)) {
25234                return installerName;
25235            }
25236            // differentiate between preload and sideload
25237            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
25238            ApplicationInfo appInfo = getApplicationInfo(packageName,
25239                                    /*flags*/ 0,
25240                                    /*userId*/ callingUser);
25241            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
25242                return "preload";
25243            }
25244            return "";
25245        }
25246
25247        @Override
25248        public int getVersionCodeForPackage(String packageName) throws RemoteException {
25249            try {
25250                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
25251                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
25252                if (pInfo != null) {
25253                    return pInfo.versionCode;
25254                }
25255            } catch (Exception e) {
25256            }
25257            return 0;
25258        }
25259    }
25260
25261    private class PackageManagerInternalImpl extends PackageManagerInternal {
25262        @Override
25263        public void setLocationPackagesProvider(PackagesProvider provider) {
25264            synchronized (mPackages) {
25265                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
25266            }
25267        }
25268
25269        @Override
25270        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
25271            synchronized (mPackages) {
25272                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
25273            }
25274        }
25275
25276        @Override
25277        public void setSmsAppPackagesProvider(PackagesProvider provider) {
25278            synchronized (mPackages) {
25279                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
25280            }
25281        }
25282
25283        @Override
25284        public void setDialerAppPackagesProvider(PackagesProvider provider) {
25285            synchronized (mPackages) {
25286                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
25287            }
25288        }
25289
25290        @Override
25291        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
25292            synchronized (mPackages) {
25293                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
25294            }
25295        }
25296
25297        @Override
25298        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
25299            synchronized (mPackages) {
25300                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
25301            }
25302        }
25303
25304        @Override
25305        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
25306            synchronized (mPackages) {
25307                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
25308                        packageName, userId);
25309            }
25310        }
25311
25312        @Override
25313        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
25314            synchronized (mPackages) {
25315                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
25316                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
25317                        packageName, userId);
25318            }
25319        }
25320
25321        @Override
25322        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
25323            synchronized (mPackages) {
25324                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
25325                        packageName, userId);
25326            }
25327        }
25328
25329        @Override
25330        public void setKeepUninstalledPackages(final List<String> packageList) {
25331            Preconditions.checkNotNull(packageList);
25332            List<String> removedFromList = null;
25333            synchronized (mPackages) {
25334                if (mKeepUninstalledPackages != null) {
25335                    final int packagesCount = mKeepUninstalledPackages.size();
25336                    for (int i = 0; i < packagesCount; i++) {
25337                        String oldPackage = mKeepUninstalledPackages.get(i);
25338                        if (packageList != null && packageList.contains(oldPackage)) {
25339                            continue;
25340                        }
25341                        if (removedFromList == null) {
25342                            removedFromList = new ArrayList<>();
25343                        }
25344                        removedFromList.add(oldPackage);
25345                    }
25346                }
25347                mKeepUninstalledPackages = new ArrayList<>(packageList);
25348                if (removedFromList != null) {
25349                    final int removedCount = removedFromList.size();
25350                    for (int i = 0; i < removedCount; i++) {
25351                        deletePackageIfUnusedLPr(removedFromList.get(i));
25352                    }
25353                }
25354            }
25355        }
25356
25357        @Override
25358        public boolean isPermissionsReviewRequired(String packageName, int userId) {
25359            synchronized (mPackages) {
25360                // If we do not support permission review, done.
25361                if (!mPermissionReviewRequired) {
25362                    return false;
25363                }
25364
25365                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
25366                if (packageSetting == null) {
25367                    return false;
25368                }
25369
25370                // Permission review applies only to apps not supporting the new permission model.
25371                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
25372                    return false;
25373                }
25374
25375                // Legacy apps have the permission and get user consent on launch.
25376                PermissionsState permissionsState = packageSetting.getPermissionsState();
25377                return permissionsState.isPermissionReviewRequired(userId);
25378            }
25379        }
25380
25381        @Override
25382        public PackageInfo getPackageInfo(
25383                String packageName, int flags, int filterCallingUid, int userId) {
25384            return PackageManagerService.this
25385                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
25386                            flags, filterCallingUid, userId);
25387        }
25388
25389        @Override
25390        public ApplicationInfo getApplicationInfo(
25391                String packageName, int flags, int filterCallingUid, int userId) {
25392            return PackageManagerService.this
25393                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
25394        }
25395
25396        @Override
25397        public ActivityInfo getActivityInfo(
25398                ComponentName component, int flags, int filterCallingUid, int userId) {
25399            return PackageManagerService.this
25400                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
25401        }
25402
25403        @Override
25404        public List<ResolveInfo> queryIntentActivities(
25405                Intent intent, int flags, int filterCallingUid, int userId) {
25406            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25407            return PackageManagerService.this
25408                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
25409                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
25410        }
25411
25412        @Override
25413        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
25414                int userId) {
25415            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
25416        }
25417
25418        @Override
25419        public void setDeviceAndProfileOwnerPackages(
25420                int deviceOwnerUserId, String deviceOwnerPackage,
25421                SparseArray<String> profileOwnerPackages) {
25422            mProtectedPackages.setDeviceAndProfileOwnerPackages(
25423                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
25424        }
25425
25426        @Override
25427        public boolean isPackageDataProtected(int userId, String packageName) {
25428            return mProtectedPackages.isPackageDataProtected(userId, packageName);
25429        }
25430
25431        @Override
25432        public boolean isPackageEphemeral(int userId, String packageName) {
25433            synchronized (mPackages) {
25434                final PackageSetting ps = mSettings.mPackages.get(packageName);
25435                return ps != null ? ps.getInstantApp(userId) : false;
25436            }
25437        }
25438
25439        @Override
25440        public boolean wasPackageEverLaunched(String packageName, int userId) {
25441            synchronized (mPackages) {
25442                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25443            }
25444        }
25445
25446        @Override
25447        public void grantRuntimePermission(String packageName, String name, int userId,
25448                boolean overridePolicy) {
25449            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25450                    overridePolicy);
25451        }
25452
25453        @Override
25454        public void revokeRuntimePermission(String packageName, String name, int userId,
25455                boolean overridePolicy) {
25456            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25457                    overridePolicy);
25458        }
25459
25460        @Override
25461        public String getNameForUid(int uid) {
25462            return PackageManagerService.this.getNameForUid(uid);
25463        }
25464
25465        @Override
25466        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25467                Intent origIntent, String resolvedType, String callingPackage,
25468                Bundle verificationBundle, int userId) {
25469            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25470                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25471                    userId);
25472        }
25473
25474        @Override
25475        public void grantEphemeralAccess(int userId, Intent intent,
25476                int targetAppId, int ephemeralAppId) {
25477            synchronized (mPackages) {
25478                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25479                        targetAppId, ephemeralAppId);
25480            }
25481        }
25482
25483        @Override
25484        public boolean isInstantAppInstallerComponent(ComponentName component) {
25485            synchronized (mPackages) {
25486                return mInstantAppInstallerActivity != null
25487                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25488            }
25489        }
25490
25491        @Override
25492        public void pruneInstantApps() {
25493            mInstantAppRegistry.pruneInstantApps();
25494        }
25495
25496        @Override
25497        public String getSetupWizardPackageName() {
25498            return mSetupWizardPackage;
25499        }
25500
25501        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25502            if (policy != null) {
25503                mExternalSourcesPolicy = policy;
25504            }
25505        }
25506
25507        @Override
25508        public boolean isPackagePersistent(String packageName) {
25509            synchronized (mPackages) {
25510                PackageParser.Package pkg = mPackages.get(packageName);
25511                return pkg != null
25512                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25513                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25514                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25515                        : false;
25516            }
25517        }
25518
25519        @Override
25520        public List<PackageInfo> getOverlayPackages(int userId) {
25521            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25522            synchronized (mPackages) {
25523                for (PackageParser.Package p : mPackages.values()) {
25524                    if (p.mOverlayTarget != null) {
25525                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25526                        if (pkg != null) {
25527                            overlayPackages.add(pkg);
25528                        }
25529                    }
25530                }
25531            }
25532            return overlayPackages;
25533        }
25534
25535        @Override
25536        public List<String> getTargetPackageNames(int userId) {
25537            List<String> targetPackages = new ArrayList<>();
25538            synchronized (mPackages) {
25539                for (PackageParser.Package p : mPackages.values()) {
25540                    if (p.mOverlayTarget == null) {
25541                        targetPackages.add(p.packageName);
25542                    }
25543                }
25544            }
25545            return targetPackages;
25546        }
25547
25548        @Override
25549        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25550                @Nullable List<String> overlayPackageNames) {
25551            synchronized (mPackages) {
25552                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25553                    Slog.e(TAG, "failed to find package " + targetPackageName);
25554                    return false;
25555                }
25556                ArrayList<String> overlayPaths = null;
25557                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25558                    final int N = overlayPackageNames.size();
25559                    overlayPaths = new ArrayList<>(N);
25560                    for (int i = 0; i < N; i++) {
25561                        final String packageName = overlayPackageNames.get(i);
25562                        final PackageParser.Package pkg = mPackages.get(packageName);
25563                        if (pkg == null) {
25564                            Slog.e(TAG, "failed to find package " + packageName);
25565                            return false;
25566                        }
25567                        overlayPaths.add(pkg.baseCodePath);
25568                    }
25569                }
25570
25571                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25572                ps.setOverlayPaths(overlayPaths, userId);
25573                return true;
25574            }
25575        }
25576
25577        @Override
25578        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25579                int flags, int userId) {
25580            return resolveIntentInternal(
25581                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25582        }
25583
25584        @Override
25585        public ResolveInfo resolveService(Intent intent, String resolvedType,
25586                int flags, int userId, int callingUid) {
25587            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25588        }
25589
25590        @Override
25591        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25592            synchronized (mPackages) {
25593                mIsolatedOwners.put(isolatedUid, ownerUid);
25594            }
25595        }
25596
25597        @Override
25598        public void removeIsolatedUid(int isolatedUid) {
25599            synchronized (mPackages) {
25600                mIsolatedOwners.delete(isolatedUid);
25601            }
25602        }
25603
25604        @Override
25605        public int getUidTargetSdkVersion(int uid) {
25606            synchronized (mPackages) {
25607                return getUidTargetSdkVersionLockedLPr(uid);
25608            }
25609        }
25610
25611        @Override
25612        public boolean canAccessInstantApps(int callingUid, int userId) {
25613            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25614        }
25615
25616        @Override
25617        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
25618            synchronized (mPackages) {
25619                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
25620            }
25621        }
25622
25623        @Override
25624        public void notifyPackageUse(String packageName, int reason) {
25625            synchronized (mPackages) {
25626                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
25627            }
25628        }
25629    }
25630
25631    @Override
25632    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25633        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25634        synchronized (mPackages) {
25635            final long identity = Binder.clearCallingIdentity();
25636            try {
25637                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25638                        packageNames, userId);
25639            } finally {
25640                Binder.restoreCallingIdentity(identity);
25641            }
25642        }
25643    }
25644
25645    @Override
25646    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25647        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25648        synchronized (mPackages) {
25649            final long identity = Binder.clearCallingIdentity();
25650            try {
25651                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25652                        packageNames, userId);
25653            } finally {
25654                Binder.restoreCallingIdentity(identity);
25655            }
25656        }
25657    }
25658
25659    private static void enforceSystemOrPhoneCaller(String tag) {
25660        int callingUid = Binder.getCallingUid();
25661        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25662            throw new SecurityException(
25663                    "Cannot call " + tag + " from UID " + callingUid);
25664        }
25665    }
25666
25667    boolean isHistoricalPackageUsageAvailable() {
25668        return mPackageUsage.isHistoricalPackageUsageAvailable();
25669    }
25670
25671    /**
25672     * Return a <b>copy</b> of the collection of packages known to the package manager.
25673     * @return A copy of the values of mPackages.
25674     */
25675    Collection<PackageParser.Package> getPackages() {
25676        synchronized (mPackages) {
25677            return new ArrayList<>(mPackages.values());
25678        }
25679    }
25680
25681    /**
25682     * Logs process start information (including base APK hash) to the security log.
25683     * @hide
25684     */
25685    @Override
25686    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25687            String apkFile, int pid) {
25688        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25689            return;
25690        }
25691        if (!SecurityLog.isLoggingEnabled()) {
25692            return;
25693        }
25694        Bundle data = new Bundle();
25695        data.putLong("startTimestamp", System.currentTimeMillis());
25696        data.putString("processName", processName);
25697        data.putInt("uid", uid);
25698        data.putString("seinfo", seinfo);
25699        data.putString("apkFile", apkFile);
25700        data.putInt("pid", pid);
25701        Message msg = mProcessLoggingHandler.obtainMessage(
25702                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25703        msg.setData(data);
25704        mProcessLoggingHandler.sendMessage(msg);
25705    }
25706
25707    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25708        return mCompilerStats.getPackageStats(pkgName);
25709    }
25710
25711    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25712        return getOrCreateCompilerPackageStats(pkg.packageName);
25713    }
25714
25715    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25716        return mCompilerStats.getOrCreatePackageStats(pkgName);
25717    }
25718
25719    public void deleteCompilerPackageStats(String pkgName) {
25720        mCompilerStats.deletePackageStats(pkgName);
25721    }
25722
25723    @Override
25724    public int getInstallReason(String packageName, int userId) {
25725        final int callingUid = Binder.getCallingUid();
25726        enforceCrossUserPermission(callingUid, userId,
25727                true /* requireFullPermission */, false /* checkShell */,
25728                "get install reason");
25729        synchronized (mPackages) {
25730            final PackageSetting ps = mSettings.mPackages.get(packageName);
25731            if (filterAppAccessLPr(ps, callingUid, userId)) {
25732                return PackageManager.INSTALL_REASON_UNKNOWN;
25733            }
25734            if (ps != null) {
25735                return ps.getInstallReason(userId);
25736            }
25737        }
25738        return PackageManager.INSTALL_REASON_UNKNOWN;
25739    }
25740
25741    @Override
25742    public boolean canRequestPackageInstalls(String packageName, int userId) {
25743        return canRequestPackageInstallsInternal(packageName, 0, userId,
25744                true /* throwIfPermNotDeclared*/);
25745    }
25746
25747    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25748            boolean throwIfPermNotDeclared) {
25749        int callingUid = Binder.getCallingUid();
25750        int uid = getPackageUid(packageName, 0, userId);
25751        if (callingUid != uid && callingUid != Process.ROOT_UID
25752                && callingUid != Process.SYSTEM_UID) {
25753            throw new SecurityException(
25754                    "Caller uid " + callingUid + " does not own package " + packageName);
25755        }
25756        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25757        if (info == null) {
25758            return false;
25759        }
25760        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25761            return false;
25762        }
25763        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25764        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25765        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25766            if (throwIfPermNotDeclared) {
25767                throw new SecurityException("Need to declare " + appOpPermission
25768                        + " to call this api");
25769            } else {
25770                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25771                return false;
25772            }
25773        }
25774        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25775            return false;
25776        }
25777        if (mExternalSourcesPolicy != null) {
25778            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25779            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25780                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25781            }
25782        }
25783        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25784    }
25785
25786    @Override
25787    public ComponentName getInstantAppResolverSettingsComponent() {
25788        return mInstantAppResolverSettingsComponent;
25789    }
25790
25791    @Override
25792    public ComponentName getInstantAppInstallerComponent() {
25793        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25794            return null;
25795        }
25796        return mInstantAppInstallerActivity == null
25797                ? null : mInstantAppInstallerActivity.getComponentName();
25798    }
25799
25800    @Override
25801    public String getInstantAppAndroidId(String packageName, int userId) {
25802        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25803                "getInstantAppAndroidId");
25804        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25805                true /* requireFullPermission */, false /* checkShell */,
25806                "getInstantAppAndroidId");
25807        // Make sure the target is an Instant App.
25808        if (!isInstantApp(packageName, userId)) {
25809            return null;
25810        }
25811        synchronized (mPackages) {
25812            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25813        }
25814    }
25815
25816    boolean canHaveOatDir(String packageName) {
25817        synchronized (mPackages) {
25818            PackageParser.Package p = mPackages.get(packageName);
25819            if (p == null) {
25820                return false;
25821            }
25822            return p.canHaveOatDir();
25823        }
25824    }
25825
25826    private String getOatDir(PackageParser.Package pkg) {
25827        if (!pkg.canHaveOatDir()) {
25828            return null;
25829        }
25830        File codePath = new File(pkg.codePath);
25831        if (codePath.isDirectory()) {
25832            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25833        }
25834        return null;
25835    }
25836
25837    void deleteOatArtifactsOfPackage(String packageName) {
25838        final String[] instructionSets;
25839        final List<String> codePaths;
25840        final String oatDir;
25841        final PackageParser.Package pkg;
25842        synchronized (mPackages) {
25843            pkg = mPackages.get(packageName);
25844        }
25845        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25846        codePaths = pkg.getAllCodePaths();
25847        oatDir = getOatDir(pkg);
25848
25849        for (String codePath : codePaths) {
25850            for (String isa : instructionSets) {
25851                try {
25852                    mInstaller.deleteOdex(codePath, isa, oatDir);
25853                } catch (InstallerException e) {
25854                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25855                }
25856            }
25857        }
25858    }
25859
25860    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25861        Set<String> unusedPackages = new HashSet<>();
25862        long currentTimeInMillis = System.currentTimeMillis();
25863        synchronized (mPackages) {
25864            for (PackageParser.Package pkg : mPackages.values()) {
25865                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25866                if (ps == null) {
25867                    continue;
25868                }
25869                PackageDexUsage.PackageUseInfo packageUseInfo =
25870                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25871                if (PackageManagerServiceUtils
25872                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25873                                downgradeTimeThresholdMillis, packageUseInfo,
25874                                pkg.getLatestPackageUseTimeInMills(),
25875                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25876                    unusedPackages.add(pkg.packageName);
25877                }
25878            }
25879        }
25880        return unusedPackages;
25881    }
25882}
25883
25884interface PackageSender {
25885    void sendPackageBroadcast(final String action, final String pkg,
25886        final Bundle extras, final int flags, final String targetPkg,
25887        final IIntentReceiver finishedReceiver, final int[] userIds);
25888    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25889        boolean includeStopped, int appId, int... userIds);
25890}
25891