PackageManagerService.java revision c5d1b90f41cc3b33d1bed149df2f735481fe66cb
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.List;
341import java.util.Map;
342import java.util.Objects;
343import java.util.Set;
344import java.util.concurrent.CountDownLatch;
345import java.util.concurrent.Future;
346import java.util.concurrent.TimeUnit;
347import java.util.concurrent.atomic.AtomicBoolean;
348import java.util.concurrent.atomic.AtomicInteger;
349import java.util.zip.GZIPInputStream;
350
351/**
352 * Keep track of all those APKs everywhere.
353 * <p>
354 * Internally there are two important locks:
355 * <ul>
356 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
357 * and other related state. It is a fine-grained lock that should only be held
358 * momentarily, as it's one of the most contended locks in the system.
359 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
360 * operations typically involve heavy lifting of application data on disk. Since
361 * {@code installd} is single-threaded, and it's operations can often be slow,
362 * this lock should never be acquired while already holding {@link #mPackages}.
363 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
364 * holding {@link #mInstallLock}.
365 * </ul>
366 * Many internal methods rely on the caller to hold the appropriate locks, and
367 * this contract is expressed through method name suffixes:
368 * <ul>
369 * <li>fooLI(): the caller must hold {@link #mInstallLock}
370 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
371 * being modified must be frozen
372 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
373 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
374 * </ul>
375 * <p>
376 * Because this class is very central to the platform's security; please run all
377 * CTS and unit tests whenever making modifications:
378 *
379 * <pre>
380 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
381 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
382 * </pre>
383 */
384public class PackageManagerService extends IPackageManager.Stub
385        implements PackageSender {
386    static final String TAG = "PackageManager";
387    static final boolean DEBUG_SETTINGS = false;
388    static final boolean DEBUG_PREFERRED = false;
389    static final boolean DEBUG_UPGRADE = false;
390    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
391    private static final boolean DEBUG_BACKUP = false;
392    private static final boolean DEBUG_INSTALL = false;
393    private static final boolean DEBUG_REMOVE = false;
394    private static final boolean DEBUG_BROADCASTS = false;
395    private static final boolean DEBUG_SHOW_INFO = false;
396    private static final boolean DEBUG_PACKAGE_INFO = false;
397    private static final boolean DEBUG_INTENT_MATCHING = false;
398    private static final boolean DEBUG_PACKAGE_SCANNING = false;
399    private static final boolean DEBUG_VERIFY = false;
400    private static final boolean DEBUG_FILTERS = false;
401    private static final boolean DEBUG_PERMISSIONS = false;
402    private static final boolean DEBUG_SHARED_LIBRARIES = false;
403    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
404
405    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
406    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
407    // user, but by default initialize to this.
408    public static final boolean DEBUG_DEXOPT = false;
409
410    private static final boolean DEBUG_ABI_SELECTION = false;
411    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
412    private static final boolean DEBUG_TRIAGED_MISSING = false;
413    private static final boolean DEBUG_APP_DATA = false;
414
415    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
416    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
417
418    private static final boolean HIDE_EPHEMERAL_APIS = false;
419
420    private static final boolean ENABLE_FREE_CACHE_V2 =
421            SystemProperties.getBoolean("fw.free_cache_v2", true);
422
423    private static final int RADIO_UID = Process.PHONE_UID;
424    private static final int LOG_UID = Process.LOG_UID;
425    private static final int NFC_UID = Process.NFC_UID;
426    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
427    private static final int SHELL_UID = Process.SHELL_UID;
428
429    // Cap the size of permission trees that 3rd party apps can define
430    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
431
432    // Suffix used during package installation when copying/moving
433    // package apks to install directory.
434    private static final String INSTALL_PACKAGE_SUFFIX = "-";
435
436    static final int SCAN_NO_DEX = 1<<1;
437    static final int SCAN_FORCE_DEX = 1<<2;
438    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
439    static final int SCAN_NEW_INSTALL = 1<<4;
440    static final int SCAN_UPDATE_TIME = 1<<5;
441    static final int SCAN_BOOTING = 1<<6;
442    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
443    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
444    static final int SCAN_REPLACING = 1<<9;
445    static final int SCAN_REQUIRE_KNOWN = 1<<10;
446    static final int SCAN_MOVE = 1<<11;
447    static final int SCAN_INITIAL = 1<<12;
448    static final int SCAN_CHECK_ONLY = 1<<13;
449    static final int SCAN_DONT_KILL_APP = 1<<14;
450    static final int SCAN_IGNORE_FROZEN = 1<<15;
451    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
452    static final int SCAN_AS_INSTANT_APP = 1<<17;
453    static final int SCAN_AS_FULL_APP = 1<<18;
454    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
455    /** Should not be with the scan flags */
456    static final int FLAGS_REMOVE_CHATTY = 1<<31;
457
458    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
459    /** Extension of the compressed packages */
460    private final static String COMPRESSED_EXTENSION = ".gz";
461    /** Suffix of stub packages on the system partition */
462    private final static String STUB_SUFFIX = "-Stub";
463
464    private static final int[] EMPTY_INT_ARRAY = new int[0];
465
466    private static final int TYPE_UNKNOWN = 0;
467    private static final int TYPE_ACTIVITY = 1;
468    private static final int TYPE_RECEIVER = 2;
469    private static final int TYPE_SERVICE = 3;
470    private static final int TYPE_PROVIDER = 4;
471    @IntDef(prefix = { "TYPE_" }, value = {
472            TYPE_UNKNOWN,
473            TYPE_ACTIVITY,
474            TYPE_RECEIVER,
475            TYPE_SERVICE,
476            TYPE_PROVIDER,
477    })
478    @Retention(RetentionPolicy.SOURCE)
479    public @interface ComponentType {}
480
481    /**
482     * Timeout (in milliseconds) after which the watchdog should declare that
483     * our handler thread is wedged.  The usual default for such things is one
484     * minute but we sometimes do very lengthy I/O operations on this thread,
485     * such as installing multi-gigabyte applications, so ours needs to be longer.
486     */
487    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
488
489    /**
490     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
491     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
492     * settings entry if available, otherwise we use the hardcoded default.  If it's been
493     * more than this long since the last fstrim, we force one during the boot sequence.
494     *
495     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
496     * one gets run at the next available charging+idle time.  This final mandatory
497     * no-fstrim check kicks in only of the other scheduling criteria is never met.
498     */
499    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
500
501    /**
502     * Whether verification is enabled by default.
503     */
504    private static final boolean DEFAULT_VERIFY_ENABLE = true;
505
506    /**
507     * The default maximum time to wait for the verification agent to return in
508     * milliseconds.
509     */
510    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
511
512    /**
513     * The default response for package verification timeout.
514     *
515     * This can be either PackageManager.VERIFICATION_ALLOW or
516     * PackageManager.VERIFICATION_REJECT.
517     */
518    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
519
520    static final String PLATFORM_PACKAGE_NAME = "android";
521
522    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
523
524    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
525            DEFAULT_CONTAINER_PACKAGE,
526            "com.android.defcontainer.DefaultContainerService");
527
528    private static final String KILL_APP_REASON_GIDS_CHANGED =
529            "permission grant or revoke changed gids";
530
531    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
532            "permissions revoked";
533
534    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
535
536    private static final String PACKAGE_SCHEME = "package";
537
538    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
539
540    /** Permission grant: not grant the permission. */
541    private static final int GRANT_DENIED = 1;
542
543    /** Permission grant: grant the permission as an install permission. */
544    private static final int GRANT_INSTALL = 2;
545
546    /** Permission grant: grant the permission as a runtime one. */
547    private static final int GRANT_RUNTIME = 3;
548
549    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
550    private static final int GRANT_UPGRADE = 4;
551
552    /** Canonical intent used to identify what counts as a "web browser" app */
553    private static final Intent sBrowserIntent;
554    static {
555        sBrowserIntent = new Intent();
556        sBrowserIntent.setAction(Intent.ACTION_VIEW);
557        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
558        sBrowserIntent.setData(Uri.parse("http:"));
559    }
560
561    /**
562     * The set of all protected actions [i.e. those actions for which a high priority
563     * intent filter is disallowed].
564     */
565    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
566    static {
567        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
568        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
569        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
570        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
571    }
572
573    // Compilation reasons.
574    public static final int REASON_FIRST_BOOT = 0;
575    public static final int REASON_BOOT = 1;
576    public static final int REASON_INSTALL = 2;
577    public static final int REASON_BACKGROUND_DEXOPT = 3;
578    public static final int REASON_AB_OTA = 4;
579    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
580    public static final int REASON_SHARED = 6;
581
582    public static final int REASON_LAST = REASON_SHARED;
583
584    /** All dangerous permission names in the same order as the events in MetricsEvent */
585    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
586            Manifest.permission.READ_CALENDAR,
587            Manifest.permission.WRITE_CALENDAR,
588            Manifest.permission.CAMERA,
589            Manifest.permission.READ_CONTACTS,
590            Manifest.permission.WRITE_CONTACTS,
591            Manifest.permission.GET_ACCOUNTS,
592            Manifest.permission.ACCESS_FINE_LOCATION,
593            Manifest.permission.ACCESS_COARSE_LOCATION,
594            Manifest.permission.RECORD_AUDIO,
595            Manifest.permission.READ_PHONE_STATE,
596            Manifest.permission.CALL_PHONE,
597            Manifest.permission.READ_CALL_LOG,
598            Manifest.permission.WRITE_CALL_LOG,
599            Manifest.permission.ADD_VOICEMAIL,
600            Manifest.permission.USE_SIP,
601            Manifest.permission.PROCESS_OUTGOING_CALLS,
602            Manifest.permission.READ_CELL_BROADCASTS,
603            Manifest.permission.BODY_SENSORS,
604            Manifest.permission.SEND_SMS,
605            Manifest.permission.RECEIVE_SMS,
606            Manifest.permission.READ_SMS,
607            Manifest.permission.RECEIVE_WAP_PUSH,
608            Manifest.permission.RECEIVE_MMS,
609            Manifest.permission.READ_EXTERNAL_STORAGE,
610            Manifest.permission.WRITE_EXTERNAL_STORAGE,
611            Manifest.permission.READ_PHONE_NUMBERS,
612            Manifest.permission.ANSWER_PHONE_CALLS);
613
614
615    /**
616     * Version number for the package parser cache. Increment this whenever the format or
617     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
618     */
619    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
620
621    /**
622     * Whether the package parser cache is enabled.
623     */
624    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
625
626    final ServiceThread mHandlerThread;
627
628    final PackageHandler mHandler;
629
630    private final ProcessLoggingHandler mProcessLoggingHandler;
631
632    /**
633     * Messages for {@link #mHandler} that need to wait for system ready before
634     * being dispatched.
635     */
636    private ArrayList<Message> mPostSystemReadyMessages;
637
638    final int mSdkVersion = Build.VERSION.SDK_INT;
639
640    final Context mContext;
641    final boolean mFactoryTest;
642    final boolean mOnlyCore;
643    final DisplayMetrics mMetrics;
644    final int mDefParseFlags;
645    final String[] mSeparateProcesses;
646    final boolean mIsUpgrade;
647    final boolean mIsPreNUpgrade;
648    final boolean mIsPreNMR1Upgrade;
649
650    // Have we told the Activity Manager to whitelist the default container service by uid yet?
651    @GuardedBy("mPackages")
652    boolean mDefaultContainerWhitelisted = false;
653
654    @GuardedBy("mPackages")
655    private boolean mDexOptDialogShown;
656
657    /** The location for ASEC container files on internal storage. */
658    final String mAsecInternalPath;
659
660    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
661    // LOCK HELD.  Can be called with mInstallLock held.
662    @GuardedBy("mInstallLock")
663    final Installer mInstaller;
664
665    /** Directory where installed third-party apps stored */
666    final File mAppInstallDir;
667
668    /**
669     * Directory to which applications installed internally have their
670     * 32 bit native libraries copied.
671     */
672    private File mAppLib32InstallDir;
673
674    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
675    // apps.
676    final File mDrmAppPrivateInstallDir;
677
678    // ----------------------------------------------------------------
679
680    // Lock for state used when installing and doing other long running
681    // operations.  Methods that must be called with this lock held have
682    // the suffix "LI".
683    final Object mInstallLock = new Object();
684
685    // ----------------------------------------------------------------
686
687    // Keys are String (package name), values are Package.  This also serves
688    // as the lock for the global state.  Methods that must be called with
689    // this lock held have the prefix "LP".
690    @GuardedBy("mPackages")
691    final ArrayMap<String, PackageParser.Package> mPackages =
692            new ArrayMap<String, PackageParser.Package>();
693
694    final ArrayMap<String, Set<String>> mKnownCodebase =
695            new ArrayMap<String, Set<String>>();
696
697    // Keys are isolated uids and values are the uid of the application
698    // that created the isolated proccess.
699    @GuardedBy("mPackages")
700    final SparseIntArray mIsolatedOwners = new SparseIntArray();
701
702    /**
703     * Tracks new system packages [received in an OTA] that we expect to
704     * find updated user-installed versions. Keys are package name, values
705     * are package location.
706     */
707    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
708    /**
709     * Tracks high priority intent filters for protected actions. During boot, certain
710     * filter actions are protected and should never be allowed to have a high priority
711     * intent filter for them. However, there is one, and only one exception -- the
712     * setup wizard. It must be able to define a high priority intent filter for these
713     * actions to ensure there are no escapes from the wizard. We need to delay processing
714     * of these during boot as we need to look at all of the system packages in order
715     * to know which component is the setup wizard.
716     */
717    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
718    /**
719     * Whether or not processing protected filters should be deferred.
720     */
721    private boolean mDeferProtectedFilters = true;
722
723    /**
724     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
725     */
726    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
727    /**
728     * Whether or not system app permissions should be promoted from install to runtime.
729     */
730    boolean mPromoteSystemApps;
731
732    @GuardedBy("mPackages")
733    final Settings mSettings;
734
735    /**
736     * Set of package names that are currently "frozen", which means active
737     * surgery is being done on the code/data for that package. The platform
738     * will refuse to launch frozen packages to avoid race conditions.
739     *
740     * @see PackageFreezer
741     */
742    @GuardedBy("mPackages")
743    final ArraySet<String> mFrozenPackages = new ArraySet<>();
744
745    final ProtectedPackages mProtectedPackages;
746
747    @GuardedBy("mLoadedVolumes")
748    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
749
750    boolean mFirstBoot;
751
752    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
753
754    // System configuration read by SystemConfig.
755    final int[] mGlobalGids;
756    final SparseArray<ArraySet<String>> mSystemPermissions;
757    @GuardedBy("mAvailableFeatures")
758    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
759
760    // If mac_permissions.xml was found for seinfo labeling.
761    boolean mFoundPolicyFile;
762
763    private final InstantAppRegistry mInstantAppRegistry;
764
765    @GuardedBy("mPackages")
766    int mChangedPackagesSequenceNumber;
767    /**
768     * List of changed [installed, removed or updated] packages.
769     * mapping from user id -> sequence number -> package name
770     */
771    @GuardedBy("mPackages")
772    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
773    /**
774     * The sequence number of the last change to a package.
775     * mapping from user id -> package name -> sequence number
776     */
777    @GuardedBy("mPackages")
778    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
779
780    class PackageParserCallback implements PackageParser.Callback {
781        @Override public final boolean hasFeature(String feature) {
782            return PackageManagerService.this.hasSystemFeature(feature, 0);
783        }
784
785        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
786                Collection<PackageParser.Package> allPackages, String targetPackageName) {
787            List<PackageParser.Package> overlayPackages = null;
788            for (PackageParser.Package p : allPackages) {
789                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
790                    if (overlayPackages == null) {
791                        overlayPackages = new ArrayList<PackageParser.Package>();
792                    }
793                    overlayPackages.add(p);
794                }
795            }
796            if (overlayPackages != null) {
797                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
798                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
799                        return p1.mOverlayPriority - p2.mOverlayPriority;
800                    }
801                };
802                Collections.sort(overlayPackages, cmp);
803            }
804            return overlayPackages;
805        }
806
807        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
808                String targetPackageName, String targetPath) {
809            if ("android".equals(targetPackageName)) {
810                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
811                // native AssetManager.
812                return null;
813            }
814            List<PackageParser.Package> overlayPackages =
815                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
816            if (overlayPackages == null || overlayPackages.isEmpty()) {
817                return null;
818            }
819            List<String> overlayPathList = null;
820            for (PackageParser.Package overlayPackage : overlayPackages) {
821                if (targetPath == null) {
822                    if (overlayPathList == null) {
823                        overlayPathList = new ArrayList<String>();
824                    }
825                    overlayPathList.add(overlayPackage.baseCodePath);
826                    continue;
827                }
828
829                try {
830                    // Creates idmaps for system to parse correctly the Android manifest of the
831                    // target package.
832                    //
833                    // OverlayManagerService will update each of them with a correct gid from its
834                    // target package app id.
835                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
836                            UserHandle.getSharedAppGid(
837                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
838                    if (overlayPathList == null) {
839                        overlayPathList = new ArrayList<String>();
840                    }
841                    overlayPathList.add(overlayPackage.baseCodePath);
842                } catch (InstallerException e) {
843                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
844                            overlayPackage.baseCodePath);
845                }
846            }
847            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
848        }
849
850        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
851            synchronized (mPackages) {
852                return getStaticOverlayPathsLocked(
853                        mPackages.values(), targetPackageName, targetPath);
854            }
855        }
856
857        @Override public final String[] getOverlayApks(String targetPackageName) {
858            return getStaticOverlayPaths(targetPackageName, null);
859        }
860
861        @Override public final String[] getOverlayPaths(String targetPackageName,
862                String targetPath) {
863            return getStaticOverlayPaths(targetPackageName, targetPath);
864        }
865    };
866
867    class ParallelPackageParserCallback extends PackageParserCallback {
868        List<PackageParser.Package> mOverlayPackages = null;
869
870        void findStaticOverlayPackages() {
871            synchronized (mPackages) {
872                for (PackageParser.Package p : mPackages.values()) {
873                    if (p.mIsStaticOverlay) {
874                        if (mOverlayPackages == null) {
875                            mOverlayPackages = new ArrayList<PackageParser.Package>();
876                        }
877                        mOverlayPackages.add(p);
878                    }
879                }
880            }
881        }
882
883        @Override
884        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
885            // We can trust mOverlayPackages without holding mPackages because package uninstall
886            // can't happen while running parallel parsing.
887            // Moreover holding mPackages on each parsing thread causes dead-lock.
888            return mOverlayPackages == null ? null :
889                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
890        }
891    }
892
893    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
894    final ParallelPackageParserCallback mParallelPackageParserCallback =
895            new ParallelPackageParserCallback();
896
897    public static final class SharedLibraryEntry {
898        public final @Nullable String path;
899        public final @Nullable String apk;
900        public final @NonNull SharedLibraryInfo info;
901
902        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
903                String declaringPackageName, int declaringPackageVersionCode) {
904            path = _path;
905            apk = _apk;
906            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
907                    declaringPackageName, declaringPackageVersionCode), null);
908        }
909    }
910
911    // Currently known shared libraries.
912    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
913    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
914            new ArrayMap<>();
915
916    // All available activities, for your resolving pleasure.
917    final ActivityIntentResolver mActivities =
918            new ActivityIntentResolver();
919
920    // All available receivers, for your resolving pleasure.
921    final ActivityIntentResolver mReceivers =
922            new ActivityIntentResolver();
923
924    // All available services, for your resolving pleasure.
925    final ServiceIntentResolver mServices = new ServiceIntentResolver();
926
927    // All available providers, for your resolving pleasure.
928    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
929
930    // Mapping from provider base names (first directory in content URI codePath)
931    // to the provider information.
932    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
933            new ArrayMap<String, PackageParser.Provider>();
934
935    // Mapping from instrumentation class names to info about them.
936    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
937            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
938
939    // Mapping from permission names to info about them.
940    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
941            new ArrayMap<String, PackageParser.PermissionGroup>();
942
943    // Packages whose data we have transfered into another package, thus
944    // should no longer exist.
945    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
946
947    // Broadcast actions that are only available to the system.
948    @GuardedBy("mProtectedBroadcasts")
949    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
950
951    /** List of packages waiting for verification. */
952    final SparseArray<PackageVerificationState> mPendingVerification
953            = new SparseArray<PackageVerificationState>();
954
955    /** Set of packages associated with each app op permission. */
956    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
957
958    final PackageInstallerService mInstallerService;
959
960    private final PackageDexOptimizer mPackageDexOptimizer;
961    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
962    // is used by other apps).
963    private final DexManager mDexManager;
964
965    private AtomicInteger mNextMoveId = new AtomicInteger();
966    private final MoveCallbacks mMoveCallbacks;
967
968    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
969
970    // Cache of users who need badging.
971    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
972
973    /** Token for keys in mPendingVerification. */
974    private int mPendingVerificationToken = 0;
975
976    volatile boolean mSystemReady;
977    volatile boolean mSafeMode;
978    volatile boolean mHasSystemUidErrors;
979    private volatile boolean mEphemeralAppsDisabled;
980
981    ApplicationInfo mAndroidApplication;
982    final ActivityInfo mResolveActivity = new ActivityInfo();
983    final ResolveInfo mResolveInfo = new ResolveInfo();
984    ComponentName mResolveComponentName;
985    PackageParser.Package mPlatformPackage;
986    ComponentName mCustomResolverComponentName;
987
988    boolean mResolverReplaced = false;
989
990    private final @Nullable ComponentName mIntentFilterVerifierComponent;
991    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
992
993    private int mIntentFilterVerificationToken = 0;
994
995    /** The service connection to the ephemeral resolver */
996    final EphemeralResolverConnection mInstantAppResolverConnection;
997    /** Component used to show resolver settings for Instant Apps */
998    final ComponentName mInstantAppResolverSettingsComponent;
999
1000    /** Activity used to install instant applications */
1001    ActivityInfo mInstantAppInstallerActivity;
1002    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1003
1004    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1005            = new SparseArray<IntentFilterVerificationState>();
1006
1007    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1008
1009    // List of packages names to keep cached, even if they are uninstalled for all users
1010    private List<String> mKeepUninstalledPackages;
1011
1012    private UserManagerInternal mUserManagerInternal;
1013
1014    private DeviceIdleController.LocalService mDeviceIdleController;
1015
1016    private File mCacheDir;
1017
1018    private ArraySet<String> mPrivappPermissionsViolations;
1019
1020    private Future<?> mPrepareAppDataFuture;
1021
1022    private static class IFVerificationParams {
1023        PackageParser.Package pkg;
1024        boolean replacing;
1025        int userId;
1026        int verifierUid;
1027
1028        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1029                int _userId, int _verifierUid) {
1030            pkg = _pkg;
1031            replacing = _replacing;
1032            userId = _userId;
1033            replacing = _replacing;
1034            verifierUid = _verifierUid;
1035        }
1036    }
1037
1038    private interface IntentFilterVerifier<T extends IntentFilter> {
1039        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1040                                               T filter, String packageName);
1041        void startVerifications(int userId);
1042        void receiveVerificationResponse(int verificationId);
1043    }
1044
1045    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1046        private Context mContext;
1047        private ComponentName mIntentFilterVerifierComponent;
1048        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1049
1050        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1051            mContext = context;
1052            mIntentFilterVerifierComponent = verifierComponent;
1053        }
1054
1055        private String getDefaultScheme() {
1056            return IntentFilter.SCHEME_HTTPS;
1057        }
1058
1059        @Override
1060        public void startVerifications(int userId) {
1061            // Launch verifications requests
1062            int count = mCurrentIntentFilterVerifications.size();
1063            for (int n=0; n<count; n++) {
1064                int verificationId = mCurrentIntentFilterVerifications.get(n);
1065                final IntentFilterVerificationState ivs =
1066                        mIntentFilterVerificationStates.get(verificationId);
1067
1068                String packageName = ivs.getPackageName();
1069
1070                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1071                final int filterCount = filters.size();
1072                ArraySet<String> domainsSet = new ArraySet<>();
1073                for (int m=0; m<filterCount; m++) {
1074                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1075                    domainsSet.addAll(filter.getHostsList());
1076                }
1077                synchronized (mPackages) {
1078                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1079                            packageName, domainsSet) != null) {
1080                        scheduleWriteSettingsLocked();
1081                    }
1082                }
1083                sendVerificationRequest(verificationId, ivs);
1084            }
1085            mCurrentIntentFilterVerifications.clear();
1086        }
1087
1088        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1089            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1090            verificationIntent.putExtra(
1091                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1092                    verificationId);
1093            verificationIntent.putExtra(
1094                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1095                    getDefaultScheme());
1096            verificationIntent.putExtra(
1097                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1098                    ivs.getHostsString());
1099            verificationIntent.putExtra(
1100                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1101                    ivs.getPackageName());
1102            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1103            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1104
1105            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1106            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1107                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1108                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1109
1110            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1111            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1112                    "Sending IntentFilter verification broadcast");
1113        }
1114
1115        public void receiveVerificationResponse(int verificationId) {
1116            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1117
1118            final boolean verified = ivs.isVerified();
1119
1120            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1121            final int count = filters.size();
1122            if (DEBUG_DOMAIN_VERIFICATION) {
1123                Slog.i(TAG, "Received verification response " + verificationId
1124                        + " for " + count + " filters, verified=" + verified);
1125            }
1126            for (int n=0; n<count; n++) {
1127                PackageParser.ActivityIntentInfo filter = filters.get(n);
1128                filter.setVerified(verified);
1129
1130                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1131                        + " verified with result:" + verified + " and hosts:"
1132                        + ivs.getHostsString());
1133            }
1134
1135            mIntentFilterVerificationStates.remove(verificationId);
1136
1137            final String packageName = ivs.getPackageName();
1138            IntentFilterVerificationInfo ivi = null;
1139
1140            synchronized (mPackages) {
1141                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1142            }
1143            if (ivi == null) {
1144                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1145                        + verificationId + " packageName:" + packageName);
1146                return;
1147            }
1148            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1149                    "Updating IntentFilterVerificationInfo for package " + packageName
1150                            +" verificationId:" + verificationId);
1151
1152            synchronized (mPackages) {
1153                if (verified) {
1154                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1155                } else {
1156                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1157                }
1158                scheduleWriteSettingsLocked();
1159
1160                final int userId = ivs.getUserId();
1161                if (userId != UserHandle.USER_ALL) {
1162                    final int userStatus =
1163                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1164
1165                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1166                    boolean needUpdate = false;
1167
1168                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1169                    // already been set by the User thru the Disambiguation dialog
1170                    switch (userStatus) {
1171                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1172                            if (verified) {
1173                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1174                            } else {
1175                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1176                            }
1177                            needUpdate = true;
1178                            break;
1179
1180                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1181                            if (verified) {
1182                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1183                                needUpdate = true;
1184                            }
1185                            break;
1186
1187                        default:
1188                            // Nothing to do
1189                    }
1190
1191                    if (needUpdate) {
1192                        mSettings.updateIntentFilterVerificationStatusLPw(
1193                                packageName, updatedStatus, userId);
1194                        scheduleWritePackageRestrictionsLocked(userId);
1195                    }
1196                }
1197            }
1198        }
1199
1200        @Override
1201        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1202                    ActivityIntentInfo filter, String packageName) {
1203            if (!hasValidDomains(filter)) {
1204                return false;
1205            }
1206            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1207            if (ivs == null) {
1208                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1209                        packageName);
1210            }
1211            if (DEBUG_DOMAIN_VERIFICATION) {
1212                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1213            }
1214            ivs.addFilter(filter);
1215            return true;
1216        }
1217
1218        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1219                int userId, int verificationId, String packageName) {
1220            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1221                    verifierUid, userId, packageName);
1222            ivs.setPendingState();
1223            synchronized (mPackages) {
1224                mIntentFilterVerificationStates.append(verificationId, ivs);
1225                mCurrentIntentFilterVerifications.add(verificationId);
1226            }
1227            return ivs;
1228        }
1229    }
1230
1231    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1232        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1233                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1234                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1235    }
1236
1237    // Set of pending broadcasts for aggregating enable/disable of components.
1238    static class PendingPackageBroadcasts {
1239        // for each user id, a map of <package name -> components within that package>
1240        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1241
1242        public PendingPackageBroadcasts() {
1243            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1244        }
1245
1246        public ArrayList<String> get(int userId, String packageName) {
1247            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1248            return packages.get(packageName);
1249        }
1250
1251        public void put(int userId, String packageName, ArrayList<String> components) {
1252            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1253            packages.put(packageName, components);
1254        }
1255
1256        public void remove(int userId, String packageName) {
1257            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1258            if (packages != null) {
1259                packages.remove(packageName);
1260            }
1261        }
1262
1263        public void remove(int userId) {
1264            mUidMap.remove(userId);
1265        }
1266
1267        public int userIdCount() {
1268            return mUidMap.size();
1269        }
1270
1271        public int userIdAt(int n) {
1272            return mUidMap.keyAt(n);
1273        }
1274
1275        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1276            return mUidMap.get(userId);
1277        }
1278
1279        public int size() {
1280            // total number of pending broadcast entries across all userIds
1281            int num = 0;
1282            for (int i = 0; i< mUidMap.size(); i++) {
1283                num += mUidMap.valueAt(i).size();
1284            }
1285            return num;
1286        }
1287
1288        public void clear() {
1289            mUidMap.clear();
1290        }
1291
1292        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1293            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1294            if (map == null) {
1295                map = new ArrayMap<String, ArrayList<String>>();
1296                mUidMap.put(userId, map);
1297            }
1298            return map;
1299        }
1300    }
1301    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1302
1303    // Service Connection to remote media container service to copy
1304    // package uri's from external media onto secure containers
1305    // or internal storage.
1306    private IMediaContainerService mContainerService = null;
1307
1308    static final int SEND_PENDING_BROADCAST = 1;
1309    static final int MCS_BOUND = 3;
1310    static final int END_COPY = 4;
1311    static final int INIT_COPY = 5;
1312    static final int MCS_UNBIND = 6;
1313    static final int START_CLEANING_PACKAGE = 7;
1314    static final int FIND_INSTALL_LOC = 8;
1315    static final int POST_INSTALL = 9;
1316    static final int MCS_RECONNECT = 10;
1317    static final int MCS_GIVE_UP = 11;
1318    static final int UPDATED_MEDIA_STATUS = 12;
1319    static final int WRITE_SETTINGS = 13;
1320    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1321    static final int PACKAGE_VERIFIED = 15;
1322    static final int CHECK_PENDING_VERIFICATION = 16;
1323    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1324    static final int INTENT_FILTER_VERIFIED = 18;
1325    static final int WRITE_PACKAGE_LIST = 19;
1326    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1327
1328    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1329
1330    // Delay time in millisecs
1331    static final int BROADCAST_DELAY = 10 * 1000;
1332
1333    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1334            2 * 60 * 60 * 1000L; /* two hours */
1335
1336    static UserManagerService sUserManager;
1337
1338    // Stores a list of users whose package restrictions file needs to be updated
1339    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1340
1341    final private DefaultContainerConnection mDefContainerConn =
1342            new DefaultContainerConnection();
1343    class DefaultContainerConnection implements ServiceConnection {
1344        public void onServiceConnected(ComponentName name, IBinder service) {
1345            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1346            final IMediaContainerService imcs = IMediaContainerService.Stub
1347                    .asInterface(Binder.allowBlocking(service));
1348            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1349        }
1350
1351        public void onServiceDisconnected(ComponentName name) {
1352            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1353        }
1354    }
1355
1356    // Recordkeeping of restore-after-install operations that are currently in flight
1357    // between the Package Manager and the Backup Manager
1358    static class PostInstallData {
1359        public InstallArgs args;
1360        public PackageInstalledInfo res;
1361
1362        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1363            args = _a;
1364            res = _r;
1365        }
1366    }
1367
1368    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1369    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1370
1371    // XML tags for backup/restore of various bits of state
1372    private static final String TAG_PREFERRED_BACKUP = "pa";
1373    private static final String TAG_DEFAULT_APPS = "da";
1374    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1375
1376    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1377    private static final String TAG_ALL_GRANTS = "rt-grants";
1378    private static final String TAG_GRANT = "grant";
1379    private static final String ATTR_PACKAGE_NAME = "pkg";
1380
1381    private static final String TAG_PERMISSION = "perm";
1382    private static final String ATTR_PERMISSION_NAME = "name";
1383    private static final String ATTR_IS_GRANTED = "g";
1384    private static final String ATTR_USER_SET = "set";
1385    private static final String ATTR_USER_FIXED = "fixed";
1386    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1387
1388    // System/policy permission grants are not backed up
1389    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1390            FLAG_PERMISSION_POLICY_FIXED
1391            | FLAG_PERMISSION_SYSTEM_FIXED
1392            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1393
1394    // And we back up these user-adjusted states
1395    private static final int USER_RUNTIME_GRANT_MASK =
1396            FLAG_PERMISSION_USER_SET
1397            | FLAG_PERMISSION_USER_FIXED
1398            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1399
1400    final @Nullable String mRequiredVerifierPackage;
1401    final @NonNull String mRequiredInstallerPackage;
1402    final @NonNull String mRequiredUninstallerPackage;
1403    final @Nullable String mSetupWizardPackage;
1404    final @Nullable String mStorageManagerPackage;
1405    final @NonNull String mServicesSystemSharedLibraryPackageName;
1406    final @NonNull String mSharedSystemSharedLibraryPackageName;
1407
1408    final boolean mPermissionReviewRequired;
1409
1410    private final PackageUsage mPackageUsage = new PackageUsage();
1411    private final CompilerStats mCompilerStats = new CompilerStats();
1412
1413    class PackageHandler extends Handler {
1414        private boolean mBound = false;
1415        final ArrayList<HandlerParams> mPendingInstalls =
1416            new ArrayList<HandlerParams>();
1417
1418        private boolean connectToService() {
1419            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1420                    " DefaultContainerService");
1421            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1423            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1424                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1425                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1426                mBound = true;
1427                return true;
1428            }
1429            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1430            return false;
1431        }
1432
1433        private void disconnectService() {
1434            mContainerService = null;
1435            mBound = false;
1436            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1437            mContext.unbindService(mDefContainerConn);
1438            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1439        }
1440
1441        PackageHandler(Looper looper) {
1442            super(looper);
1443        }
1444
1445        public void handleMessage(Message msg) {
1446            try {
1447                doHandleMessage(msg);
1448            } finally {
1449                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1450            }
1451        }
1452
1453        void doHandleMessage(Message msg) {
1454            switch (msg.what) {
1455                case INIT_COPY: {
1456                    HandlerParams params = (HandlerParams) msg.obj;
1457                    int idx = mPendingInstalls.size();
1458                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1459                    // If a bind was already initiated we dont really
1460                    // need to do anything. The pending install
1461                    // will be processed later on.
1462                    if (!mBound) {
1463                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1464                                System.identityHashCode(mHandler));
1465                        // If this is the only one pending we might
1466                        // have to bind to the service again.
1467                        if (!connectToService()) {
1468                            Slog.e(TAG, "Failed to bind to media container service");
1469                            params.serviceError();
1470                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1471                                    System.identityHashCode(mHandler));
1472                            if (params.traceMethod != null) {
1473                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1474                                        params.traceCookie);
1475                            }
1476                            return;
1477                        } else {
1478                            // Once we bind to the service, the first
1479                            // pending request will be processed.
1480                            mPendingInstalls.add(idx, params);
1481                        }
1482                    } else {
1483                        mPendingInstalls.add(idx, params);
1484                        // Already bound to the service. Just make
1485                        // sure we trigger off processing the first request.
1486                        if (idx == 0) {
1487                            mHandler.sendEmptyMessage(MCS_BOUND);
1488                        }
1489                    }
1490                    break;
1491                }
1492                case MCS_BOUND: {
1493                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1494                    if (msg.obj != null) {
1495                        mContainerService = (IMediaContainerService) msg.obj;
1496                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1497                                System.identityHashCode(mHandler));
1498                    }
1499                    if (mContainerService == null) {
1500                        if (!mBound) {
1501                            // Something seriously wrong since we are not bound and we are not
1502                            // waiting for connection. Bail out.
1503                            Slog.e(TAG, "Cannot bind to media container service");
1504                            for (HandlerParams params : mPendingInstalls) {
1505                                // Indicate service bind error
1506                                params.serviceError();
1507                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1508                                        System.identityHashCode(params));
1509                                if (params.traceMethod != null) {
1510                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1511                                            params.traceMethod, params.traceCookie);
1512                                }
1513                                return;
1514                            }
1515                            mPendingInstalls.clear();
1516                        } else {
1517                            Slog.w(TAG, "Waiting to connect to media container service");
1518                        }
1519                    } else if (mPendingInstalls.size() > 0) {
1520                        HandlerParams params = mPendingInstalls.get(0);
1521                        if (params != null) {
1522                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1523                                    System.identityHashCode(params));
1524                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1525                            if (params.startCopy()) {
1526                                // We are done...  look for more work or to
1527                                // go idle.
1528                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1529                                        "Checking for more work or unbind...");
1530                                // Delete pending install
1531                                if (mPendingInstalls.size() > 0) {
1532                                    mPendingInstalls.remove(0);
1533                                }
1534                                if (mPendingInstalls.size() == 0) {
1535                                    if (mBound) {
1536                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1537                                                "Posting delayed MCS_UNBIND");
1538                                        removeMessages(MCS_UNBIND);
1539                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1540                                        // Unbind after a little delay, to avoid
1541                                        // continual thrashing.
1542                                        sendMessageDelayed(ubmsg, 10000);
1543                                    }
1544                                } else {
1545                                    // There are more pending requests in queue.
1546                                    // Just post MCS_BOUND message to trigger processing
1547                                    // of next pending install.
1548                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1549                                            "Posting MCS_BOUND for next work");
1550                                    mHandler.sendEmptyMessage(MCS_BOUND);
1551                                }
1552                            }
1553                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1554                        }
1555                    } else {
1556                        // Should never happen ideally.
1557                        Slog.w(TAG, "Empty queue");
1558                    }
1559                    break;
1560                }
1561                case MCS_RECONNECT: {
1562                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1563                    if (mPendingInstalls.size() > 0) {
1564                        if (mBound) {
1565                            disconnectService();
1566                        }
1567                        if (!connectToService()) {
1568                            Slog.e(TAG, "Failed to bind to media container service");
1569                            for (HandlerParams params : mPendingInstalls) {
1570                                // Indicate service bind error
1571                                params.serviceError();
1572                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1573                                        System.identityHashCode(params));
1574                            }
1575                            mPendingInstalls.clear();
1576                        }
1577                    }
1578                    break;
1579                }
1580                case MCS_UNBIND: {
1581                    // If there is no actual work left, then time to unbind.
1582                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1583
1584                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1585                        if (mBound) {
1586                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1587
1588                            disconnectService();
1589                        }
1590                    } else if (mPendingInstalls.size() > 0) {
1591                        // There are more pending requests in queue.
1592                        // Just post MCS_BOUND message to trigger processing
1593                        // of next pending install.
1594                        mHandler.sendEmptyMessage(MCS_BOUND);
1595                    }
1596
1597                    break;
1598                }
1599                case MCS_GIVE_UP: {
1600                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1601                    HandlerParams params = mPendingInstalls.remove(0);
1602                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1603                            System.identityHashCode(params));
1604                    break;
1605                }
1606                case SEND_PENDING_BROADCAST: {
1607                    String packages[];
1608                    ArrayList<String> components[];
1609                    int size = 0;
1610                    int uids[];
1611                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1612                    synchronized (mPackages) {
1613                        if (mPendingBroadcasts == null) {
1614                            return;
1615                        }
1616                        size = mPendingBroadcasts.size();
1617                        if (size <= 0) {
1618                            // Nothing to be done. Just return
1619                            return;
1620                        }
1621                        packages = new String[size];
1622                        components = new ArrayList[size];
1623                        uids = new int[size];
1624                        int i = 0;  // filling out the above arrays
1625
1626                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1627                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1628                            Iterator<Map.Entry<String, ArrayList<String>>> it
1629                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1630                                            .entrySet().iterator();
1631                            while (it.hasNext() && i < size) {
1632                                Map.Entry<String, ArrayList<String>> ent = it.next();
1633                                packages[i] = ent.getKey();
1634                                components[i] = ent.getValue();
1635                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1636                                uids[i] = (ps != null)
1637                                        ? UserHandle.getUid(packageUserId, ps.appId)
1638                                        : -1;
1639                                i++;
1640                            }
1641                        }
1642                        size = i;
1643                        mPendingBroadcasts.clear();
1644                    }
1645                    // Send broadcasts
1646                    for (int i = 0; i < size; i++) {
1647                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1648                    }
1649                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1650                    break;
1651                }
1652                case START_CLEANING_PACKAGE: {
1653                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1654                    final String packageName = (String)msg.obj;
1655                    final int userId = msg.arg1;
1656                    final boolean andCode = msg.arg2 != 0;
1657                    synchronized (mPackages) {
1658                        if (userId == UserHandle.USER_ALL) {
1659                            int[] users = sUserManager.getUserIds();
1660                            for (int user : users) {
1661                                mSettings.addPackageToCleanLPw(
1662                                        new PackageCleanItem(user, packageName, andCode));
1663                            }
1664                        } else {
1665                            mSettings.addPackageToCleanLPw(
1666                                    new PackageCleanItem(userId, packageName, andCode));
1667                        }
1668                    }
1669                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1670                    startCleaningPackages();
1671                } break;
1672                case POST_INSTALL: {
1673                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1674
1675                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1676                    final boolean didRestore = (msg.arg2 != 0);
1677                    mRunningInstalls.delete(msg.arg1);
1678
1679                    if (data != null) {
1680                        InstallArgs args = data.args;
1681                        PackageInstalledInfo parentRes = data.res;
1682
1683                        final boolean grantPermissions = (args.installFlags
1684                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1685                        final boolean killApp = (args.installFlags
1686                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1687                        final boolean virtualPreload = ((args.installFlags
1688                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1689                        final String[] grantedPermissions = args.installGrantPermissions;
1690
1691                        // Handle the parent package
1692                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1693                                virtualPreload, grantedPermissions, didRestore,
1694                                args.installerPackageName, args.observer);
1695
1696                        // Handle the child packages
1697                        final int childCount = (parentRes.addedChildPackages != null)
1698                                ? parentRes.addedChildPackages.size() : 0;
1699                        for (int i = 0; i < childCount; i++) {
1700                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1701                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1702                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1703                                    args.installerPackageName, args.observer);
1704                        }
1705
1706                        // Log tracing if needed
1707                        if (args.traceMethod != null) {
1708                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1709                                    args.traceCookie);
1710                        }
1711                    } else {
1712                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1713                    }
1714
1715                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1716                } break;
1717                case UPDATED_MEDIA_STATUS: {
1718                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1719                    boolean reportStatus = msg.arg1 == 1;
1720                    boolean doGc = msg.arg2 == 1;
1721                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1722                    if (doGc) {
1723                        // Force a gc to clear up stale containers.
1724                        Runtime.getRuntime().gc();
1725                    }
1726                    if (msg.obj != null) {
1727                        @SuppressWarnings("unchecked")
1728                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1729                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1730                        // Unload containers
1731                        unloadAllContainers(args);
1732                    }
1733                    if (reportStatus) {
1734                        try {
1735                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1736                                    "Invoking StorageManagerService call back");
1737                            PackageHelper.getStorageManager().finishMediaUpdate();
1738                        } catch (RemoteException e) {
1739                            Log.e(TAG, "StorageManagerService not running?");
1740                        }
1741                    }
1742                } break;
1743                case WRITE_SETTINGS: {
1744                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1745                    synchronized (mPackages) {
1746                        removeMessages(WRITE_SETTINGS);
1747                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1748                        mSettings.writeLPr();
1749                        mDirtyUsers.clear();
1750                    }
1751                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1752                } break;
1753                case WRITE_PACKAGE_RESTRICTIONS: {
1754                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1755                    synchronized (mPackages) {
1756                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1757                        for (int userId : mDirtyUsers) {
1758                            mSettings.writePackageRestrictionsLPr(userId);
1759                        }
1760                        mDirtyUsers.clear();
1761                    }
1762                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1763                } break;
1764                case WRITE_PACKAGE_LIST: {
1765                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1766                    synchronized (mPackages) {
1767                        removeMessages(WRITE_PACKAGE_LIST);
1768                        mSettings.writePackageListLPr(msg.arg1);
1769                    }
1770                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1771                } break;
1772                case CHECK_PENDING_VERIFICATION: {
1773                    final int verificationId = msg.arg1;
1774                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1775
1776                    if ((state != null) && !state.timeoutExtended()) {
1777                        final InstallArgs args = state.getInstallArgs();
1778                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1779
1780                        Slog.i(TAG, "Verification timed out for " + originUri);
1781                        mPendingVerification.remove(verificationId);
1782
1783                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1784
1785                        final UserHandle user = args.getUser();
1786                        if (getDefaultVerificationResponse(user)
1787                                == PackageManager.VERIFICATION_ALLOW) {
1788                            Slog.i(TAG, "Continuing with installation of " + originUri);
1789                            state.setVerifierResponse(Binder.getCallingUid(),
1790                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1791                            broadcastPackageVerified(verificationId, originUri,
1792                                    PackageManager.VERIFICATION_ALLOW, user);
1793                            try {
1794                                ret = args.copyApk(mContainerService, true);
1795                            } catch (RemoteException e) {
1796                                Slog.e(TAG, "Could not contact the ContainerService");
1797                            }
1798                        } else {
1799                            broadcastPackageVerified(verificationId, originUri,
1800                                    PackageManager.VERIFICATION_REJECT, user);
1801                        }
1802
1803                        Trace.asyncTraceEnd(
1804                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1805
1806                        processPendingInstall(args, ret);
1807                        mHandler.sendEmptyMessage(MCS_UNBIND);
1808                    }
1809                    break;
1810                }
1811                case PACKAGE_VERIFIED: {
1812                    final int verificationId = msg.arg1;
1813
1814                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1815                    if (state == null) {
1816                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1817                        break;
1818                    }
1819
1820                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1821
1822                    state.setVerifierResponse(response.callerUid, response.code);
1823
1824                    if (state.isVerificationComplete()) {
1825                        mPendingVerification.remove(verificationId);
1826
1827                        final InstallArgs args = state.getInstallArgs();
1828                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1829
1830                        int ret;
1831                        if (state.isInstallAllowed()) {
1832                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1833                            broadcastPackageVerified(verificationId, originUri,
1834                                    response.code, state.getInstallArgs().getUser());
1835                            try {
1836                                ret = args.copyApk(mContainerService, true);
1837                            } catch (RemoteException e) {
1838                                Slog.e(TAG, "Could not contact the ContainerService");
1839                            }
1840                        } else {
1841                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1842                        }
1843
1844                        Trace.asyncTraceEnd(
1845                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1846
1847                        processPendingInstall(args, ret);
1848                        mHandler.sendEmptyMessage(MCS_UNBIND);
1849                    }
1850
1851                    break;
1852                }
1853                case START_INTENT_FILTER_VERIFICATIONS: {
1854                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1855                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1856                            params.replacing, params.pkg);
1857                    break;
1858                }
1859                case INTENT_FILTER_VERIFIED: {
1860                    final int verificationId = msg.arg1;
1861
1862                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1863                            verificationId);
1864                    if (state == null) {
1865                        Slog.w(TAG, "Invalid IntentFilter verification token "
1866                                + verificationId + " received");
1867                        break;
1868                    }
1869
1870                    final int userId = state.getUserId();
1871
1872                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1873                            "Processing IntentFilter verification with token:"
1874                            + verificationId + " and userId:" + userId);
1875
1876                    final IntentFilterVerificationResponse response =
1877                            (IntentFilterVerificationResponse) msg.obj;
1878
1879                    state.setVerifierResponse(response.callerUid, response.code);
1880
1881                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1882                            "IntentFilter verification with token:" + verificationId
1883                            + " and userId:" + userId
1884                            + " is settings verifier response with response code:"
1885                            + response.code);
1886
1887                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1888                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1889                                + response.getFailedDomainsString());
1890                    }
1891
1892                    if (state.isVerificationComplete()) {
1893                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1894                    } else {
1895                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1896                                "IntentFilter verification with token:" + verificationId
1897                                + " was not said to be complete");
1898                    }
1899
1900                    break;
1901                }
1902                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1903                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1904                            mInstantAppResolverConnection,
1905                            (InstantAppRequest) msg.obj,
1906                            mInstantAppInstallerActivity,
1907                            mHandler);
1908                }
1909            }
1910        }
1911    }
1912
1913    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1914            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1915            boolean launchedForRestore, String installerPackage,
1916            IPackageInstallObserver2 installObserver) {
1917        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1918            // Send the removed broadcasts
1919            if (res.removedInfo != null) {
1920                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1921            }
1922
1923            // Now that we successfully installed the package, grant runtime
1924            // permissions if requested before broadcasting the install. Also
1925            // for legacy apps in permission review mode we clear the permission
1926            // review flag which is used to emulate runtime permissions for
1927            // legacy apps.
1928            if (grantPermissions) {
1929                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1930            }
1931
1932            final boolean update = res.removedInfo != null
1933                    && res.removedInfo.removedPackage != null;
1934            final String installerPackageName =
1935                    res.installerPackageName != null
1936                            ? res.installerPackageName
1937                            : res.removedInfo != null
1938                                    ? res.removedInfo.installerPackageName
1939                                    : null;
1940
1941            // If this is the first time we have child packages for a disabled privileged
1942            // app that had no children, we grant requested runtime permissions to the new
1943            // children if the parent on the system image had them already granted.
1944            if (res.pkg.parentPackage != null) {
1945                synchronized (mPackages) {
1946                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1947                }
1948            }
1949
1950            synchronized (mPackages) {
1951                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1952            }
1953
1954            final String packageName = res.pkg.applicationInfo.packageName;
1955
1956            // Determine the set of users who are adding this package for
1957            // the first time vs. those who are seeing an update.
1958            int[] firstUsers = EMPTY_INT_ARRAY;
1959            int[] updateUsers = EMPTY_INT_ARRAY;
1960            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1961            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1962            for (int newUser : res.newUsers) {
1963                if (ps.getInstantApp(newUser)) {
1964                    continue;
1965                }
1966                if (allNewUsers) {
1967                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1968                    continue;
1969                }
1970                boolean isNew = true;
1971                for (int origUser : res.origUsers) {
1972                    if (origUser == newUser) {
1973                        isNew = false;
1974                        break;
1975                    }
1976                }
1977                if (isNew) {
1978                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1979                } else {
1980                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1981                }
1982            }
1983
1984            // Send installed broadcasts if the package is not a static shared lib.
1985            if (res.pkg.staticSharedLibName == null) {
1986                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1987
1988                // Send added for users that see the package for the first time
1989                // sendPackageAddedForNewUsers also deals with system apps
1990                int appId = UserHandle.getAppId(res.uid);
1991                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1992                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1993                        virtualPreload /*startReceiver*/, appId, firstUsers);
1994
1995                // Send added for users that don't see the package for the first time
1996                Bundle extras = new Bundle(1);
1997                extras.putInt(Intent.EXTRA_UID, res.uid);
1998                if (update) {
1999                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2000                }
2001                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2002                        extras, 0 /*flags*/,
2003                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2004                if (installerPackageName != null) {
2005                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2006                            extras, 0 /*flags*/,
2007                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2008                }
2009
2010                // Send replaced for users that don't see the package for the first time
2011                if (update) {
2012                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2013                            packageName, extras, 0 /*flags*/,
2014                            null /*targetPackage*/, null /*finishedReceiver*/,
2015                            updateUsers);
2016                    if (installerPackageName != null) {
2017                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2018                                extras, 0 /*flags*/,
2019                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2020                    }
2021                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2022                            null /*package*/, null /*extras*/, 0 /*flags*/,
2023                            packageName /*targetPackage*/,
2024                            null /*finishedReceiver*/, updateUsers);
2025                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2026                    // First-install and we did a restore, so we're responsible for the
2027                    // first-launch broadcast.
2028                    if (DEBUG_BACKUP) {
2029                        Slog.i(TAG, "Post-restore of " + packageName
2030                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2031                    }
2032                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2033                }
2034
2035                // Send broadcast package appeared if forward locked/external for all users
2036                // treat asec-hosted packages like removable media on upgrade
2037                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2038                    if (DEBUG_INSTALL) {
2039                        Slog.i(TAG, "upgrading pkg " + res.pkg
2040                                + " is ASEC-hosted -> AVAILABLE");
2041                    }
2042                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2043                    ArrayList<String> pkgList = new ArrayList<>(1);
2044                    pkgList.add(packageName);
2045                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2046                }
2047            }
2048
2049            // Work that needs to happen on first install within each user
2050            if (firstUsers != null && firstUsers.length > 0) {
2051                synchronized (mPackages) {
2052                    for (int userId : firstUsers) {
2053                        // If this app is a browser and it's newly-installed for some
2054                        // users, clear any default-browser state in those users. The
2055                        // app's nature doesn't depend on the user, so we can just check
2056                        // its browser nature in any user and generalize.
2057                        if (packageIsBrowser(packageName, userId)) {
2058                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2059                        }
2060
2061                        // We may also need to apply pending (restored) runtime
2062                        // permission grants within these users.
2063                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2064                    }
2065                }
2066            }
2067
2068            // Log current value of "unknown sources" setting
2069            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2070                    getUnknownSourcesSettings());
2071
2072            // Remove the replaced package's older resources safely now
2073            // We delete after a gc for applications  on sdcard.
2074            if (res.removedInfo != null && res.removedInfo.args != null) {
2075                Runtime.getRuntime().gc();
2076                synchronized (mInstallLock) {
2077                    res.removedInfo.args.doPostDeleteLI(true);
2078                }
2079            } else {
2080                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2081                // and not block here.
2082                VMRuntime.getRuntime().requestConcurrentGC();
2083            }
2084
2085            // Notify DexManager that the package was installed for new users.
2086            // The updated users should already be indexed and the package code paths
2087            // should not change.
2088            // Don't notify the manager for ephemeral apps as they are not expected to
2089            // survive long enough to benefit of background optimizations.
2090            for (int userId : firstUsers) {
2091                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2092                // There's a race currently where some install events may interleave with an uninstall.
2093                // This can lead to package info being null (b/36642664).
2094                if (info != null) {
2095                    mDexManager.notifyPackageInstalled(info, userId);
2096                }
2097            }
2098        }
2099
2100        // If someone is watching installs - notify them
2101        if (installObserver != null) {
2102            try {
2103                Bundle extras = extrasForInstallResult(res);
2104                installObserver.onPackageInstalled(res.name, res.returnCode,
2105                        res.returnMsg, extras);
2106            } catch (RemoteException e) {
2107                Slog.i(TAG, "Observer no longer exists.");
2108            }
2109        }
2110    }
2111
2112    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2113            PackageParser.Package pkg) {
2114        if (pkg.parentPackage == null) {
2115            return;
2116        }
2117        if (pkg.requestedPermissions == null) {
2118            return;
2119        }
2120        final PackageSetting disabledSysParentPs = mSettings
2121                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2122        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2123                || !disabledSysParentPs.isPrivileged()
2124                || (disabledSysParentPs.childPackageNames != null
2125                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2126            return;
2127        }
2128        final int[] allUserIds = sUserManager.getUserIds();
2129        final int permCount = pkg.requestedPermissions.size();
2130        for (int i = 0; i < permCount; i++) {
2131            String permission = pkg.requestedPermissions.get(i);
2132            BasePermission bp = mSettings.mPermissions.get(permission);
2133            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2134                continue;
2135            }
2136            for (int userId : allUserIds) {
2137                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2138                        permission, userId)) {
2139                    grantRuntimePermission(pkg.packageName, permission, userId);
2140                }
2141            }
2142        }
2143    }
2144
2145    private StorageEventListener mStorageListener = new StorageEventListener() {
2146        @Override
2147        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2148            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2149                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2150                    final String volumeUuid = vol.getFsUuid();
2151
2152                    // Clean up any users or apps that were removed or recreated
2153                    // while this volume was missing
2154                    sUserManager.reconcileUsers(volumeUuid);
2155                    reconcileApps(volumeUuid);
2156
2157                    // Clean up any install sessions that expired or were
2158                    // cancelled while this volume was missing
2159                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2160
2161                    loadPrivatePackages(vol);
2162
2163                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2164                    unloadPrivatePackages(vol);
2165                }
2166            }
2167
2168            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2169                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2170                    updateExternalMediaStatus(true, false);
2171                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2172                    updateExternalMediaStatus(false, false);
2173                }
2174            }
2175        }
2176
2177        @Override
2178        public void onVolumeForgotten(String fsUuid) {
2179            if (TextUtils.isEmpty(fsUuid)) {
2180                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2181                return;
2182            }
2183
2184            // Remove any apps installed on the forgotten volume
2185            synchronized (mPackages) {
2186                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2187                for (PackageSetting ps : packages) {
2188                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2189                    deletePackageVersioned(new VersionedPackage(ps.name,
2190                            PackageManager.VERSION_CODE_HIGHEST),
2191                            new LegacyPackageDeleteObserver(null).getBinder(),
2192                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2193                    // Try very hard to release any references to this package
2194                    // so we don't risk the system server being killed due to
2195                    // open FDs
2196                    AttributeCache.instance().removePackage(ps.name);
2197                }
2198
2199                mSettings.onVolumeForgotten(fsUuid);
2200                mSettings.writeLPr();
2201            }
2202        }
2203    };
2204
2205    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2206            String[] grantedPermissions) {
2207        for (int userId : userIds) {
2208            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2209        }
2210    }
2211
2212    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2213            String[] grantedPermissions) {
2214        PackageSetting ps = (PackageSetting) pkg.mExtras;
2215        if (ps == null) {
2216            return;
2217        }
2218
2219        PermissionsState permissionsState = ps.getPermissionsState();
2220
2221        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2222                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2223
2224        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2225                >= Build.VERSION_CODES.M;
2226
2227        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2228
2229        for (String permission : pkg.requestedPermissions) {
2230            final BasePermission bp;
2231            synchronized (mPackages) {
2232                bp = mSettings.mPermissions.get(permission);
2233            }
2234            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2235                    && (!instantApp || bp.isInstant())
2236                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2237                    && (grantedPermissions == null
2238                           || ArrayUtils.contains(grantedPermissions, permission))) {
2239                final int flags = permissionsState.getPermissionFlags(permission, userId);
2240                if (supportsRuntimePermissions) {
2241                    // Installer cannot change immutable permissions.
2242                    if ((flags & immutableFlags) == 0) {
2243                        grantRuntimePermission(pkg.packageName, permission, userId);
2244                    }
2245                } else if (mPermissionReviewRequired) {
2246                    // In permission review mode we clear the review flag when we
2247                    // are asked to install the app with all permissions granted.
2248                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2249                        updatePermissionFlags(permission, pkg.packageName,
2250                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2251                    }
2252                }
2253            }
2254        }
2255    }
2256
2257    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2258        Bundle extras = null;
2259        switch (res.returnCode) {
2260            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2261                extras = new Bundle();
2262                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2263                        res.origPermission);
2264                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2265                        res.origPackage);
2266                break;
2267            }
2268            case PackageManager.INSTALL_SUCCEEDED: {
2269                extras = new Bundle();
2270                extras.putBoolean(Intent.EXTRA_REPLACING,
2271                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2272                break;
2273            }
2274        }
2275        return extras;
2276    }
2277
2278    void scheduleWriteSettingsLocked() {
2279        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2280            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2281        }
2282    }
2283
2284    void scheduleWritePackageListLocked(int userId) {
2285        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2286            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2287            msg.arg1 = userId;
2288            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2289        }
2290    }
2291
2292    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2293        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2294        scheduleWritePackageRestrictionsLocked(userId);
2295    }
2296
2297    void scheduleWritePackageRestrictionsLocked(int userId) {
2298        final int[] userIds = (userId == UserHandle.USER_ALL)
2299                ? sUserManager.getUserIds() : new int[]{userId};
2300        for (int nextUserId : userIds) {
2301            if (!sUserManager.exists(nextUserId)) return;
2302            mDirtyUsers.add(nextUserId);
2303            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2304                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2305            }
2306        }
2307    }
2308
2309    public static PackageManagerService main(Context context, Installer installer,
2310            boolean factoryTest, boolean onlyCore) {
2311        // Self-check for initial settings.
2312        PackageManagerServiceCompilerMapping.checkProperties();
2313
2314        PackageManagerService m = new PackageManagerService(context, installer,
2315                factoryTest, onlyCore);
2316        m.enableSystemUserPackages();
2317        ServiceManager.addService("package", m);
2318        final PackageManagerNative pmn = m.new PackageManagerNative();
2319        ServiceManager.addService("package_native", pmn);
2320        return m;
2321    }
2322
2323    private void enableSystemUserPackages() {
2324        if (!UserManager.isSplitSystemUser()) {
2325            return;
2326        }
2327        // For system user, enable apps based on the following conditions:
2328        // - app is whitelisted or belong to one of these groups:
2329        //   -- system app which has no launcher icons
2330        //   -- system app which has INTERACT_ACROSS_USERS permission
2331        //   -- system IME app
2332        // - app is not in the blacklist
2333        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2334        Set<String> enableApps = new ArraySet<>();
2335        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2336                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2337                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2338        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2339        enableApps.addAll(wlApps);
2340        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2341                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2342        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2343        enableApps.removeAll(blApps);
2344        Log.i(TAG, "Applications installed for system user: " + enableApps);
2345        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2346                UserHandle.SYSTEM);
2347        final int allAppsSize = allAps.size();
2348        synchronized (mPackages) {
2349            for (int i = 0; i < allAppsSize; i++) {
2350                String pName = allAps.get(i);
2351                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2352                // Should not happen, but we shouldn't be failing if it does
2353                if (pkgSetting == null) {
2354                    continue;
2355                }
2356                boolean install = enableApps.contains(pName);
2357                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2358                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2359                            + " for system user");
2360                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2361                }
2362            }
2363            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2364        }
2365    }
2366
2367    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2368        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2369                Context.DISPLAY_SERVICE);
2370        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2371    }
2372
2373    /**
2374     * Requests that files preopted on a secondary system partition be copied to the data partition
2375     * if possible.  Note that the actual copying of the files is accomplished by init for security
2376     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2377     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2378     */
2379    private static void requestCopyPreoptedFiles() {
2380        final int WAIT_TIME_MS = 100;
2381        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2382        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2383            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2384            // We will wait for up to 100 seconds.
2385            final long timeStart = SystemClock.uptimeMillis();
2386            final long timeEnd = timeStart + 100 * 1000;
2387            long timeNow = timeStart;
2388            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2389                try {
2390                    Thread.sleep(WAIT_TIME_MS);
2391                } catch (InterruptedException e) {
2392                    // Do nothing
2393                }
2394                timeNow = SystemClock.uptimeMillis();
2395                if (timeNow > timeEnd) {
2396                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2397                    Slog.wtf(TAG, "cppreopt did not finish!");
2398                    break;
2399                }
2400            }
2401
2402            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2403        }
2404    }
2405
2406    public PackageManagerService(Context context, Installer installer,
2407            boolean factoryTest, boolean onlyCore) {
2408        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2409        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2410        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2411                SystemClock.uptimeMillis());
2412
2413        if (mSdkVersion <= 0) {
2414            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2415        }
2416
2417        mContext = context;
2418
2419        mPermissionReviewRequired = context.getResources().getBoolean(
2420                R.bool.config_permissionReviewRequired);
2421
2422        mFactoryTest = factoryTest;
2423        mOnlyCore = onlyCore;
2424        mMetrics = new DisplayMetrics();
2425        mSettings = new Settings(mPackages);
2426        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2427                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2428        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2429                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2430        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2431                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2432        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2433                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2434        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2435                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2436        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2437                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2438
2439        String separateProcesses = SystemProperties.get("debug.separate_processes");
2440        if (separateProcesses != null && separateProcesses.length() > 0) {
2441            if ("*".equals(separateProcesses)) {
2442                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2443                mSeparateProcesses = null;
2444                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2445            } else {
2446                mDefParseFlags = 0;
2447                mSeparateProcesses = separateProcesses.split(",");
2448                Slog.w(TAG, "Running with debug.separate_processes: "
2449                        + separateProcesses);
2450            }
2451        } else {
2452            mDefParseFlags = 0;
2453            mSeparateProcesses = null;
2454        }
2455
2456        mInstaller = installer;
2457        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2458                "*dexopt*");
2459        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2460        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2461
2462        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2463                FgThread.get().getLooper());
2464
2465        getDefaultDisplayMetrics(context, mMetrics);
2466
2467        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2468        SystemConfig systemConfig = SystemConfig.getInstance();
2469        mGlobalGids = systemConfig.getGlobalGids();
2470        mSystemPermissions = systemConfig.getSystemPermissions();
2471        mAvailableFeatures = systemConfig.getAvailableFeatures();
2472        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2473
2474        mProtectedPackages = new ProtectedPackages(mContext);
2475
2476        synchronized (mInstallLock) {
2477        // writer
2478        synchronized (mPackages) {
2479            mHandlerThread = new ServiceThread(TAG,
2480                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2481            mHandlerThread.start();
2482            mHandler = new PackageHandler(mHandlerThread.getLooper());
2483            mProcessLoggingHandler = new ProcessLoggingHandler();
2484            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2485
2486            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2487            mInstantAppRegistry = new InstantAppRegistry(this);
2488
2489            File dataDir = Environment.getDataDirectory();
2490            mAppInstallDir = new File(dataDir, "app");
2491            mAppLib32InstallDir = new File(dataDir, "app-lib");
2492            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2493            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2494            sUserManager = new UserManagerService(context, this,
2495                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2496
2497            // Propagate permission configuration in to package manager.
2498            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2499                    = systemConfig.getPermissions();
2500            for (int i=0; i<permConfig.size(); i++) {
2501                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2502                BasePermission bp = mSettings.mPermissions.get(perm.name);
2503                if (bp == null) {
2504                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2505                    mSettings.mPermissions.put(perm.name, bp);
2506                }
2507                if (perm.gids != null) {
2508                    bp.setGids(perm.gids, perm.perUser);
2509                }
2510            }
2511
2512            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2513            final int builtInLibCount = libConfig.size();
2514            for (int i = 0; i < builtInLibCount; i++) {
2515                String name = libConfig.keyAt(i);
2516                String path = libConfig.valueAt(i);
2517                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2518                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2519            }
2520
2521            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2522
2523            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2524            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2525            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2526
2527            // Clean up orphaned packages for which the code path doesn't exist
2528            // and they are an update to a system app - caused by bug/32321269
2529            final int packageSettingCount = mSettings.mPackages.size();
2530            for (int i = packageSettingCount - 1; i >= 0; i--) {
2531                PackageSetting ps = mSettings.mPackages.valueAt(i);
2532                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2533                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2534                    mSettings.mPackages.removeAt(i);
2535                    mSettings.enableSystemPackageLPw(ps.name);
2536                }
2537            }
2538
2539            if (mFirstBoot) {
2540                requestCopyPreoptedFiles();
2541            }
2542
2543            String customResolverActivity = Resources.getSystem().getString(
2544                    R.string.config_customResolverActivity);
2545            if (TextUtils.isEmpty(customResolverActivity)) {
2546                customResolverActivity = null;
2547            } else {
2548                mCustomResolverComponentName = ComponentName.unflattenFromString(
2549                        customResolverActivity);
2550            }
2551
2552            long startTime = SystemClock.uptimeMillis();
2553
2554            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2555                    startTime);
2556
2557            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2558            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2559
2560            if (bootClassPath == null) {
2561                Slog.w(TAG, "No BOOTCLASSPATH found!");
2562            }
2563
2564            if (systemServerClassPath == null) {
2565                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2566            }
2567
2568            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2569
2570            final VersionInfo ver = mSettings.getInternalVersion();
2571            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2572            if (mIsUpgrade) {
2573                logCriticalInfo(Log.INFO,
2574                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2575            }
2576
2577            // when upgrading from pre-M, promote system app permissions from install to runtime
2578            mPromoteSystemApps =
2579                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2580
2581            // When upgrading from pre-N, we need to handle package extraction like first boot,
2582            // as there is no profiling data available.
2583            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2584
2585            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2586
2587            // save off the names of pre-existing system packages prior to scanning; we don't
2588            // want to automatically grant runtime permissions for new system apps
2589            if (mPromoteSystemApps) {
2590                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2591                while (pkgSettingIter.hasNext()) {
2592                    PackageSetting ps = pkgSettingIter.next();
2593                    if (isSystemApp(ps)) {
2594                        mExistingSystemPackages.add(ps.name);
2595                    }
2596                }
2597            }
2598
2599            mCacheDir = preparePackageParserCache(mIsUpgrade);
2600
2601            // Set flag to monitor and not change apk file paths when
2602            // scanning install directories.
2603            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2604
2605            if (mIsUpgrade || mFirstBoot) {
2606                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2607            }
2608
2609            // Collect vendor overlay packages. (Do this before scanning any apps.)
2610            // For security and version matching reason, only consider
2611            // overlay packages if they reside in the right directory.
2612            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2613                    | PackageParser.PARSE_IS_SYSTEM
2614                    | PackageParser.PARSE_IS_SYSTEM_DIR
2615                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2616
2617            mParallelPackageParserCallback.findStaticOverlayPackages();
2618
2619            // Find base frameworks (resource packages without code).
2620            scanDirTracedLI(frameworkDir, mDefParseFlags
2621                    | PackageParser.PARSE_IS_SYSTEM
2622                    | PackageParser.PARSE_IS_SYSTEM_DIR
2623                    | PackageParser.PARSE_IS_PRIVILEGED,
2624                    scanFlags | SCAN_NO_DEX, 0);
2625
2626            // Collected privileged system packages.
2627            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2628            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2629                    | PackageParser.PARSE_IS_SYSTEM
2630                    | PackageParser.PARSE_IS_SYSTEM_DIR
2631                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2632
2633            // Collect ordinary system packages.
2634            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2635            scanDirTracedLI(systemAppDir, mDefParseFlags
2636                    | PackageParser.PARSE_IS_SYSTEM
2637                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2638
2639            // Collect all vendor packages.
2640            File vendorAppDir = new File("/vendor/app");
2641            try {
2642                vendorAppDir = vendorAppDir.getCanonicalFile();
2643            } catch (IOException e) {
2644                // failed to look up canonical path, continue with original one
2645            }
2646            scanDirTracedLI(vendorAppDir, mDefParseFlags
2647                    | PackageParser.PARSE_IS_SYSTEM
2648                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2649
2650            // Collect all OEM packages.
2651            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2652            scanDirTracedLI(oemAppDir, mDefParseFlags
2653                    | PackageParser.PARSE_IS_SYSTEM
2654                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2655
2656            // Prune any system packages that no longer exist.
2657            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2658            // Stub packages must either be replaced with full versions in the /data
2659            // partition or be disabled.
2660            final List<String> stubSystemApps = new ArrayList<>();
2661            if (!mOnlyCore) {
2662                // do this first before mucking with mPackages for the "expecting better" case
2663                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2664                while (pkgIterator.hasNext()) {
2665                    final PackageParser.Package pkg = pkgIterator.next();
2666                    if (pkg.isStub) {
2667                        stubSystemApps.add(pkg.packageName);
2668                    }
2669                }
2670
2671                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2672                while (psit.hasNext()) {
2673                    PackageSetting ps = psit.next();
2674
2675                    /*
2676                     * If this is not a system app, it can't be a
2677                     * disable system app.
2678                     */
2679                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2680                        continue;
2681                    }
2682
2683                    /*
2684                     * If the package is scanned, it's not erased.
2685                     */
2686                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2687                    if (scannedPkg != null) {
2688                        /*
2689                         * If the system app is both scanned and in the
2690                         * disabled packages list, then it must have been
2691                         * added via OTA. Remove it from the currently
2692                         * scanned package so the previously user-installed
2693                         * application can be scanned.
2694                         */
2695                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2696                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2697                                    + ps.name + "; removing system app.  Last known codePath="
2698                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2699                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2700                                    + scannedPkg.mVersionCode);
2701                            removePackageLI(scannedPkg, true);
2702                            mExpectingBetter.put(ps.name, ps.codePath);
2703                        }
2704
2705                        continue;
2706                    }
2707
2708                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2709                        psit.remove();
2710                        logCriticalInfo(Log.WARN, "System package " + ps.name
2711                                + " no longer exists; it's data will be wiped");
2712                        // Actual deletion of code and data will be handled by later
2713                        // reconciliation step
2714                    } else {
2715                        // we still have a disabled system package, but, it still might have
2716                        // been removed. check the code path still exists and check there's
2717                        // still a package. the latter can happen if an OTA keeps the same
2718                        // code path, but, changes the package name.
2719                        final PackageSetting disabledPs =
2720                                mSettings.getDisabledSystemPkgLPr(ps.name);
2721                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2722                                || disabledPs.pkg == null) {
2723                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2724                        }
2725                    }
2726                }
2727            }
2728
2729            //look for any incomplete package installations
2730            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2731            for (int i = 0; i < deletePkgsList.size(); i++) {
2732                // Actual deletion of code and data will be handled by later
2733                // reconciliation step
2734                final String packageName = deletePkgsList.get(i).name;
2735                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2736                synchronized (mPackages) {
2737                    mSettings.removePackageLPw(packageName);
2738                }
2739            }
2740
2741            //delete tmp files
2742            deleteTempPackageFiles();
2743
2744            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2745
2746            // Remove any shared userIDs that have no associated packages
2747            mSettings.pruneSharedUsersLPw();
2748            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2749            final int systemPackagesCount = mPackages.size();
2750            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2751                    + " ms, packageCount: " + systemPackagesCount
2752                    + " , timePerPackage: "
2753                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2754                    + " , cached: " + cachedSystemApps);
2755            if (mIsUpgrade && systemPackagesCount > 0) {
2756                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2757                        ((int) systemScanTime) / systemPackagesCount);
2758            }
2759            if (!mOnlyCore) {
2760                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2761                        SystemClock.uptimeMillis());
2762                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2763
2764                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2765                        | PackageParser.PARSE_FORWARD_LOCK,
2766                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2767
2768                // Remove disable package settings for updated system apps that were
2769                // removed via an OTA. If the update is no longer present, remove the
2770                // app completely. Otherwise, revoke their system privileges.
2771                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2772                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2773                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2774
2775                    final String msg;
2776                    if (deletedPkg == null) {
2777                        // should have found an update, but, we didn't; remove everything
2778                        msg = "Updated system package " + deletedAppName
2779                                + " no longer exists; removing its data";
2780                        // Actual deletion of code and data will be handled by later
2781                        // reconciliation step
2782                    } else {
2783                        // found an update; revoke system privileges
2784                        msg = "Updated system package + " + deletedAppName
2785                                + " no longer exists; revoking system privileges";
2786
2787                        // Don't do anything if a stub is removed from the system image. If
2788                        // we were to remove the uncompressed version from the /data partition,
2789                        // this is where it'd be done.
2790
2791                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2792                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2793                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2794                    }
2795                    logCriticalInfo(Log.WARN, msg);
2796                }
2797
2798                /*
2799                 * Make sure all system apps that we expected to appear on
2800                 * the userdata partition actually showed up. If they never
2801                 * appeared, crawl back and revive the system version.
2802                 */
2803                for (int i = 0; i < mExpectingBetter.size(); i++) {
2804                    final String packageName = mExpectingBetter.keyAt(i);
2805                    if (!mPackages.containsKey(packageName)) {
2806                        final File scanFile = mExpectingBetter.valueAt(i);
2807
2808                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2809                                + " but never showed up; reverting to system");
2810
2811                        int reparseFlags = mDefParseFlags;
2812                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2813                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2814                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2815                                    | PackageParser.PARSE_IS_PRIVILEGED;
2816                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2817                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2818                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2819                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2820                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2821                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2822                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2823                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2824                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2825                        } else {
2826                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2827                            continue;
2828                        }
2829
2830                        mSettings.enableSystemPackageLPw(packageName);
2831
2832                        try {
2833                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2834                        } catch (PackageManagerException e) {
2835                            Slog.e(TAG, "Failed to parse original system package: "
2836                                    + e.getMessage());
2837                        }
2838                    }
2839                }
2840
2841                // Uncompress and install any stubbed system applications.
2842                // This must be done last to ensure all stubs are replaced or disabled.
2843                decompressSystemApplications(stubSystemApps, scanFlags);
2844
2845                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2846                                - cachedSystemApps;
2847
2848                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2849                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2850                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2851                        + " ms, packageCount: " + dataPackagesCount
2852                        + " , timePerPackage: "
2853                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2854                        + " , cached: " + cachedNonSystemApps);
2855                if (mIsUpgrade && dataPackagesCount > 0) {
2856                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2857                            ((int) dataScanTime) / dataPackagesCount);
2858                }
2859            }
2860            mExpectingBetter.clear();
2861
2862            // Resolve the storage manager.
2863            mStorageManagerPackage = getStorageManagerPackageName();
2864
2865            // Resolve protected action filters. Only the setup wizard is allowed to
2866            // have a high priority filter for these actions.
2867            mSetupWizardPackage = getSetupWizardPackageName();
2868            if (mProtectedFilters.size() > 0) {
2869                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2870                    Slog.i(TAG, "No setup wizard;"
2871                        + " All protected intents capped to priority 0");
2872                }
2873                for (ActivityIntentInfo filter : mProtectedFilters) {
2874                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2875                        if (DEBUG_FILTERS) {
2876                            Slog.i(TAG, "Found setup wizard;"
2877                                + " allow priority " + filter.getPriority() + ";"
2878                                + " package: " + filter.activity.info.packageName
2879                                + " activity: " + filter.activity.className
2880                                + " priority: " + filter.getPriority());
2881                        }
2882                        // skip setup wizard; allow it to keep the high priority filter
2883                        continue;
2884                    }
2885                    if (DEBUG_FILTERS) {
2886                        Slog.i(TAG, "Protected action; cap priority to 0;"
2887                                + " package: " + filter.activity.info.packageName
2888                                + " activity: " + filter.activity.className
2889                                + " origPrio: " + filter.getPriority());
2890                    }
2891                    filter.setPriority(0);
2892                }
2893            }
2894            mDeferProtectedFilters = false;
2895            mProtectedFilters.clear();
2896
2897            // Now that we know all of the shared libraries, update all clients to have
2898            // the correct library paths.
2899            updateAllSharedLibrariesLPw(null);
2900
2901            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2902                // NOTE: We ignore potential failures here during a system scan (like
2903                // the rest of the commands above) because there's precious little we
2904                // can do about it. A settings error is reported, though.
2905                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2906            }
2907
2908            // Now that we know all the packages we are keeping,
2909            // read and update their last usage times.
2910            mPackageUsage.read(mPackages);
2911            mCompilerStats.read();
2912
2913            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2914                    SystemClock.uptimeMillis());
2915            Slog.i(TAG, "Time to scan packages: "
2916                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2917                    + " seconds");
2918
2919            // If the platform SDK has changed since the last time we booted,
2920            // we need to re-grant app permission to catch any new ones that
2921            // appear.  This is really a hack, and means that apps can in some
2922            // cases get permissions that the user didn't initially explicitly
2923            // allow...  it would be nice to have some better way to handle
2924            // this situation.
2925            int updateFlags = UPDATE_PERMISSIONS_ALL;
2926            if (ver.sdkVersion != mSdkVersion) {
2927                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2928                        + mSdkVersion + "; regranting permissions for internal storage");
2929                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2930            }
2931            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2932            ver.sdkVersion = mSdkVersion;
2933
2934            // If this is the first boot or an update from pre-M, and it is a normal
2935            // boot, then we need to initialize the default preferred apps across
2936            // all defined users.
2937            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2938                for (UserInfo user : sUserManager.getUsers(true)) {
2939                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2940                    applyFactoryDefaultBrowserLPw(user.id);
2941                    primeDomainVerificationsLPw(user.id);
2942                }
2943            }
2944
2945            // Prepare storage for system user really early during boot,
2946            // since core system apps like SettingsProvider and SystemUI
2947            // can't wait for user to start
2948            final int storageFlags;
2949            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2950                storageFlags = StorageManager.FLAG_STORAGE_DE;
2951            } else {
2952                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2953            }
2954            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2955                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2956                    true /* onlyCoreApps */);
2957            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2958                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2959                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2960                traceLog.traceBegin("AppDataFixup");
2961                try {
2962                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2963                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2964                } catch (InstallerException e) {
2965                    Slog.w(TAG, "Trouble fixing GIDs", e);
2966                }
2967                traceLog.traceEnd();
2968
2969                traceLog.traceBegin("AppDataPrepare");
2970                if (deferPackages == null || deferPackages.isEmpty()) {
2971                    return;
2972                }
2973                int count = 0;
2974                for (String pkgName : deferPackages) {
2975                    PackageParser.Package pkg = null;
2976                    synchronized (mPackages) {
2977                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2978                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2979                            pkg = ps.pkg;
2980                        }
2981                    }
2982                    if (pkg != null) {
2983                        synchronized (mInstallLock) {
2984                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2985                                    true /* maybeMigrateAppData */);
2986                        }
2987                        count++;
2988                    }
2989                }
2990                traceLog.traceEnd();
2991                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2992            }, "prepareAppData");
2993
2994            // If this is first boot after an OTA, and a normal boot, then
2995            // we need to clear code cache directories.
2996            // Note that we do *not* clear the application profiles. These remain valid
2997            // across OTAs and are used to drive profile verification (post OTA) and
2998            // profile compilation (without waiting to collect a fresh set of profiles).
2999            if (mIsUpgrade && !onlyCore) {
3000                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3001                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3002                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3003                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3004                        // No apps are running this early, so no need to freeze
3005                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3006                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3007                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3008                    }
3009                }
3010                ver.fingerprint = Build.FINGERPRINT;
3011            }
3012
3013            checkDefaultBrowser();
3014
3015            // clear only after permissions and other defaults have been updated
3016            mExistingSystemPackages.clear();
3017            mPromoteSystemApps = false;
3018
3019            // All the changes are done during package scanning.
3020            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3021
3022            // can downgrade to reader
3023            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3024            mSettings.writeLPr();
3025            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3026            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3027                    SystemClock.uptimeMillis());
3028
3029            if (!mOnlyCore) {
3030                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3031                mRequiredInstallerPackage = getRequiredInstallerLPr();
3032                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3033                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3034                if (mIntentFilterVerifierComponent != null) {
3035                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3036                            mIntentFilterVerifierComponent);
3037                } else {
3038                    mIntentFilterVerifier = null;
3039                }
3040                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3041                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3042                        SharedLibraryInfo.VERSION_UNDEFINED);
3043                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3044                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3045                        SharedLibraryInfo.VERSION_UNDEFINED);
3046            } else {
3047                mRequiredVerifierPackage = null;
3048                mRequiredInstallerPackage = null;
3049                mRequiredUninstallerPackage = null;
3050                mIntentFilterVerifierComponent = null;
3051                mIntentFilterVerifier = null;
3052                mServicesSystemSharedLibraryPackageName = null;
3053                mSharedSystemSharedLibraryPackageName = null;
3054            }
3055
3056            mInstallerService = new PackageInstallerService(context, this);
3057            final Pair<ComponentName, String> instantAppResolverComponent =
3058                    getInstantAppResolverLPr();
3059            if (instantAppResolverComponent != null) {
3060                if (DEBUG_EPHEMERAL) {
3061                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3062                }
3063                mInstantAppResolverConnection = new EphemeralResolverConnection(
3064                        mContext, instantAppResolverComponent.first,
3065                        instantAppResolverComponent.second);
3066                mInstantAppResolverSettingsComponent =
3067                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3068            } else {
3069                mInstantAppResolverConnection = null;
3070                mInstantAppResolverSettingsComponent = null;
3071            }
3072            updateInstantAppInstallerLocked(null);
3073
3074            // Read and update the usage of dex files.
3075            // Do this at the end of PM init so that all the packages have their
3076            // data directory reconciled.
3077            // At this point we know the code paths of the packages, so we can validate
3078            // the disk file and build the internal cache.
3079            // The usage file is expected to be small so loading and verifying it
3080            // should take a fairly small time compare to the other activities (e.g. package
3081            // scanning).
3082            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3083            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3084            for (int userId : currentUserIds) {
3085                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3086            }
3087            mDexManager.load(userPackages);
3088            if (mIsUpgrade) {
3089                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3090                        (int) (SystemClock.uptimeMillis() - startTime));
3091            }
3092        } // synchronized (mPackages)
3093        } // synchronized (mInstallLock)
3094
3095        // Now after opening every single application zip, make sure they
3096        // are all flushed.  Not really needed, but keeps things nice and
3097        // tidy.
3098        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3099        Runtime.getRuntime().gc();
3100        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3101
3102        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3103        FallbackCategoryProvider.loadFallbacks();
3104        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3105
3106        // The initial scanning above does many calls into installd while
3107        // holding the mPackages lock, but we're mostly interested in yelling
3108        // once we have a booted system.
3109        mInstaller.setWarnIfHeld(mPackages);
3110
3111        // Expose private service for system components to use.
3112        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3113        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3114    }
3115
3116    /**
3117     * Uncompress and install stub applications.
3118     * <p>In order to save space on the system partition, some applications are shipped in a
3119     * compressed form. In addition the compressed bits for the full application, the
3120     * system image contains a tiny stub comprised of only the Android manifest.
3121     * <p>During the first boot, attempt to uncompress and install the full application. If
3122     * the application can't be installed for any reason, disable the stub and prevent
3123     * uncompressing the full application during future boots.
3124     * <p>In order to forcefully attempt an installation of a full application, go to app
3125     * settings and enable the application.
3126     */
3127    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3128        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3129            final String pkgName = stubSystemApps.get(i);
3130            // skip if the system package is already disabled
3131            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3132                stubSystemApps.remove(i);
3133                continue;
3134            }
3135            // skip if the package isn't installed (?!); this should never happen
3136            final PackageParser.Package pkg = mPackages.get(pkgName);
3137            if (pkg == null) {
3138                stubSystemApps.remove(i);
3139                continue;
3140            }
3141            // skip if the package has been disabled by the user
3142            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3143            if (ps != null) {
3144                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3145                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3146                    stubSystemApps.remove(i);
3147                    continue;
3148                }
3149            }
3150
3151            if (DEBUG_COMPRESSION) {
3152                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3153            }
3154
3155            // uncompress the binary to its eventual destination on /data
3156            final File scanFile = decompressPackage(pkg);
3157            if (scanFile == null) {
3158                continue;
3159            }
3160
3161            // install the package to replace the stub on /system
3162            try {
3163                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3164                removePackageLI(pkg, true /*chatty*/);
3165                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3166                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3167                        UserHandle.USER_SYSTEM, "android");
3168                stubSystemApps.remove(i);
3169                continue;
3170            } catch (PackageManagerException e) {
3171                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3172            }
3173
3174            // any failed attempt to install the package will be cleaned up later
3175        }
3176
3177        // disable any stub still left; these failed to install the full application
3178        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3179            final String pkgName = stubSystemApps.get(i);
3180            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3181            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3182                    UserHandle.USER_SYSTEM, "android");
3183            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3184        }
3185    }
3186
3187    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3188        if (DEBUG_COMPRESSION) {
3189            Slog.i(TAG, "Decompress file"
3190                    + "; src: " + srcFile.getAbsolutePath()
3191                    + ", dst: " + dstFile.getAbsolutePath());
3192        }
3193        try (
3194                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3195                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3196        ) {
3197            Streams.copy(fileIn, fileOut);
3198            Os.chmod(dstFile.getAbsolutePath(), 0644);
3199            return PackageManager.INSTALL_SUCCEEDED;
3200        } catch (IOException e) {
3201            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3202                    + "; src: " + srcFile.getAbsolutePath()
3203                    + ", dst: " + dstFile.getAbsolutePath());
3204        }
3205        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3206    }
3207
3208    private File[] getCompressedFiles(String codePath) {
3209        final File stubCodePath = new File(codePath);
3210        final String stubName = stubCodePath.getName();
3211
3212        // The layout of a compressed package on a given partition is as follows :
3213        //
3214        // Compressed artifacts:
3215        //
3216        // /partition/ModuleName/foo.gz
3217        // /partation/ModuleName/bar.gz
3218        //
3219        // Stub artifact:
3220        //
3221        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3222        //
3223        // In other words, stub is on the same partition as the compressed artifacts
3224        // and in a directory that's suffixed with "-Stub".
3225        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3226        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3227            return null;
3228        }
3229
3230        final File stubParentDir = stubCodePath.getParentFile();
3231        if (stubParentDir == null) {
3232            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3233            return null;
3234        }
3235
3236        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3237        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3238            @Override
3239            public boolean accept(File dir, String name) {
3240                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3241            }
3242        });
3243
3244        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3245            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3246        }
3247
3248        return files;
3249    }
3250
3251    private boolean compressedFileExists(String codePath) {
3252        final File[] compressedFiles = getCompressedFiles(codePath);
3253        return compressedFiles != null && compressedFiles.length > 0;
3254    }
3255
3256    /**
3257     * Decompresses the given package on the system image onto
3258     * the /data partition.
3259     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3260     */
3261    private File decompressPackage(PackageParser.Package pkg) {
3262        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3263        if (compressedFiles == null || compressedFiles.length == 0) {
3264            if (DEBUG_COMPRESSION) {
3265                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3266            }
3267            return null;
3268        }
3269        final File dstCodePath =
3270                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3271        int ret = PackageManager.INSTALL_SUCCEEDED;
3272        try {
3273            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3274            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3275            for (File srcFile : compressedFiles) {
3276                final String srcFileName = srcFile.getName();
3277                final String dstFileName = srcFileName.substring(
3278                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3279                final File dstFile = new File(dstCodePath, dstFileName);
3280                ret = decompressFile(srcFile, dstFile);
3281                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3282                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3283                            + "; pkg: " + pkg.packageName
3284                            + ", file: " + dstFileName);
3285                    break;
3286                }
3287            }
3288        } catch (ErrnoException e) {
3289            logCriticalInfo(Log.ERROR, "Failed to decompress"
3290                    + "; pkg: " + pkg.packageName
3291                    + ", err: " + e.errno);
3292        }
3293        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3294            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3295            NativeLibraryHelper.Handle handle = null;
3296            try {
3297                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3298                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3299                        null /*abiOverride*/);
3300            } catch (IOException e) {
3301                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3302                        + "; pkg: " + pkg.packageName);
3303                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3304            } finally {
3305                IoUtils.closeQuietly(handle);
3306            }
3307        }
3308        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3309            if (dstCodePath == null || !dstCodePath.exists()) {
3310                return null;
3311            }
3312            removeCodePathLI(dstCodePath);
3313            return null;
3314        }
3315
3316        // If we have a profile for a compressed APK, copy it to the reference location.
3317        // Since the package is the stub one, remove the stub suffix to get the normal package and
3318        // APK name.
3319        File profileFile = new File(getPrebuildProfilePath(pkg).replace(STUB_SUFFIX, ""));
3320        if (profileFile.exists()) {
3321            try {
3322                // We could also do this lazily before calling dexopt in
3323                // PackageDexOptimizer to prevent this happening on first boot. The issue
3324                // is that we don't have a good way to say "do this only once".
3325                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
3326                        pkg.applicationInfo.uid, pkg.packageName)) {
3327                    Log.e(TAG, "decompressPackage failed to copy system profile!");
3328                }
3329            } catch (Exception e) {
3330                Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", e);
3331            }
3332        }
3333        return dstCodePath;
3334    }
3335
3336    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3337        // we're only interested in updating the installer appliction when 1) it's not
3338        // already set or 2) the modified package is the installer
3339        if (mInstantAppInstallerActivity != null
3340                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3341                        .equals(modifiedPackage)) {
3342            return;
3343        }
3344        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3345    }
3346
3347    private static File preparePackageParserCache(boolean isUpgrade) {
3348        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3349            return null;
3350        }
3351
3352        // Disable package parsing on eng builds to allow for faster incremental development.
3353        if (Build.IS_ENG) {
3354            return null;
3355        }
3356
3357        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3358            Slog.i(TAG, "Disabling package parser cache due to system property.");
3359            return null;
3360        }
3361
3362        // The base directory for the package parser cache lives under /data/system/.
3363        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3364                "package_cache");
3365        if (cacheBaseDir == null) {
3366            return null;
3367        }
3368
3369        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3370        // This also serves to "GC" unused entries when the package cache version changes (which
3371        // can only happen during upgrades).
3372        if (isUpgrade) {
3373            FileUtils.deleteContents(cacheBaseDir);
3374        }
3375
3376
3377        // Return the versioned package cache directory. This is something like
3378        // "/data/system/package_cache/1"
3379        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3380
3381        // The following is a workaround to aid development on non-numbered userdebug
3382        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3383        // the system partition is newer.
3384        //
3385        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3386        // that starts with "eng." to signify that this is an engineering build and not
3387        // destined for release.
3388        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3389            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3390
3391            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3392            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3393            // in general and should not be used for production changes. In this specific case,
3394            // we know that they will work.
3395            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3396            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3397                FileUtils.deleteContents(cacheBaseDir);
3398                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3399            }
3400        }
3401
3402        return cacheDir;
3403    }
3404
3405    @Override
3406    public boolean isFirstBoot() {
3407        // allow instant applications
3408        return mFirstBoot;
3409    }
3410
3411    @Override
3412    public boolean isOnlyCoreApps() {
3413        // allow instant applications
3414        return mOnlyCore;
3415    }
3416
3417    @Override
3418    public boolean isUpgrade() {
3419        // allow instant applications
3420        return mIsUpgrade;
3421    }
3422
3423    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3424        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3425
3426        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3427                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3428                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3429        if (matches.size() == 1) {
3430            return matches.get(0).getComponentInfo().packageName;
3431        } else if (matches.size() == 0) {
3432            Log.e(TAG, "There should probably be a verifier, but, none were found");
3433            return null;
3434        }
3435        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3436    }
3437
3438    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3439        synchronized (mPackages) {
3440            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3441            if (libraryEntry == null) {
3442                throw new IllegalStateException("Missing required shared library:" + name);
3443            }
3444            return libraryEntry.apk;
3445        }
3446    }
3447
3448    private @NonNull String getRequiredInstallerLPr() {
3449        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3450        intent.addCategory(Intent.CATEGORY_DEFAULT);
3451        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3452
3453        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3454                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3455                UserHandle.USER_SYSTEM);
3456        if (matches.size() == 1) {
3457            ResolveInfo resolveInfo = matches.get(0);
3458            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3459                throw new RuntimeException("The installer must be a privileged app");
3460            }
3461            return matches.get(0).getComponentInfo().packageName;
3462        } else {
3463            throw new RuntimeException("There must be exactly one installer; found " + matches);
3464        }
3465    }
3466
3467    private @NonNull String getRequiredUninstallerLPr() {
3468        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3469        intent.addCategory(Intent.CATEGORY_DEFAULT);
3470        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3471
3472        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3473                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3474                UserHandle.USER_SYSTEM);
3475        if (resolveInfo == null ||
3476                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3477            throw new RuntimeException("There must be exactly one uninstaller; found "
3478                    + resolveInfo);
3479        }
3480        return resolveInfo.getComponentInfo().packageName;
3481    }
3482
3483    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3484        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3485
3486        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3487                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3488                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3489        ResolveInfo best = null;
3490        final int N = matches.size();
3491        for (int i = 0; i < N; i++) {
3492            final ResolveInfo cur = matches.get(i);
3493            final String packageName = cur.getComponentInfo().packageName;
3494            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3495                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3496                continue;
3497            }
3498
3499            if (best == null || cur.priority > best.priority) {
3500                best = cur;
3501            }
3502        }
3503
3504        if (best != null) {
3505            return best.getComponentInfo().getComponentName();
3506        }
3507        Slog.w(TAG, "Intent filter verifier not found");
3508        return null;
3509    }
3510
3511    @Override
3512    public @Nullable ComponentName getInstantAppResolverComponent() {
3513        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3514            return null;
3515        }
3516        synchronized (mPackages) {
3517            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3518            if (instantAppResolver == null) {
3519                return null;
3520            }
3521            return instantAppResolver.first;
3522        }
3523    }
3524
3525    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3526        final String[] packageArray =
3527                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3528        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3529            if (DEBUG_EPHEMERAL) {
3530                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3531            }
3532            return null;
3533        }
3534
3535        final int callingUid = Binder.getCallingUid();
3536        final int resolveFlags =
3537                MATCH_DIRECT_BOOT_AWARE
3538                | MATCH_DIRECT_BOOT_UNAWARE
3539                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3540        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3541        final Intent resolverIntent = new Intent(actionName);
3542        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3543                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3544        // temporarily look for the old action
3545        if (resolvers.size() == 0) {
3546            if (DEBUG_EPHEMERAL) {
3547                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3548            }
3549            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3550            resolverIntent.setAction(actionName);
3551            resolvers = queryIntentServicesInternal(resolverIntent, null,
3552                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3553        }
3554        final int N = resolvers.size();
3555        if (N == 0) {
3556            if (DEBUG_EPHEMERAL) {
3557                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3558            }
3559            return null;
3560        }
3561
3562        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3563        for (int i = 0; i < N; i++) {
3564            final ResolveInfo info = resolvers.get(i);
3565
3566            if (info.serviceInfo == null) {
3567                continue;
3568            }
3569
3570            final String packageName = info.serviceInfo.packageName;
3571            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3572                if (DEBUG_EPHEMERAL) {
3573                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3574                            + " pkg: " + packageName + ", info:" + info);
3575                }
3576                continue;
3577            }
3578
3579            if (DEBUG_EPHEMERAL) {
3580                Slog.v(TAG, "Ephemeral resolver found;"
3581                        + " pkg: " + packageName + ", info:" + info);
3582            }
3583            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3584        }
3585        if (DEBUG_EPHEMERAL) {
3586            Slog.v(TAG, "Ephemeral resolver NOT found");
3587        }
3588        return null;
3589    }
3590
3591    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3592        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3593        intent.addCategory(Intent.CATEGORY_DEFAULT);
3594        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3595
3596        final int resolveFlags =
3597                MATCH_DIRECT_BOOT_AWARE
3598                | MATCH_DIRECT_BOOT_UNAWARE
3599                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3600        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3601                resolveFlags, UserHandle.USER_SYSTEM);
3602        // temporarily look for the old action
3603        if (matches.isEmpty()) {
3604            if (DEBUG_EPHEMERAL) {
3605                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3606            }
3607            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3608            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3609                    resolveFlags, UserHandle.USER_SYSTEM);
3610        }
3611        Iterator<ResolveInfo> iter = matches.iterator();
3612        while (iter.hasNext()) {
3613            final ResolveInfo rInfo = iter.next();
3614            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3615            if (ps != null) {
3616                final PermissionsState permissionsState = ps.getPermissionsState();
3617                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3618                    continue;
3619                }
3620            }
3621            iter.remove();
3622        }
3623        if (matches.size() == 0) {
3624            return null;
3625        } else if (matches.size() == 1) {
3626            return (ActivityInfo) matches.get(0).getComponentInfo();
3627        } else {
3628            throw new RuntimeException(
3629                    "There must be at most one ephemeral installer; found " + matches);
3630        }
3631    }
3632
3633    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3634            @NonNull ComponentName resolver) {
3635        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3636                .addCategory(Intent.CATEGORY_DEFAULT)
3637                .setPackage(resolver.getPackageName());
3638        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3639        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3640                UserHandle.USER_SYSTEM);
3641        // temporarily look for the old action
3642        if (matches.isEmpty()) {
3643            if (DEBUG_EPHEMERAL) {
3644                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3645            }
3646            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3647            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3648                    UserHandle.USER_SYSTEM);
3649        }
3650        if (matches.isEmpty()) {
3651            return null;
3652        }
3653        return matches.get(0).getComponentInfo().getComponentName();
3654    }
3655
3656    private void primeDomainVerificationsLPw(int userId) {
3657        if (DEBUG_DOMAIN_VERIFICATION) {
3658            Slog.d(TAG, "Priming domain verifications in user " + userId);
3659        }
3660
3661        SystemConfig systemConfig = SystemConfig.getInstance();
3662        ArraySet<String> packages = systemConfig.getLinkedApps();
3663
3664        for (String packageName : packages) {
3665            PackageParser.Package pkg = mPackages.get(packageName);
3666            if (pkg != null) {
3667                if (!pkg.isSystemApp()) {
3668                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3669                    continue;
3670                }
3671
3672                ArraySet<String> domains = null;
3673                for (PackageParser.Activity a : pkg.activities) {
3674                    for (ActivityIntentInfo filter : a.intents) {
3675                        if (hasValidDomains(filter)) {
3676                            if (domains == null) {
3677                                domains = new ArraySet<String>();
3678                            }
3679                            domains.addAll(filter.getHostsList());
3680                        }
3681                    }
3682                }
3683
3684                if (domains != null && domains.size() > 0) {
3685                    if (DEBUG_DOMAIN_VERIFICATION) {
3686                        Slog.v(TAG, "      + " + packageName);
3687                    }
3688                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3689                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3690                    // and then 'always' in the per-user state actually used for intent resolution.
3691                    final IntentFilterVerificationInfo ivi;
3692                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3693                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3694                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3695                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3696                } else {
3697                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3698                            + "' does not handle web links");
3699                }
3700            } else {
3701                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3702            }
3703        }
3704
3705        scheduleWritePackageRestrictionsLocked(userId);
3706        scheduleWriteSettingsLocked();
3707    }
3708
3709    private void applyFactoryDefaultBrowserLPw(int userId) {
3710        // The default browser app's package name is stored in a string resource,
3711        // with a product-specific overlay used for vendor customization.
3712        String browserPkg = mContext.getResources().getString(
3713                com.android.internal.R.string.default_browser);
3714        if (!TextUtils.isEmpty(browserPkg)) {
3715            // non-empty string => required to be a known package
3716            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3717            if (ps == null) {
3718                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3719                browserPkg = null;
3720            } else {
3721                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3722            }
3723        }
3724
3725        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3726        // default.  If there's more than one, just leave everything alone.
3727        if (browserPkg == null) {
3728            calculateDefaultBrowserLPw(userId);
3729        }
3730    }
3731
3732    private void calculateDefaultBrowserLPw(int userId) {
3733        List<String> allBrowsers = resolveAllBrowserApps(userId);
3734        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3735        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3736    }
3737
3738    private List<String> resolveAllBrowserApps(int userId) {
3739        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3740        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3741                PackageManager.MATCH_ALL, userId);
3742
3743        final int count = list.size();
3744        List<String> result = new ArrayList<String>(count);
3745        for (int i=0; i<count; i++) {
3746            ResolveInfo info = list.get(i);
3747            if (info.activityInfo == null
3748                    || !info.handleAllWebDataURI
3749                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3750                    || result.contains(info.activityInfo.packageName)) {
3751                continue;
3752            }
3753            result.add(info.activityInfo.packageName);
3754        }
3755
3756        return result;
3757    }
3758
3759    private boolean packageIsBrowser(String packageName, int userId) {
3760        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3761                PackageManager.MATCH_ALL, userId);
3762        final int N = list.size();
3763        for (int i = 0; i < N; i++) {
3764            ResolveInfo info = list.get(i);
3765            if (packageName.equals(info.activityInfo.packageName)) {
3766                return true;
3767            }
3768        }
3769        return false;
3770    }
3771
3772    private void checkDefaultBrowser() {
3773        final int myUserId = UserHandle.myUserId();
3774        final String packageName = getDefaultBrowserPackageName(myUserId);
3775        if (packageName != null) {
3776            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3777            if (info == null) {
3778                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3779                synchronized (mPackages) {
3780                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3781                }
3782            }
3783        }
3784    }
3785
3786    @Override
3787    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3788            throws RemoteException {
3789        try {
3790            return super.onTransact(code, data, reply, flags);
3791        } catch (RuntimeException e) {
3792            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3793                Slog.wtf(TAG, "Package Manager Crash", e);
3794            }
3795            throw e;
3796        }
3797    }
3798
3799    static int[] appendInts(int[] cur, int[] add) {
3800        if (add == null) return cur;
3801        if (cur == null) return add;
3802        final int N = add.length;
3803        for (int i=0; i<N; i++) {
3804            cur = appendInt(cur, add[i]);
3805        }
3806        return cur;
3807    }
3808
3809    /**
3810     * Returns whether or not a full application can see an instant application.
3811     * <p>
3812     * Currently, there are three cases in which this can occur:
3813     * <ol>
3814     * <li>The calling application is a "special" process. The special
3815     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3816     *     and {@code 0}</li>
3817     * <li>The calling application has the permission
3818     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3819     * <li>The calling application is the default launcher on the
3820     *     system partition.</li>
3821     * </ol>
3822     */
3823    private boolean canViewInstantApps(int callingUid, int userId) {
3824        if (callingUid == Process.SYSTEM_UID
3825                || callingUid == Process.SHELL_UID
3826                || callingUid == Process.ROOT_UID) {
3827            return true;
3828        }
3829        if (mContext.checkCallingOrSelfPermission(
3830                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3831            return true;
3832        }
3833        if (mContext.checkCallingOrSelfPermission(
3834                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3835            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3836            if (homeComponent != null
3837                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3838                return true;
3839            }
3840        }
3841        return false;
3842    }
3843
3844    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3845        if (!sUserManager.exists(userId)) return null;
3846        if (ps == null) {
3847            return null;
3848        }
3849        PackageParser.Package p = ps.pkg;
3850        if (p == null) {
3851            return null;
3852        }
3853        final int callingUid = Binder.getCallingUid();
3854        // Filter out ephemeral app metadata:
3855        //   * The system/shell/root can see metadata for any app
3856        //   * An installed app can see metadata for 1) other installed apps
3857        //     and 2) ephemeral apps that have explicitly interacted with it
3858        //   * Ephemeral apps can only see their own data and exposed installed apps
3859        //   * Holding a signature permission allows seeing instant apps
3860        if (filterAppAccessLPr(ps, callingUid, userId)) {
3861            return null;
3862        }
3863
3864        final PermissionsState permissionsState = ps.getPermissionsState();
3865
3866        // Compute GIDs only if requested
3867        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3868                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3869        // Compute granted permissions only if package has requested permissions
3870        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3871                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3872        final PackageUserState state = ps.readUserState(userId);
3873
3874        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3875                && ps.isSystem()) {
3876            flags |= MATCH_ANY_USER;
3877        }
3878
3879        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3880                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3881
3882        if (packageInfo == null) {
3883            return null;
3884        }
3885
3886        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3887                resolveExternalPackageNameLPr(p);
3888
3889        return packageInfo;
3890    }
3891
3892    @Override
3893    public void checkPackageStartable(String packageName, int userId) {
3894        final int callingUid = Binder.getCallingUid();
3895        if (getInstantAppPackageName(callingUid) != null) {
3896            throw new SecurityException("Instant applications don't have access to this method");
3897        }
3898        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3899        synchronized (mPackages) {
3900            final PackageSetting ps = mSettings.mPackages.get(packageName);
3901            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3902                throw new SecurityException("Package " + packageName + " was not found!");
3903            }
3904
3905            if (!ps.getInstalled(userId)) {
3906                throw new SecurityException(
3907                        "Package " + packageName + " was not installed for user " + userId + "!");
3908            }
3909
3910            if (mSafeMode && !ps.isSystem()) {
3911                throw new SecurityException("Package " + packageName + " not a system app!");
3912            }
3913
3914            if (mFrozenPackages.contains(packageName)) {
3915                throw new SecurityException("Package " + packageName + " is currently frozen!");
3916            }
3917
3918            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3919                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3920            }
3921        }
3922    }
3923
3924    @Override
3925    public boolean isPackageAvailable(String packageName, int userId) {
3926        if (!sUserManager.exists(userId)) return false;
3927        final int callingUid = Binder.getCallingUid();
3928        enforceCrossUserPermission(callingUid, userId,
3929                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3930        synchronized (mPackages) {
3931            PackageParser.Package p = mPackages.get(packageName);
3932            if (p != null) {
3933                final PackageSetting ps = (PackageSetting) p.mExtras;
3934                if (filterAppAccessLPr(ps, callingUid, userId)) {
3935                    return false;
3936                }
3937                if (ps != null) {
3938                    final PackageUserState state = ps.readUserState(userId);
3939                    if (state != null) {
3940                        return PackageParser.isAvailable(state);
3941                    }
3942                }
3943            }
3944        }
3945        return false;
3946    }
3947
3948    @Override
3949    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3950        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3951                flags, Binder.getCallingUid(), userId);
3952    }
3953
3954    @Override
3955    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3956            int flags, int userId) {
3957        return getPackageInfoInternal(versionedPackage.getPackageName(),
3958                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3959    }
3960
3961    /**
3962     * Important: The provided filterCallingUid is used exclusively to filter out packages
3963     * that can be seen based on user state. It's typically the original caller uid prior
3964     * to clearing. Because it can only be provided by trusted code, it's value can be
3965     * trusted and will be used as-is; unlike userId which will be validated by this method.
3966     */
3967    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3968            int flags, int filterCallingUid, int userId) {
3969        if (!sUserManager.exists(userId)) return null;
3970        flags = updateFlagsForPackage(flags, userId, packageName);
3971        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3972                false /* requireFullPermission */, false /* checkShell */, "get package info");
3973
3974        // reader
3975        synchronized (mPackages) {
3976            // Normalize package name to handle renamed packages and static libs
3977            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3978
3979            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3980            if (matchFactoryOnly) {
3981                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3982                if (ps != null) {
3983                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3984                        return null;
3985                    }
3986                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3987                        return null;
3988                    }
3989                    return generatePackageInfo(ps, flags, userId);
3990                }
3991            }
3992
3993            PackageParser.Package p = mPackages.get(packageName);
3994            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3995                return null;
3996            }
3997            if (DEBUG_PACKAGE_INFO)
3998                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3999            if (p != null) {
4000                final PackageSetting ps = (PackageSetting) p.mExtras;
4001                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4002                    return null;
4003                }
4004                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4005                    return null;
4006                }
4007                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4008            }
4009            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4010                final PackageSetting ps = mSettings.mPackages.get(packageName);
4011                if (ps == null) return null;
4012                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4013                    return null;
4014                }
4015                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4016                    return null;
4017                }
4018                return generatePackageInfo(ps, flags, userId);
4019            }
4020        }
4021        return null;
4022    }
4023
4024    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4025        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4026            return true;
4027        }
4028        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4029            return true;
4030        }
4031        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4032            return true;
4033        }
4034        return false;
4035    }
4036
4037    private boolean isComponentVisibleToInstantApp(
4038            @Nullable ComponentName component, @ComponentType int type) {
4039        if (type == TYPE_ACTIVITY) {
4040            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4041            return activity != null
4042                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4043                    : false;
4044        } else if (type == TYPE_RECEIVER) {
4045            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4046            return activity != null
4047                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4048                    : false;
4049        } else if (type == TYPE_SERVICE) {
4050            final PackageParser.Service service = mServices.mServices.get(component);
4051            return service != null
4052                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4053                    : false;
4054        } else if (type == TYPE_PROVIDER) {
4055            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4056            return provider != null
4057                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4058                    : false;
4059        } else if (type == TYPE_UNKNOWN) {
4060            return isComponentVisibleToInstantApp(component);
4061        }
4062        return false;
4063    }
4064
4065    /**
4066     * Returns whether or not access to the application should be filtered.
4067     * <p>
4068     * Access may be limited based upon whether the calling or target applications
4069     * are instant applications.
4070     *
4071     * @see #canAccessInstantApps(int)
4072     */
4073    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4074            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4075        // if we're in an isolated process, get the real calling UID
4076        if (Process.isIsolated(callingUid)) {
4077            callingUid = mIsolatedOwners.get(callingUid);
4078        }
4079        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4080        final boolean callerIsInstantApp = instantAppPkgName != null;
4081        if (ps == null) {
4082            if (callerIsInstantApp) {
4083                // pretend the application exists, but, needs to be filtered
4084                return true;
4085            }
4086            return false;
4087        }
4088        // if the target and caller are the same application, don't filter
4089        if (isCallerSameApp(ps.name, callingUid)) {
4090            return false;
4091        }
4092        if (callerIsInstantApp) {
4093            // request for a specific component; if it hasn't been explicitly exposed, filter
4094            if (component != null) {
4095                return !isComponentVisibleToInstantApp(component, componentType);
4096            }
4097            // request for application; if no components have been explicitly exposed, filter
4098            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4099        }
4100        if (ps.getInstantApp(userId)) {
4101            // caller can see all components of all instant applications, don't filter
4102            if (canViewInstantApps(callingUid, userId)) {
4103                return false;
4104            }
4105            // request for a specific instant application component, filter
4106            if (component != null) {
4107                return true;
4108            }
4109            // request for an instant application; if the caller hasn't been granted access, filter
4110            return !mInstantAppRegistry.isInstantAccessGranted(
4111                    userId, UserHandle.getAppId(callingUid), ps.appId);
4112        }
4113        return false;
4114    }
4115
4116    /**
4117     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4118     */
4119    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4120        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4121    }
4122
4123    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4124            int flags) {
4125        // Callers can access only the libs they depend on, otherwise they need to explicitly
4126        // ask for the shared libraries given the caller is allowed to access all static libs.
4127        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4128            // System/shell/root get to see all static libs
4129            final int appId = UserHandle.getAppId(uid);
4130            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4131                    || appId == Process.ROOT_UID) {
4132                return false;
4133            }
4134        }
4135
4136        // No package means no static lib as it is always on internal storage
4137        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4138            return false;
4139        }
4140
4141        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4142                ps.pkg.staticSharedLibVersion);
4143        if (libEntry == null) {
4144            return false;
4145        }
4146
4147        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4148        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4149        if (uidPackageNames == null) {
4150            return true;
4151        }
4152
4153        for (String uidPackageName : uidPackageNames) {
4154            if (ps.name.equals(uidPackageName)) {
4155                return false;
4156            }
4157            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4158            if (uidPs != null) {
4159                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4160                        libEntry.info.getName());
4161                if (index < 0) {
4162                    continue;
4163                }
4164                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4165                    return false;
4166                }
4167            }
4168        }
4169        return true;
4170    }
4171
4172    @Override
4173    public String[] currentToCanonicalPackageNames(String[] names) {
4174        final int callingUid = Binder.getCallingUid();
4175        if (getInstantAppPackageName(callingUid) != null) {
4176            return names;
4177        }
4178        final String[] out = new String[names.length];
4179        // reader
4180        synchronized (mPackages) {
4181            final int callingUserId = UserHandle.getUserId(callingUid);
4182            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4183            for (int i=names.length-1; i>=0; i--) {
4184                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4185                boolean translateName = false;
4186                if (ps != null && ps.realName != null) {
4187                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4188                    translateName = !targetIsInstantApp
4189                            || canViewInstantApps
4190                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4191                                    UserHandle.getAppId(callingUid), ps.appId);
4192                }
4193                out[i] = translateName ? ps.realName : names[i];
4194            }
4195        }
4196        return out;
4197    }
4198
4199    @Override
4200    public String[] canonicalToCurrentPackageNames(String[] names) {
4201        final int callingUid = Binder.getCallingUid();
4202        if (getInstantAppPackageName(callingUid) != null) {
4203            return names;
4204        }
4205        final String[] out = new String[names.length];
4206        // reader
4207        synchronized (mPackages) {
4208            final int callingUserId = UserHandle.getUserId(callingUid);
4209            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4210            for (int i=names.length-1; i>=0; i--) {
4211                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4212                boolean translateName = false;
4213                if (cur != null) {
4214                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4215                    final boolean targetIsInstantApp =
4216                            ps != null && ps.getInstantApp(callingUserId);
4217                    translateName = !targetIsInstantApp
4218                            || canViewInstantApps
4219                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4220                                    UserHandle.getAppId(callingUid), ps.appId);
4221                }
4222                out[i] = translateName ? cur : names[i];
4223            }
4224        }
4225        return out;
4226    }
4227
4228    @Override
4229    public int getPackageUid(String packageName, int flags, int userId) {
4230        if (!sUserManager.exists(userId)) return -1;
4231        final int callingUid = Binder.getCallingUid();
4232        flags = updateFlagsForPackage(flags, userId, packageName);
4233        enforceCrossUserPermission(callingUid, userId,
4234                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4235
4236        // reader
4237        synchronized (mPackages) {
4238            final PackageParser.Package p = mPackages.get(packageName);
4239            if (p != null && p.isMatch(flags)) {
4240                PackageSetting ps = (PackageSetting) p.mExtras;
4241                if (filterAppAccessLPr(ps, callingUid, userId)) {
4242                    return -1;
4243                }
4244                return UserHandle.getUid(userId, p.applicationInfo.uid);
4245            }
4246            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4247                final PackageSetting ps = mSettings.mPackages.get(packageName);
4248                if (ps != null && ps.isMatch(flags)
4249                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4250                    return UserHandle.getUid(userId, ps.appId);
4251                }
4252            }
4253        }
4254
4255        return -1;
4256    }
4257
4258    @Override
4259    public int[] getPackageGids(String packageName, int flags, int userId) {
4260        if (!sUserManager.exists(userId)) return null;
4261        final int callingUid = Binder.getCallingUid();
4262        flags = updateFlagsForPackage(flags, userId, packageName);
4263        enforceCrossUserPermission(callingUid, userId,
4264                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4265
4266        // reader
4267        synchronized (mPackages) {
4268            final PackageParser.Package p = mPackages.get(packageName);
4269            if (p != null && p.isMatch(flags)) {
4270                PackageSetting ps = (PackageSetting) p.mExtras;
4271                if (filterAppAccessLPr(ps, callingUid, userId)) {
4272                    return null;
4273                }
4274                // TODO: Shouldn't this be checking for package installed state for userId and
4275                // return null?
4276                return ps.getPermissionsState().computeGids(userId);
4277            }
4278            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4279                final PackageSetting ps = mSettings.mPackages.get(packageName);
4280                if (ps != null && ps.isMatch(flags)
4281                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4282                    return ps.getPermissionsState().computeGids(userId);
4283                }
4284            }
4285        }
4286
4287        return null;
4288    }
4289
4290    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4291        if (bp.perm != null) {
4292            return PackageParser.generatePermissionInfo(bp.perm, flags);
4293        }
4294        PermissionInfo pi = new PermissionInfo();
4295        pi.name = bp.name;
4296        pi.packageName = bp.sourcePackage;
4297        pi.nonLocalizedLabel = bp.name;
4298        pi.protectionLevel = bp.protectionLevel;
4299        return pi;
4300    }
4301
4302    @Override
4303    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4304        final int callingUid = Binder.getCallingUid();
4305        if (getInstantAppPackageName(callingUid) != null) {
4306            return null;
4307        }
4308        // reader
4309        synchronized (mPackages) {
4310            final BasePermission p = mSettings.mPermissions.get(name);
4311            if (p == null) {
4312                return null;
4313            }
4314            // If the caller is an app that targets pre 26 SDK drop protection flags.
4315            PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4316            if (permissionInfo != null) {
4317                final int protectionLevel = adjustPermissionProtectionFlagsLPr(
4318                        permissionInfo.protectionLevel, packageName, callingUid);
4319                if (permissionInfo.protectionLevel != protectionLevel) {
4320                    // If we return different protection level, don't use the cached info
4321                    if (p.perm != null && p.perm.info == permissionInfo) {
4322                        permissionInfo = new PermissionInfo(permissionInfo);
4323                    }
4324                    permissionInfo.protectionLevel = protectionLevel;
4325                }
4326            }
4327            return permissionInfo;
4328        }
4329    }
4330
4331    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4332            String packageName, int uid) {
4333        // Signature permission flags area always reported
4334        final int protectionLevelMasked = protectionLevel
4335                & (PermissionInfo.PROTECTION_NORMAL
4336                | PermissionInfo.PROTECTION_DANGEROUS
4337                | PermissionInfo.PROTECTION_SIGNATURE);
4338        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4339            return protectionLevel;
4340        }
4341
4342        // System sees all flags.
4343        final int appId = UserHandle.getAppId(uid);
4344        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4345                || appId == Process.SHELL_UID) {
4346            return protectionLevel;
4347        }
4348
4349        // Normalize package name to handle renamed packages and static libs
4350        packageName = resolveInternalPackageNameLPr(packageName,
4351                PackageManager.VERSION_CODE_HIGHEST);
4352
4353        // Apps that target O see flags for all protection levels.
4354        final PackageSetting ps = mSettings.mPackages.get(packageName);
4355        if (ps == null) {
4356            return protectionLevel;
4357        }
4358        if (ps.appId != appId) {
4359            return protectionLevel;
4360        }
4361
4362        final PackageParser.Package pkg = mPackages.get(packageName);
4363        if (pkg == null) {
4364            return protectionLevel;
4365        }
4366        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4367            return protectionLevelMasked;
4368        }
4369
4370        return protectionLevel;
4371    }
4372
4373    @Override
4374    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4375            int flags) {
4376        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4377            return null;
4378        }
4379        // reader
4380        synchronized (mPackages) {
4381            if (group != null && !mPermissionGroups.containsKey(group)) {
4382                // This is thrown as NameNotFoundException
4383                return null;
4384            }
4385
4386            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4387            for (BasePermission p : mSettings.mPermissions.values()) {
4388                if (group == null) {
4389                    if (p.perm == null || p.perm.info.group == null) {
4390                        out.add(generatePermissionInfo(p, flags));
4391                    }
4392                } else {
4393                    if (p.perm != null && group.equals(p.perm.info.group)) {
4394                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4395                    }
4396                }
4397            }
4398            return new ParceledListSlice<>(out);
4399        }
4400    }
4401
4402    @Override
4403    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4404        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4405            return null;
4406        }
4407        // reader
4408        synchronized (mPackages) {
4409            return PackageParser.generatePermissionGroupInfo(
4410                    mPermissionGroups.get(name), flags);
4411        }
4412    }
4413
4414    @Override
4415    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4416        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4417            return ParceledListSlice.emptyList();
4418        }
4419        // reader
4420        synchronized (mPackages) {
4421            final int N = mPermissionGroups.size();
4422            ArrayList<PermissionGroupInfo> out
4423                    = new ArrayList<PermissionGroupInfo>(N);
4424            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4425                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4426            }
4427            return new ParceledListSlice<>(out);
4428        }
4429    }
4430
4431    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4432            int filterCallingUid, int userId) {
4433        if (!sUserManager.exists(userId)) return null;
4434        PackageSetting ps = mSettings.mPackages.get(packageName);
4435        if (ps != null) {
4436            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4437                return null;
4438            }
4439            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4440                return null;
4441            }
4442            if (ps.pkg == null) {
4443                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4444                if (pInfo != null) {
4445                    return pInfo.applicationInfo;
4446                }
4447                return null;
4448            }
4449            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4450                    ps.readUserState(userId), userId);
4451            if (ai != null) {
4452                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4453            }
4454            return ai;
4455        }
4456        return null;
4457    }
4458
4459    @Override
4460    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4461        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4462    }
4463
4464    /**
4465     * Important: The provided filterCallingUid is used exclusively to filter out applications
4466     * that can be seen based on user state. It's typically the original caller uid prior
4467     * to clearing. Because it can only be provided by trusted code, it's value can be
4468     * trusted and will be used as-is; unlike userId which will be validated by this method.
4469     */
4470    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4471            int filterCallingUid, int userId) {
4472        if (!sUserManager.exists(userId)) return null;
4473        flags = updateFlagsForApplication(flags, userId, packageName);
4474        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4475                false /* requireFullPermission */, false /* checkShell */, "get application info");
4476
4477        // writer
4478        synchronized (mPackages) {
4479            // Normalize package name to handle renamed packages and static libs
4480            packageName = resolveInternalPackageNameLPr(packageName,
4481                    PackageManager.VERSION_CODE_HIGHEST);
4482
4483            PackageParser.Package p = mPackages.get(packageName);
4484            if (DEBUG_PACKAGE_INFO) Log.v(
4485                    TAG, "getApplicationInfo " + packageName
4486                    + ": " + p);
4487            if (p != null) {
4488                PackageSetting ps = mSettings.mPackages.get(packageName);
4489                if (ps == null) return null;
4490                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4491                    return null;
4492                }
4493                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4494                    return null;
4495                }
4496                // Note: isEnabledLP() does not apply here - always return info
4497                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4498                        p, flags, ps.readUserState(userId), userId);
4499                if (ai != null) {
4500                    ai.packageName = resolveExternalPackageNameLPr(p);
4501                }
4502                return ai;
4503            }
4504            if ("android".equals(packageName)||"system".equals(packageName)) {
4505                return mAndroidApplication;
4506            }
4507            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4508                // Already generates the external package name
4509                return generateApplicationInfoFromSettingsLPw(packageName,
4510                        flags, filterCallingUid, userId);
4511            }
4512        }
4513        return null;
4514    }
4515
4516    private String normalizePackageNameLPr(String packageName) {
4517        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4518        return normalizedPackageName != null ? normalizedPackageName : packageName;
4519    }
4520
4521    @Override
4522    public void deletePreloadsFileCache() {
4523        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4524            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4525        }
4526        File dir = Environment.getDataPreloadsFileCacheDirectory();
4527        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4528        FileUtils.deleteContents(dir);
4529    }
4530
4531    @Override
4532    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4533            final int storageFlags, final IPackageDataObserver observer) {
4534        mContext.enforceCallingOrSelfPermission(
4535                android.Manifest.permission.CLEAR_APP_CACHE, null);
4536        mHandler.post(() -> {
4537            boolean success = false;
4538            try {
4539                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4540                success = true;
4541            } catch (IOException e) {
4542                Slog.w(TAG, e);
4543            }
4544            if (observer != null) {
4545                try {
4546                    observer.onRemoveCompleted(null, success);
4547                } catch (RemoteException e) {
4548                    Slog.w(TAG, e);
4549                }
4550            }
4551        });
4552    }
4553
4554    @Override
4555    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4556            final int storageFlags, final IntentSender pi) {
4557        mContext.enforceCallingOrSelfPermission(
4558                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4559        mHandler.post(() -> {
4560            boolean success = false;
4561            try {
4562                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4563                success = true;
4564            } catch (IOException e) {
4565                Slog.w(TAG, e);
4566            }
4567            if (pi != null) {
4568                try {
4569                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4570                } catch (SendIntentException e) {
4571                    Slog.w(TAG, e);
4572                }
4573            }
4574        });
4575    }
4576
4577    /**
4578     * Blocking call to clear various types of cached data across the system
4579     * until the requested bytes are available.
4580     */
4581    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4582        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4583        final File file = storage.findPathForUuid(volumeUuid);
4584        if (file.getUsableSpace() >= bytes) return;
4585
4586        if (ENABLE_FREE_CACHE_V2) {
4587            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4588                    volumeUuid);
4589            final boolean aggressive = (storageFlags
4590                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4591            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4592
4593            // 1. Pre-flight to determine if we have any chance to succeed
4594            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4595            if (internalVolume && (aggressive || SystemProperties
4596                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4597                deletePreloadsFileCache();
4598                if (file.getUsableSpace() >= bytes) return;
4599            }
4600
4601            // 3. Consider parsed APK data (aggressive only)
4602            if (internalVolume && aggressive) {
4603                FileUtils.deleteContents(mCacheDir);
4604                if (file.getUsableSpace() >= bytes) return;
4605            }
4606
4607            // 4. Consider cached app data (above quotas)
4608            try {
4609                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4610                        Installer.FLAG_FREE_CACHE_V2);
4611            } catch (InstallerException ignored) {
4612            }
4613            if (file.getUsableSpace() >= bytes) return;
4614
4615            // 5. Consider shared libraries with refcount=0 and age>min cache period
4616            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4617                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4618                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4619                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4620                return;
4621            }
4622
4623            // 6. Consider dexopt output (aggressive only)
4624            // TODO: Implement
4625
4626            // 7. Consider installed instant apps unused longer than min cache period
4627            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4628                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4629                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4630                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4631                return;
4632            }
4633
4634            // 8. Consider cached app data (below quotas)
4635            try {
4636                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4637                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4638            } catch (InstallerException ignored) {
4639            }
4640            if (file.getUsableSpace() >= bytes) return;
4641
4642            // 9. Consider DropBox entries
4643            // TODO: Implement
4644
4645            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4646            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4647                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4648                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4649                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4650                return;
4651            }
4652        } else {
4653            try {
4654                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4655            } catch (InstallerException ignored) {
4656            }
4657            if (file.getUsableSpace() >= bytes) return;
4658        }
4659
4660        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4661    }
4662
4663    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4664            throws IOException {
4665        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4666        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4667
4668        List<VersionedPackage> packagesToDelete = null;
4669        final long now = System.currentTimeMillis();
4670
4671        synchronized (mPackages) {
4672            final int[] allUsers = sUserManager.getUserIds();
4673            final int libCount = mSharedLibraries.size();
4674            for (int i = 0; i < libCount; i++) {
4675                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4676                if (versionedLib == null) {
4677                    continue;
4678                }
4679                final int versionCount = versionedLib.size();
4680                for (int j = 0; j < versionCount; j++) {
4681                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4682                    // Skip packages that are not static shared libs.
4683                    if (!libInfo.isStatic()) {
4684                        break;
4685                    }
4686                    // Important: We skip static shared libs used for some user since
4687                    // in such a case we need to keep the APK on the device. The check for
4688                    // a lib being used for any user is performed by the uninstall call.
4689                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4690                    // Resolve the package name - we use synthetic package names internally
4691                    final String internalPackageName = resolveInternalPackageNameLPr(
4692                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4693                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4694                    // Skip unused static shared libs cached less than the min period
4695                    // to prevent pruning a lib needed by a subsequently installed package.
4696                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4697                        continue;
4698                    }
4699                    if (packagesToDelete == null) {
4700                        packagesToDelete = new ArrayList<>();
4701                    }
4702                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4703                            declaringPackage.getVersionCode()));
4704                }
4705            }
4706        }
4707
4708        if (packagesToDelete != null) {
4709            final int packageCount = packagesToDelete.size();
4710            for (int i = 0; i < packageCount; i++) {
4711                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4712                // Delete the package synchronously (will fail of the lib used for any user).
4713                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4714                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4715                                == PackageManager.DELETE_SUCCEEDED) {
4716                    if (volume.getUsableSpace() >= neededSpace) {
4717                        return true;
4718                    }
4719                }
4720            }
4721        }
4722
4723        return false;
4724    }
4725
4726    /**
4727     * Update given flags based on encryption status of current user.
4728     */
4729    private int updateFlags(int flags, int userId) {
4730        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4731                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4732            // Caller expressed an explicit opinion about what encryption
4733            // aware/unaware components they want to see, so fall through and
4734            // give them what they want
4735        } else {
4736            // Caller expressed no opinion, so match based on user state
4737            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4738                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4739            } else {
4740                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4741            }
4742        }
4743        return flags;
4744    }
4745
4746    private UserManagerInternal getUserManagerInternal() {
4747        if (mUserManagerInternal == null) {
4748            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4749        }
4750        return mUserManagerInternal;
4751    }
4752
4753    private DeviceIdleController.LocalService getDeviceIdleController() {
4754        if (mDeviceIdleController == null) {
4755            mDeviceIdleController =
4756                    LocalServices.getService(DeviceIdleController.LocalService.class);
4757        }
4758        return mDeviceIdleController;
4759    }
4760
4761    /**
4762     * Update given flags when being used to request {@link PackageInfo}.
4763     */
4764    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4765        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4766        boolean triaged = true;
4767        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4768                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4769            // Caller is asking for component details, so they'd better be
4770            // asking for specific encryption matching behavior, or be triaged
4771            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4772                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4773                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4774                triaged = false;
4775            }
4776        }
4777        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4778                | PackageManager.MATCH_SYSTEM_ONLY
4779                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4780            triaged = false;
4781        }
4782        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4783            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4784                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4785                    + Debug.getCallers(5));
4786        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4787                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4788            // If the caller wants all packages and has a restricted profile associated with it,
4789            // then match all users. This is to make sure that launchers that need to access work
4790            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4791            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4792            flags |= PackageManager.MATCH_ANY_USER;
4793        }
4794        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4795            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4796                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4797        }
4798        return updateFlags(flags, userId);
4799    }
4800
4801    /**
4802     * Update given flags when being used to request {@link ApplicationInfo}.
4803     */
4804    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4805        return updateFlagsForPackage(flags, userId, cookie);
4806    }
4807
4808    /**
4809     * Update given flags when being used to request {@link ComponentInfo}.
4810     */
4811    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4812        if (cookie instanceof Intent) {
4813            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4814                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4815            }
4816        }
4817
4818        boolean triaged = true;
4819        // Caller is asking for component details, so they'd better be
4820        // asking for specific encryption matching behavior, or be triaged
4821        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4822                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4823                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4824            triaged = false;
4825        }
4826        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4827            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4828                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4829        }
4830
4831        return updateFlags(flags, userId);
4832    }
4833
4834    /**
4835     * Update given intent when being used to request {@link ResolveInfo}.
4836     */
4837    private Intent updateIntentForResolve(Intent intent) {
4838        if (intent.getSelector() != null) {
4839            intent = intent.getSelector();
4840        }
4841        if (DEBUG_PREFERRED) {
4842            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4843        }
4844        return intent;
4845    }
4846
4847    /**
4848     * Update given flags when being used to request {@link ResolveInfo}.
4849     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4850     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4851     * flag set. However, this flag is only honoured in three circumstances:
4852     * <ul>
4853     * <li>when called from a system process</li>
4854     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4855     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4856     * action and a {@code android.intent.category.BROWSABLE} category</li>
4857     * </ul>
4858     */
4859    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4860        return updateFlagsForResolve(flags, userId, intent, callingUid,
4861                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4862    }
4863    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4864            boolean wantInstantApps) {
4865        return updateFlagsForResolve(flags, userId, intent, callingUid,
4866                wantInstantApps, false /*onlyExposedExplicitly*/);
4867    }
4868    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4869            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4870        // Safe mode means we shouldn't match any third-party components
4871        if (mSafeMode) {
4872            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4873        }
4874        if (getInstantAppPackageName(callingUid) != null) {
4875            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4876            if (onlyExposedExplicitly) {
4877                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4878            }
4879            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4880            flags |= PackageManager.MATCH_INSTANT;
4881        } else {
4882            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4883            final boolean allowMatchInstant =
4884                    (wantInstantApps
4885                            && Intent.ACTION_VIEW.equals(intent.getAction())
4886                            && hasWebURI(intent))
4887                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4888            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4889                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4890            if (!allowMatchInstant) {
4891                flags &= ~PackageManager.MATCH_INSTANT;
4892            }
4893        }
4894        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4895    }
4896
4897    @Override
4898    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4899        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4900    }
4901
4902    /**
4903     * Important: The provided filterCallingUid is used exclusively to filter out activities
4904     * that can be seen based on user state. It's typically the original caller uid prior
4905     * to clearing. Because it can only be provided by trusted code, it's value can be
4906     * trusted and will be used as-is; unlike userId which will be validated by this method.
4907     */
4908    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4909            int filterCallingUid, int userId) {
4910        if (!sUserManager.exists(userId)) return null;
4911        flags = updateFlagsForComponent(flags, userId, component);
4912        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4913                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4914        synchronized (mPackages) {
4915            PackageParser.Activity a = mActivities.mActivities.get(component);
4916
4917            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4918            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4919                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4920                if (ps == null) return null;
4921                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4922                    return null;
4923                }
4924                return PackageParser.generateActivityInfo(
4925                        a, flags, ps.readUserState(userId), userId);
4926            }
4927            if (mResolveComponentName.equals(component)) {
4928                return PackageParser.generateActivityInfo(
4929                        mResolveActivity, flags, new PackageUserState(), userId);
4930            }
4931        }
4932        return null;
4933    }
4934
4935    @Override
4936    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4937            String resolvedType) {
4938        synchronized (mPackages) {
4939            if (component.equals(mResolveComponentName)) {
4940                // The resolver supports EVERYTHING!
4941                return true;
4942            }
4943            final int callingUid = Binder.getCallingUid();
4944            final int callingUserId = UserHandle.getUserId(callingUid);
4945            PackageParser.Activity a = mActivities.mActivities.get(component);
4946            if (a == null) {
4947                return false;
4948            }
4949            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4950            if (ps == null) {
4951                return false;
4952            }
4953            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4954                return false;
4955            }
4956            for (int i=0; i<a.intents.size(); i++) {
4957                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4958                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4959                    return true;
4960                }
4961            }
4962            return false;
4963        }
4964    }
4965
4966    @Override
4967    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4968        if (!sUserManager.exists(userId)) return null;
4969        final int callingUid = Binder.getCallingUid();
4970        flags = updateFlagsForComponent(flags, userId, component);
4971        enforceCrossUserPermission(callingUid, userId,
4972                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4973        synchronized (mPackages) {
4974            PackageParser.Activity a = mReceivers.mActivities.get(component);
4975            if (DEBUG_PACKAGE_INFO) Log.v(
4976                TAG, "getReceiverInfo " + component + ": " + a);
4977            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4978                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4979                if (ps == null) return null;
4980                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4981                    return null;
4982                }
4983                return PackageParser.generateActivityInfo(
4984                        a, flags, ps.readUserState(userId), userId);
4985            }
4986        }
4987        return null;
4988    }
4989
4990    @Override
4991    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4992            int flags, int userId) {
4993        if (!sUserManager.exists(userId)) return null;
4994        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4995        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4996            return null;
4997        }
4998
4999        flags = updateFlagsForPackage(flags, userId, null);
5000
5001        final boolean canSeeStaticLibraries =
5002                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
5003                        == PERMISSION_GRANTED
5004                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
5005                        == PERMISSION_GRANTED
5006                || canRequestPackageInstallsInternal(packageName,
5007                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
5008                        false  /* throwIfPermNotDeclared*/)
5009                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
5010                        == PERMISSION_GRANTED;
5011
5012        synchronized (mPackages) {
5013            List<SharedLibraryInfo> result = null;
5014
5015            final int libCount = mSharedLibraries.size();
5016            for (int i = 0; i < libCount; i++) {
5017                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5018                if (versionedLib == null) {
5019                    continue;
5020                }
5021
5022                final int versionCount = versionedLib.size();
5023                for (int j = 0; j < versionCount; j++) {
5024                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5025                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5026                        break;
5027                    }
5028                    final long identity = Binder.clearCallingIdentity();
5029                    try {
5030                        PackageInfo packageInfo = getPackageInfoVersioned(
5031                                libInfo.getDeclaringPackage(), flags
5032                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5033                        if (packageInfo == null) {
5034                            continue;
5035                        }
5036                    } finally {
5037                        Binder.restoreCallingIdentity(identity);
5038                    }
5039
5040                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5041                            libInfo.getVersion(), libInfo.getType(),
5042                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5043                            flags, userId));
5044
5045                    if (result == null) {
5046                        result = new ArrayList<>();
5047                    }
5048                    result.add(resLibInfo);
5049                }
5050            }
5051
5052            return result != null ? new ParceledListSlice<>(result) : null;
5053        }
5054    }
5055
5056    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5057            SharedLibraryInfo libInfo, int flags, int userId) {
5058        List<VersionedPackage> versionedPackages = null;
5059        final int packageCount = mSettings.mPackages.size();
5060        for (int i = 0; i < packageCount; i++) {
5061            PackageSetting ps = mSettings.mPackages.valueAt(i);
5062
5063            if (ps == null) {
5064                continue;
5065            }
5066
5067            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5068                continue;
5069            }
5070
5071            final String libName = libInfo.getName();
5072            if (libInfo.isStatic()) {
5073                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5074                if (libIdx < 0) {
5075                    continue;
5076                }
5077                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5078                    continue;
5079                }
5080                if (versionedPackages == null) {
5081                    versionedPackages = new ArrayList<>();
5082                }
5083                // If the dependent is a static shared lib, use the public package name
5084                String dependentPackageName = ps.name;
5085                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5086                    dependentPackageName = ps.pkg.manifestPackageName;
5087                }
5088                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5089            } else if (ps.pkg != null) {
5090                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5091                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5092                    if (versionedPackages == null) {
5093                        versionedPackages = new ArrayList<>();
5094                    }
5095                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5096                }
5097            }
5098        }
5099
5100        return versionedPackages;
5101    }
5102
5103    @Override
5104    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5105        if (!sUserManager.exists(userId)) return null;
5106        final int callingUid = Binder.getCallingUid();
5107        flags = updateFlagsForComponent(flags, userId, component);
5108        enforceCrossUserPermission(callingUid, userId,
5109                false /* requireFullPermission */, false /* checkShell */, "get service info");
5110        synchronized (mPackages) {
5111            PackageParser.Service s = mServices.mServices.get(component);
5112            if (DEBUG_PACKAGE_INFO) Log.v(
5113                TAG, "getServiceInfo " + component + ": " + s);
5114            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5115                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5116                if (ps == null) return null;
5117                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5118                    return null;
5119                }
5120                return PackageParser.generateServiceInfo(
5121                        s, flags, ps.readUserState(userId), userId);
5122            }
5123        }
5124        return null;
5125    }
5126
5127    @Override
5128    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5129        if (!sUserManager.exists(userId)) return null;
5130        final int callingUid = Binder.getCallingUid();
5131        flags = updateFlagsForComponent(flags, userId, component);
5132        enforceCrossUserPermission(callingUid, userId,
5133                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5134        synchronized (mPackages) {
5135            PackageParser.Provider p = mProviders.mProviders.get(component);
5136            if (DEBUG_PACKAGE_INFO) Log.v(
5137                TAG, "getProviderInfo " + component + ": " + p);
5138            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5139                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5140                if (ps == null) return null;
5141                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5142                    return null;
5143                }
5144                return PackageParser.generateProviderInfo(
5145                        p, flags, ps.readUserState(userId), userId);
5146            }
5147        }
5148        return null;
5149    }
5150
5151    @Override
5152    public String[] getSystemSharedLibraryNames() {
5153        // allow instant applications
5154        synchronized (mPackages) {
5155            Set<String> libs = null;
5156            final int libCount = mSharedLibraries.size();
5157            for (int i = 0; i < libCount; i++) {
5158                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5159                if (versionedLib == null) {
5160                    continue;
5161                }
5162                final int versionCount = versionedLib.size();
5163                for (int j = 0; j < versionCount; j++) {
5164                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5165                    if (!libEntry.info.isStatic()) {
5166                        if (libs == null) {
5167                            libs = new ArraySet<>();
5168                        }
5169                        libs.add(libEntry.info.getName());
5170                        break;
5171                    }
5172                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5173                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5174                            UserHandle.getUserId(Binder.getCallingUid()),
5175                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5176                        if (libs == null) {
5177                            libs = new ArraySet<>();
5178                        }
5179                        libs.add(libEntry.info.getName());
5180                        break;
5181                    }
5182                }
5183            }
5184
5185            if (libs != null) {
5186                String[] libsArray = new String[libs.size()];
5187                libs.toArray(libsArray);
5188                return libsArray;
5189            }
5190
5191            return null;
5192        }
5193    }
5194
5195    @Override
5196    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5197        // allow instant applications
5198        synchronized (mPackages) {
5199            return mServicesSystemSharedLibraryPackageName;
5200        }
5201    }
5202
5203    @Override
5204    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5205        // allow instant applications
5206        synchronized (mPackages) {
5207            return mSharedSystemSharedLibraryPackageName;
5208        }
5209    }
5210
5211    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5212        for (int i = userList.length - 1; i >= 0; --i) {
5213            final int userId = userList[i];
5214            // don't add instant app to the list of updates
5215            if (pkgSetting.getInstantApp(userId)) {
5216                continue;
5217            }
5218            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5219            if (changedPackages == null) {
5220                changedPackages = new SparseArray<>();
5221                mChangedPackages.put(userId, changedPackages);
5222            }
5223            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5224            if (sequenceNumbers == null) {
5225                sequenceNumbers = new HashMap<>();
5226                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5227            }
5228            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5229            if (sequenceNumber != null) {
5230                changedPackages.remove(sequenceNumber);
5231            }
5232            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5233            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5234        }
5235        mChangedPackagesSequenceNumber++;
5236    }
5237
5238    @Override
5239    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5240        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5241            return null;
5242        }
5243        synchronized (mPackages) {
5244            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5245                return null;
5246            }
5247            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5248            if (changedPackages == null) {
5249                return null;
5250            }
5251            final List<String> packageNames =
5252                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5253            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5254                final String packageName = changedPackages.get(i);
5255                if (packageName != null) {
5256                    packageNames.add(packageName);
5257                }
5258            }
5259            return packageNames.isEmpty()
5260                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5261        }
5262    }
5263
5264    @Override
5265    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5266        // allow instant applications
5267        ArrayList<FeatureInfo> res;
5268        synchronized (mAvailableFeatures) {
5269            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5270            res.addAll(mAvailableFeatures.values());
5271        }
5272        final FeatureInfo fi = new FeatureInfo();
5273        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5274                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5275        res.add(fi);
5276
5277        return new ParceledListSlice<>(res);
5278    }
5279
5280    @Override
5281    public boolean hasSystemFeature(String name, int version) {
5282        // allow instant applications
5283        synchronized (mAvailableFeatures) {
5284            final FeatureInfo feat = mAvailableFeatures.get(name);
5285            if (feat == null) {
5286                return false;
5287            } else {
5288                return feat.version >= version;
5289            }
5290        }
5291    }
5292
5293    @Override
5294    public int checkPermission(String permName, String pkgName, int userId) {
5295        if (!sUserManager.exists(userId)) {
5296            return PackageManager.PERMISSION_DENIED;
5297        }
5298        final int callingUid = Binder.getCallingUid();
5299
5300        synchronized (mPackages) {
5301            final PackageParser.Package p = mPackages.get(pkgName);
5302            if (p != null && p.mExtras != null) {
5303                final PackageSetting ps = (PackageSetting) p.mExtras;
5304                if (filterAppAccessLPr(ps, callingUid, userId)) {
5305                    return PackageManager.PERMISSION_DENIED;
5306                }
5307                final boolean instantApp = ps.getInstantApp(userId);
5308                final PermissionsState permissionsState = ps.getPermissionsState();
5309                if (permissionsState.hasPermission(permName, userId)) {
5310                    if (instantApp) {
5311                        BasePermission bp = mSettings.mPermissions.get(permName);
5312                        if (bp != null && bp.isInstant()) {
5313                            return PackageManager.PERMISSION_GRANTED;
5314                        }
5315                    } else {
5316                        return PackageManager.PERMISSION_GRANTED;
5317                    }
5318                }
5319                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5320                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5321                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5322                    return PackageManager.PERMISSION_GRANTED;
5323                }
5324            }
5325        }
5326
5327        return PackageManager.PERMISSION_DENIED;
5328    }
5329
5330    @Override
5331    public int checkUidPermission(String permName, int uid) {
5332        final int callingUid = Binder.getCallingUid();
5333        final int callingUserId = UserHandle.getUserId(callingUid);
5334        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5335        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5336        final int userId = UserHandle.getUserId(uid);
5337        if (!sUserManager.exists(userId)) {
5338            return PackageManager.PERMISSION_DENIED;
5339        }
5340
5341        synchronized (mPackages) {
5342            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5343            if (obj != null) {
5344                if (obj instanceof SharedUserSetting) {
5345                    if (isCallerInstantApp) {
5346                        return PackageManager.PERMISSION_DENIED;
5347                    }
5348                } else if (obj instanceof PackageSetting) {
5349                    final PackageSetting ps = (PackageSetting) obj;
5350                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5351                        return PackageManager.PERMISSION_DENIED;
5352                    }
5353                }
5354                final SettingBase settingBase = (SettingBase) obj;
5355                final PermissionsState permissionsState = settingBase.getPermissionsState();
5356                if (permissionsState.hasPermission(permName, userId)) {
5357                    if (isUidInstantApp) {
5358                        BasePermission bp = mSettings.mPermissions.get(permName);
5359                        if (bp != null && bp.isInstant()) {
5360                            return PackageManager.PERMISSION_GRANTED;
5361                        }
5362                    } else {
5363                        return PackageManager.PERMISSION_GRANTED;
5364                    }
5365                }
5366                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5367                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5368                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5369                    return PackageManager.PERMISSION_GRANTED;
5370                }
5371            } else {
5372                ArraySet<String> perms = mSystemPermissions.get(uid);
5373                if (perms != null) {
5374                    if (perms.contains(permName)) {
5375                        return PackageManager.PERMISSION_GRANTED;
5376                    }
5377                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5378                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5379                        return PackageManager.PERMISSION_GRANTED;
5380                    }
5381                }
5382            }
5383        }
5384
5385        return PackageManager.PERMISSION_DENIED;
5386    }
5387
5388    @Override
5389    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5390        if (UserHandle.getCallingUserId() != userId) {
5391            mContext.enforceCallingPermission(
5392                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5393                    "isPermissionRevokedByPolicy for user " + userId);
5394        }
5395
5396        if (checkPermission(permission, packageName, userId)
5397                == PackageManager.PERMISSION_GRANTED) {
5398            return false;
5399        }
5400
5401        final int callingUid = Binder.getCallingUid();
5402        if (getInstantAppPackageName(callingUid) != null) {
5403            if (!isCallerSameApp(packageName, callingUid)) {
5404                return false;
5405            }
5406        } else {
5407            if (isInstantApp(packageName, userId)) {
5408                return false;
5409            }
5410        }
5411
5412        final long identity = Binder.clearCallingIdentity();
5413        try {
5414            final int flags = getPermissionFlags(permission, packageName, userId);
5415            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5416        } finally {
5417            Binder.restoreCallingIdentity(identity);
5418        }
5419    }
5420
5421    @Override
5422    public String getPermissionControllerPackageName() {
5423        synchronized (mPackages) {
5424            return mRequiredInstallerPackage;
5425        }
5426    }
5427
5428    /**
5429     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5430     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5431     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5432     * @param message the message to log on security exception
5433     */
5434    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5435            boolean checkShell, String message) {
5436        if (userId < 0) {
5437            throw new IllegalArgumentException("Invalid userId " + userId);
5438        }
5439        if (checkShell) {
5440            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5441        }
5442        if (userId == UserHandle.getUserId(callingUid)) return;
5443        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5444            if (requireFullPermission) {
5445                mContext.enforceCallingOrSelfPermission(
5446                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5447            } else {
5448                try {
5449                    mContext.enforceCallingOrSelfPermission(
5450                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5451                } catch (SecurityException se) {
5452                    mContext.enforceCallingOrSelfPermission(
5453                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5454                }
5455            }
5456        }
5457    }
5458
5459    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5460        if (callingUid == Process.SHELL_UID) {
5461            if (userHandle >= 0
5462                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5463                throw new SecurityException("Shell does not have permission to access user "
5464                        + userHandle);
5465            } else if (userHandle < 0) {
5466                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5467                        + Debug.getCallers(3));
5468            }
5469        }
5470    }
5471
5472    private BasePermission findPermissionTreeLP(String permName) {
5473        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5474            if (permName.startsWith(bp.name) &&
5475                    permName.length() > bp.name.length() &&
5476                    permName.charAt(bp.name.length()) == '.') {
5477                return bp;
5478            }
5479        }
5480        return null;
5481    }
5482
5483    private BasePermission checkPermissionTreeLP(String permName) {
5484        if (permName != null) {
5485            BasePermission bp = findPermissionTreeLP(permName);
5486            if (bp != null) {
5487                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5488                    return bp;
5489                }
5490                throw new SecurityException("Calling uid "
5491                        + Binder.getCallingUid()
5492                        + " is not allowed to add to permission tree "
5493                        + bp.name + " owned by uid " + bp.uid);
5494            }
5495        }
5496        throw new SecurityException("No permission tree found for " + permName);
5497    }
5498
5499    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5500        if (s1 == null) {
5501            return s2 == null;
5502        }
5503        if (s2 == null) {
5504            return false;
5505        }
5506        if (s1.getClass() != s2.getClass()) {
5507            return false;
5508        }
5509        return s1.equals(s2);
5510    }
5511
5512    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5513        if (pi1.icon != pi2.icon) return false;
5514        if (pi1.logo != pi2.logo) return false;
5515        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5516        if (!compareStrings(pi1.name, pi2.name)) return false;
5517        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5518        // We'll take care of setting this one.
5519        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5520        // These are not currently stored in settings.
5521        //if (!compareStrings(pi1.group, pi2.group)) return false;
5522        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5523        //if (pi1.labelRes != pi2.labelRes) return false;
5524        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5525        return true;
5526    }
5527
5528    int permissionInfoFootprint(PermissionInfo info) {
5529        int size = info.name.length();
5530        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5531        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5532        return size;
5533    }
5534
5535    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5536        int size = 0;
5537        for (BasePermission perm : mSettings.mPermissions.values()) {
5538            if (perm.uid == tree.uid) {
5539                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5540            }
5541        }
5542        return size;
5543    }
5544
5545    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5546        // We calculate the max size of permissions defined by this uid and throw
5547        // if that plus the size of 'info' would exceed our stated maximum.
5548        if (tree.uid != Process.SYSTEM_UID) {
5549            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5550            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5551                throw new SecurityException("Permission tree size cap exceeded");
5552            }
5553        }
5554    }
5555
5556    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5557        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5558            throw new SecurityException("Instant apps can't add permissions");
5559        }
5560        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5561            throw new SecurityException("Label must be specified in permission");
5562        }
5563        BasePermission tree = checkPermissionTreeLP(info.name);
5564        BasePermission bp = mSettings.mPermissions.get(info.name);
5565        boolean added = bp == null;
5566        boolean changed = true;
5567        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5568        if (added) {
5569            enforcePermissionCapLocked(info, tree);
5570            bp = new BasePermission(info.name, tree.sourcePackage,
5571                    BasePermission.TYPE_DYNAMIC);
5572        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5573            throw new SecurityException(
5574                    "Not allowed to modify non-dynamic permission "
5575                    + info.name);
5576        } else {
5577            if (bp.protectionLevel == fixedLevel
5578                    && bp.perm.owner.equals(tree.perm.owner)
5579                    && bp.uid == tree.uid
5580                    && comparePermissionInfos(bp.perm.info, info)) {
5581                changed = false;
5582            }
5583        }
5584        bp.protectionLevel = fixedLevel;
5585        info = new PermissionInfo(info);
5586        info.protectionLevel = fixedLevel;
5587        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5588        bp.perm.info.packageName = tree.perm.info.packageName;
5589        bp.uid = tree.uid;
5590        if (added) {
5591            mSettings.mPermissions.put(info.name, bp);
5592        }
5593        if (changed) {
5594            if (!async) {
5595                mSettings.writeLPr();
5596            } else {
5597                scheduleWriteSettingsLocked();
5598            }
5599        }
5600        return added;
5601    }
5602
5603    @Override
5604    public boolean addPermission(PermissionInfo info) {
5605        synchronized (mPackages) {
5606            return addPermissionLocked(info, false);
5607        }
5608    }
5609
5610    @Override
5611    public boolean addPermissionAsync(PermissionInfo info) {
5612        synchronized (mPackages) {
5613            return addPermissionLocked(info, true);
5614        }
5615    }
5616
5617    @Override
5618    public void removePermission(String name) {
5619        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5620            throw new SecurityException("Instant applications don't have access to this method");
5621        }
5622        synchronized (mPackages) {
5623            checkPermissionTreeLP(name);
5624            BasePermission bp = mSettings.mPermissions.get(name);
5625            if (bp != null) {
5626                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5627                    throw new SecurityException(
5628                            "Not allowed to modify non-dynamic permission "
5629                            + name);
5630                }
5631                mSettings.mPermissions.remove(name);
5632                mSettings.writeLPr();
5633            }
5634        }
5635    }
5636
5637    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5638            PackageParser.Package pkg, BasePermission bp) {
5639        int index = pkg.requestedPermissions.indexOf(bp.name);
5640        if (index == -1) {
5641            throw new SecurityException("Package " + pkg.packageName
5642                    + " has not requested permission " + bp.name);
5643        }
5644        if (!bp.isRuntime() && !bp.isDevelopment()) {
5645            throw new SecurityException("Permission " + bp.name
5646                    + " is not a changeable permission type");
5647        }
5648    }
5649
5650    @Override
5651    public void grantRuntimePermission(String packageName, String name, final int userId) {
5652        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5653    }
5654
5655    private void grantRuntimePermission(String packageName, String name, final int userId,
5656            boolean overridePolicy) {
5657        if (!sUserManager.exists(userId)) {
5658            Log.e(TAG, "No such user:" + userId);
5659            return;
5660        }
5661        final int callingUid = Binder.getCallingUid();
5662
5663        mContext.enforceCallingOrSelfPermission(
5664                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5665                "grantRuntimePermission");
5666
5667        enforceCrossUserPermission(callingUid, userId,
5668                true /* requireFullPermission */, true /* checkShell */,
5669                "grantRuntimePermission");
5670
5671        final int uid;
5672        final PackageSetting ps;
5673
5674        synchronized (mPackages) {
5675            final PackageParser.Package pkg = mPackages.get(packageName);
5676            if (pkg == null) {
5677                throw new IllegalArgumentException("Unknown package: " + packageName);
5678            }
5679            final BasePermission bp = mSettings.mPermissions.get(name);
5680            if (bp == null) {
5681                throw new IllegalArgumentException("Unknown permission: " + name);
5682            }
5683            ps = (PackageSetting) pkg.mExtras;
5684            if (ps == null
5685                    || filterAppAccessLPr(ps, callingUid, userId)) {
5686                throw new IllegalArgumentException("Unknown package: " + packageName);
5687            }
5688
5689            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5690
5691            // If a permission review is required for legacy apps we represent
5692            // their permissions as always granted runtime ones since we need
5693            // to keep the review required permission flag per user while an
5694            // install permission's state is shared across all users.
5695            if (mPermissionReviewRequired
5696                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5697                    && bp.isRuntime()) {
5698                return;
5699            }
5700
5701            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5702
5703            final PermissionsState permissionsState = ps.getPermissionsState();
5704
5705            final int flags = permissionsState.getPermissionFlags(name, userId);
5706            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5707                throw new SecurityException("Cannot grant system fixed permission "
5708                        + name + " for package " + packageName);
5709            }
5710            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5711                throw new SecurityException("Cannot grant policy fixed permission "
5712                        + name + " for package " + packageName);
5713            }
5714
5715            if (bp.isDevelopment()) {
5716                // Development permissions must be handled specially, since they are not
5717                // normal runtime permissions.  For now they apply to all users.
5718                if (permissionsState.grantInstallPermission(bp) !=
5719                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5720                    scheduleWriteSettingsLocked();
5721                }
5722                return;
5723            }
5724
5725            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5726                throw new SecurityException("Cannot grant non-ephemeral permission"
5727                        + name + " for package " + packageName);
5728            }
5729
5730            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5731                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5732                return;
5733            }
5734
5735            final int result = permissionsState.grantRuntimePermission(bp, userId);
5736            switch (result) {
5737                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5738                    return;
5739                }
5740
5741                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5742                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5743                    mHandler.post(new Runnable() {
5744                        @Override
5745                        public void run() {
5746                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5747                        }
5748                    });
5749                }
5750                break;
5751            }
5752
5753            if (bp.isRuntime()) {
5754                logPermissionGranted(mContext, name, packageName);
5755            }
5756
5757            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5758
5759            // Not critical if that is lost - app has to request again.
5760            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5761        }
5762
5763        // Only need to do this if user is initialized. Otherwise it's a new user
5764        // and there are no processes running as the user yet and there's no need
5765        // to make an expensive call to remount processes for the changed permissions.
5766        if (READ_EXTERNAL_STORAGE.equals(name)
5767                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5768            final long token = Binder.clearCallingIdentity();
5769            try {
5770                if (sUserManager.isInitialized(userId)) {
5771                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5772                            StorageManagerInternal.class);
5773                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5774                }
5775            } finally {
5776                Binder.restoreCallingIdentity(token);
5777            }
5778        }
5779    }
5780
5781    @Override
5782    public void revokeRuntimePermission(String packageName, String name, int userId) {
5783        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5784    }
5785
5786    private void revokeRuntimePermission(String packageName, String name, int userId,
5787            boolean overridePolicy) {
5788        if (!sUserManager.exists(userId)) {
5789            Log.e(TAG, "No such user:" + userId);
5790            return;
5791        }
5792
5793        mContext.enforceCallingOrSelfPermission(
5794                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5795                "revokeRuntimePermission");
5796
5797        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5798                true /* requireFullPermission */, true /* checkShell */,
5799                "revokeRuntimePermission");
5800
5801        final int appId;
5802
5803        synchronized (mPackages) {
5804            final PackageParser.Package pkg = mPackages.get(packageName);
5805            if (pkg == null) {
5806                throw new IllegalArgumentException("Unknown package: " + packageName);
5807            }
5808            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5809            if (ps == null
5810                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5811                throw new IllegalArgumentException("Unknown package: " + packageName);
5812            }
5813            final BasePermission bp = mSettings.mPermissions.get(name);
5814            if (bp == null) {
5815                throw new IllegalArgumentException("Unknown permission: " + name);
5816            }
5817
5818            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5819
5820            // If a permission review is required for legacy apps we represent
5821            // their permissions as always granted runtime ones since we need
5822            // to keep the review required permission flag per user while an
5823            // install permission's state is shared across all users.
5824            if (mPermissionReviewRequired
5825                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5826                    && bp.isRuntime()) {
5827                return;
5828            }
5829
5830            final PermissionsState permissionsState = ps.getPermissionsState();
5831
5832            final int flags = permissionsState.getPermissionFlags(name, userId);
5833            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5834                throw new SecurityException("Cannot revoke system fixed permission "
5835                        + name + " for package " + packageName);
5836            }
5837            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5838                throw new SecurityException("Cannot revoke policy fixed permission "
5839                        + name + " for package " + packageName);
5840            }
5841
5842            if (bp.isDevelopment()) {
5843                // Development permissions must be handled specially, since they are not
5844                // normal runtime permissions.  For now they apply to all users.
5845                if (permissionsState.revokeInstallPermission(bp) !=
5846                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5847                    scheduleWriteSettingsLocked();
5848                }
5849                return;
5850            }
5851
5852            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5853                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5854                return;
5855            }
5856
5857            if (bp.isRuntime()) {
5858                logPermissionRevoked(mContext, name, packageName);
5859            }
5860
5861            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5862
5863            // Critical, after this call app should never have the permission.
5864            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5865
5866            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5867        }
5868
5869        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5870    }
5871
5872    /**
5873     * Get the first event id for the permission.
5874     *
5875     * <p>There are four events for each permission: <ul>
5876     *     <li>Request permission: first id + 0</li>
5877     *     <li>Grant permission: first id + 1</li>
5878     *     <li>Request for permission denied: first id + 2</li>
5879     *     <li>Revoke permission: first id + 3</li>
5880     * </ul></p>
5881     *
5882     * @param name name of the permission
5883     *
5884     * @return The first event id for the permission
5885     */
5886    private static int getBaseEventId(@NonNull String name) {
5887        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5888
5889        if (eventIdIndex == -1) {
5890            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5891                    || Build.IS_USER) {
5892                Log.i(TAG, "Unknown permission " + name);
5893
5894                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5895            } else {
5896                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5897                //
5898                // Also update
5899                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5900                // - metrics_constants.proto
5901                throw new IllegalStateException("Unknown permission " + name);
5902            }
5903        }
5904
5905        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5906    }
5907
5908    /**
5909     * Log that a permission was revoked.
5910     *
5911     * @param context Context of the caller
5912     * @param name name of the permission
5913     * @param packageName package permission if for
5914     */
5915    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5916            @NonNull String packageName) {
5917        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5918    }
5919
5920    /**
5921     * Log that a permission request was granted.
5922     *
5923     * @param context Context of the caller
5924     * @param name name of the permission
5925     * @param packageName package permission if for
5926     */
5927    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5928            @NonNull String packageName) {
5929        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5930    }
5931
5932    @Override
5933    public void resetRuntimePermissions() {
5934        mContext.enforceCallingOrSelfPermission(
5935                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5936                "revokeRuntimePermission");
5937
5938        int callingUid = Binder.getCallingUid();
5939        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5940            mContext.enforceCallingOrSelfPermission(
5941                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5942                    "resetRuntimePermissions");
5943        }
5944
5945        synchronized (mPackages) {
5946            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5947            for (int userId : UserManagerService.getInstance().getUserIds()) {
5948                final int packageCount = mPackages.size();
5949                for (int i = 0; i < packageCount; i++) {
5950                    PackageParser.Package pkg = mPackages.valueAt(i);
5951                    if (!(pkg.mExtras instanceof PackageSetting)) {
5952                        continue;
5953                    }
5954                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5955                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5956                }
5957            }
5958        }
5959    }
5960
5961    @Override
5962    public int getPermissionFlags(String name, String packageName, int userId) {
5963        if (!sUserManager.exists(userId)) {
5964            return 0;
5965        }
5966
5967        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5968
5969        final int callingUid = Binder.getCallingUid();
5970        enforceCrossUserPermission(callingUid, userId,
5971                true /* requireFullPermission */, false /* checkShell */,
5972                "getPermissionFlags");
5973
5974        synchronized (mPackages) {
5975            final PackageParser.Package pkg = mPackages.get(packageName);
5976            if (pkg == null) {
5977                return 0;
5978            }
5979            final BasePermission bp = mSettings.mPermissions.get(name);
5980            if (bp == null) {
5981                return 0;
5982            }
5983            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5984            if (ps == null
5985                    || filterAppAccessLPr(ps, callingUid, userId)) {
5986                return 0;
5987            }
5988            PermissionsState permissionsState = ps.getPermissionsState();
5989            return permissionsState.getPermissionFlags(name, userId);
5990        }
5991    }
5992
5993    @Override
5994    public void updatePermissionFlags(String name, String packageName, int flagMask,
5995            int flagValues, int userId) {
5996        if (!sUserManager.exists(userId)) {
5997            return;
5998        }
5999
6000        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
6001
6002        final int callingUid = Binder.getCallingUid();
6003        enforceCrossUserPermission(callingUid, userId,
6004                true /* requireFullPermission */, true /* checkShell */,
6005                "updatePermissionFlags");
6006
6007        // Only the system can change these flags and nothing else.
6008        if (getCallingUid() != Process.SYSTEM_UID) {
6009            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6010            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6011            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
6012            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
6013            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
6014        }
6015
6016        synchronized (mPackages) {
6017            final PackageParser.Package pkg = mPackages.get(packageName);
6018            if (pkg == null) {
6019                throw new IllegalArgumentException("Unknown package: " + packageName);
6020            }
6021            final PackageSetting ps = (PackageSetting) pkg.mExtras;
6022            if (ps == null
6023                    || filterAppAccessLPr(ps, callingUid, userId)) {
6024                throw new IllegalArgumentException("Unknown package: " + packageName);
6025            }
6026
6027            final BasePermission bp = mSettings.mPermissions.get(name);
6028            if (bp == null) {
6029                throw new IllegalArgumentException("Unknown permission: " + name);
6030            }
6031
6032            PermissionsState permissionsState = ps.getPermissionsState();
6033
6034            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
6035
6036            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
6037                // Install and runtime permissions are stored in different places,
6038                // so figure out what permission changed and persist the change.
6039                if (permissionsState.getInstallPermissionState(name) != null) {
6040                    scheduleWriteSettingsLocked();
6041                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
6042                        || hadState) {
6043                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6044                }
6045            }
6046        }
6047    }
6048
6049    /**
6050     * Update the permission flags for all packages and runtime permissions of a user in order
6051     * to allow device or profile owner to remove POLICY_FIXED.
6052     */
6053    @Override
6054    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
6055        if (!sUserManager.exists(userId)) {
6056            return;
6057        }
6058
6059        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
6060
6061        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6062                true /* requireFullPermission */, true /* checkShell */,
6063                "updatePermissionFlagsForAllApps");
6064
6065        // Only the system can change system fixed flags.
6066        if (getCallingUid() != Process.SYSTEM_UID) {
6067            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6068            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6069        }
6070
6071        synchronized (mPackages) {
6072            boolean changed = false;
6073            final int packageCount = mPackages.size();
6074            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6075                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6076                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6077                if (ps == null) {
6078                    continue;
6079                }
6080                PermissionsState permissionsState = ps.getPermissionsState();
6081                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6082                        userId, flagMask, flagValues);
6083            }
6084            if (changed) {
6085                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6086            }
6087        }
6088    }
6089
6090    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6091        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6092                != PackageManager.PERMISSION_GRANTED
6093            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6094                != PackageManager.PERMISSION_GRANTED) {
6095            throw new SecurityException(message + " requires "
6096                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6097                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6098        }
6099    }
6100
6101    @Override
6102    public boolean shouldShowRequestPermissionRationale(String permissionName,
6103            String packageName, int userId) {
6104        if (UserHandle.getCallingUserId() != userId) {
6105            mContext.enforceCallingPermission(
6106                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6107                    "canShowRequestPermissionRationale for user " + userId);
6108        }
6109
6110        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6111        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6112            return false;
6113        }
6114
6115        if (checkPermission(permissionName, packageName, userId)
6116                == PackageManager.PERMISSION_GRANTED) {
6117            return false;
6118        }
6119
6120        final int flags;
6121
6122        final long identity = Binder.clearCallingIdentity();
6123        try {
6124            flags = getPermissionFlags(permissionName,
6125                    packageName, userId);
6126        } finally {
6127            Binder.restoreCallingIdentity(identity);
6128        }
6129
6130        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6131                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6132                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6133
6134        if ((flags & fixedFlags) != 0) {
6135            return false;
6136        }
6137
6138        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6139    }
6140
6141    @Override
6142    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6143        mContext.enforceCallingOrSelfPermission(
6144                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6145                "addOnPermissionsChangeListener");
6146
6147        synchronized (mPackages) {
6148            mOnPermissionChangeListeners.addListenerLocked(listener);
6149        }
6150    }
6151
6152    @Override
6153    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6154        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6155            throw new SecurityException("Instant applications don't have access to this method");
6156        }
6157        synchronized (mPackages) {
6158            mOnPermissionChangeListeners.removeListenerLocked(listener);
6159        }
6160    }
6161
6162    @Override
6163    public boolean isProtectedBroadcast(String actionName) {
6164        // allow instant applications
6165        synchronized (mProtectedBroadcasts) {
6166            if (mProtectedBroadcasts.contains(actionName)) {
6167                return true;
6168            } else if (actionName != null) {
6169                // TODO: remove these terrible hacks
6170                if (actionName.startsWith("android.net.netmon.lingerExpired")
6171                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6172                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6173                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6174                    return true;
6175                }
6176            }
6177        }
6178        return false;
6179    }
6180
6181    @Override
6182    public int checkSignatures(String pkg1, String pkg2) {
6183        synchronized (mPackages) {
6184            final PackageParser.Package p1 = mPackages.get(pkg1);
6185            final PackageParser.Package p2 = mPackages.get(pkg2);
6186            if (p1 == null || p1.mExtras == null
6187                    || p2 == null || p2.mExtras == null) {
6188                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6189            }
6190            final int callingUid = Binder.getCallingUid();
6191            final int callingUserId = UserHandle.getUserId(callingUid);
6192            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6193            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6194            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6195                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6196                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6197            }
6198            return compareSignatures(p1.mSignatures, p2.mSignatures);
6199        }
6200    }
6201
6202    @Override
6203    public int checkUidSignatures(int uid1, int uid2) {
6204        final int callingUid = Binder.getCallingUid();
6205        final int callingUserId = UserHandle.getUserId(callingUid);
6206        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6207        // Map to base uids.
6208        uid1 = UserHandle.getAppId(uid1);
6209        uid2 = UserHandle.getAppId(uid2);
6210        // reader
6211        synchronized (mPackages) {
6212            Signature[] s1;
6213            Signature[] s2;
6214            Object obj = mSettings.getUserIdLPr(uid1);
6215            if (obj != null) {
6216                if (obj instanceof SharedUserSetting) {
6217                    if (isCallerInstantApp) {
6218                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6219                    }
6220                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6221                } else if (obj instanceof PackageSetting) {
6222                    final PackageSetting ps = (PackageSetting) obj;
6223                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6224                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6225                    }
6226                    s1 = ps.signatures.mSignatures;
6227                } else {
6228                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6229                }
6230            } else {
6231                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6232            }
6233            obj = mSettings.getUserIdLPr(uid2);
6234            if (obj != null) {
6235                if (obj instanceof SharedUserSetting) {
6236                    if (isCallerInstantApp) {
6237                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6238                    }
6239                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6240                } else if (obj instanceof PackageSetting) {
6241                    final PackageSetting ps = (PackageSetting) obj;
6242                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6243                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6244                    }
6245                    s2 = ps.signatures.mSignatures;
6246                } else {
6247                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6248                }
6249            } else {
6250                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6251            }
6252            return compareSignatures(s1, s2);
6253        }
6254    }
6255
6256    /**
6257     * This method should typically only be used when granting or revoking
6258     * permissions, since the app may immediately restart after this call.
6259     * <p>
6260     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6261     * guard your work against the app being relaunched.
6262     */
6263    private void killUid(int appId, int userId, String reason) {
6264        final long identity = Binder.clearCallingIdentity();
6265        try {
6266            IActivityManager am = ActivityManager.getService();
6267            if (am != null) {
6268                try {
6269                    am.killUid(appId, userId, reason);
6270                } catch (RemoteException e) {
6271                    /* ignore - same process */
6272                }
6273            }
6274        } finally {
6275            Binder.restoreCallingIdentity(identity);
6276        }
6277    }
6278
6279    /**
6280     * Compares two sets of signatures. Returns:
6281     * <br />
6282     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6283     * <br />
6284     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6285     * <br />
6286     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6287     * <br />
6288     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6289     * <br />
6290     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6291     */
6292    static int compareSignatures(Signature[] s1, Signature[] s2) {
6293        if (s1 == null) {
6294            return s2 == null
6295                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6296                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6297        }
6298
6299        if (s2 == null) {
6300            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6301        }
6302
6303        if (s1.length != s2.length) {
6304            return PackageManager.SIGNATURE_NO_MATCH;
6305        }
6306
6307        // Since both signature sets are of size 1, we can compare without HashSets.
6308        if (s1.length == 1) {
6309            return s1[0].equals(s2[0]) ?
6310                    PackageManager.SIGNATURE_MATCH :
6311                    PackageManager.SIGNATURE_NO_MATCH;
6312        }
6313
6314        ArraySet<Signature> set1 = new ArraySet<Signature>();
6315        for (Signature sig : s1) {
6316            set1.add(sig);
6317        }
6318        ArraySet<Signature> set2 = new ArraySet<Signature>();
6319        for (Signature sig : s2) {
6320            set2.add(sig);
6321        }
6322        // Make sure s2 contains all signatures in s1.
6323        if (set1.equals(set2)) {
6324            return PackageManager.SIGNATURE_MATCH;
6325        }
6326        return PackageManager.SIGNATURE_NO_MATCH;
6327    }
6328
6329    /**
6330     * If the database version for this type of package (internal storage or
6331     * external storage) is less than the version where package signatures
6332     * were updated, return true.
6333     */
6334    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6335        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6336        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6337    }
6338
6339    /**
6340     * Used for backward compatibility to make sure any packages with
6341     * certificate chains get upgraded to the new style. {@code existingSigs}
6342     * will be in the old format (since they were stored on disk from before the
6343     * system upgrade) and {@code scannedSigs} will be in the newer format.
6344     */
6345    private int compareSignaturesCompat(PackageSignatures existingSigs,
6346            PackageParser.Package scannedPkg) {
6347        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6348            return PackageManager.SIGNATURE_NO_MATCH;
6349        }
6350
6351        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6352        for (Signature sig : existingSigs.mSignatures) {
6353            existingSet.add(sig);
6354        }
6355        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6356        for (Signature sig : scannedPkg.mSignatures) {
6357            try {
6358                Signature[] chainSignatures = sig.getChainSignatures();
6359                for (Signature chainSig : chainSignatures) {
6360                    scannedCompatSet.add(chainSig);
6361                }
6362            } catch (CertificateEncodingException e) {
6363                scannedCompatSet.add(sig);
6364            }
6365        }
6366        /*
6367         * Make sure the expanded scanned set contains all signatures in the
6368         * existing one.
6369         */
6370        if (scannedCompatSet.equals(existingSet)) {
6371            // Migrate the old signatures to the new scheme.
6372            existingSigs.assignSignatures(scannedPkg.mSignatures);
6373            // The new KeySets will be re-added later in the scanning process.
6374            synchronized (mPackages) {
6375                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6376            }
6377            return PackageManager.SIGNATURE_MATCH;
6378        }
6379        return PackageManager.SIGNATURE_NO_MATCH;
6380    }
6381
6382    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6383        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6384        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6385    }
6386
6387    private int compareSignaturesRecover(PackageSignatures existingSigs,
6388            PackageParser.Package scannedPkg) {
6389        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6390            return PackageManager.SIGNATURE_NO_MATCH;
6391        }
6392
6393        String msg = null;
6394        try {
6395            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6396                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6397                        + scannedPkg.packageName);
6398                return PackageManager.SIGNATURE_MATCH;
6399            }
6400        } catch (CertificateException e) {
6401            msg = e.getMessage();
6402        }
6403
6404        logCriticalInfo(Log.INFO,
6405                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6406        return PackageManager.SIGNATURE_NO_MATCH;
6407    }
6408
6409    @Override
6410    public List<String> getAllPackages() {
6411        final int callingUid = Binder.getCallingUid();
6412        final int callingUserId = UserHandle.getUserId(callingUid);
6413        synchronized (mPackages) {
6414            if (canViewInstantApps(callingUid, callingUserId)) {
6415                return new ArrayList<String>(mPackages.keySet());
6416            }
6417            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6418            final List<String> result = new ArrayList<>();
6419            if (instantAppPkgName != null) {
6420                // caller is an instant application; filter unexposed applications
6421                for (PackageParser.Package pkg : mPackages.values()) {
6422                    if (!pkg.visibleToInstantApps) {
6423                        continue;
6424                    }
6425                    result.add(pkg.packageName);
6426                }
6427            } else {
6428                // caller is a normal application; filter instant applications
6429                for (PackageParser.Package pkg : mPackages.values()) {
6430                    final PackageSetting ps =
6431                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6432                    if (ps != null
6433                            && ps.getInstantApp(callingUserId)
6434                            && !mInstantAppRegistry.isInstantAccessGranted(
6435                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6436                        continue;
6437                    }
6438                    result.add(pkg.packageName);
6439                }
6440            }
6441            return result;
6442        }
6443    }
6444
6445    @Override
6446    public String[] getPackagesForUid(int uid) {
6447        final int callingUid = Binder.getCallingUid();
6448        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6449        final int userId = UserHandle.getUserId(uid);
6450        uid = UserHandle.getAppId(uid);
6451        // reader
6452        synchronized (mPackages) {
6453            Object obj = mSettings.getUserIdLPr(uid);
6454            if (obj instanceof SharedUserSetting) {
6455                if (isCallerInstantApp) {
6456                    return null;
6457                }
6458                final SharedUserSetting sus = (SharedUserSetting) obj;
6459                final int N = sus.packages.size();
6460                String[] res = new String[N];
6461                final Iterator<PackageSetting> it = sus.packages.iterator();
6462                int i = 0;
6463                while (it.hasNext()) {
6464                    PackageSetting ps = it.next();
6465                    if (ps.getInstalled(userId)) {
6466                        res[i++] = ps.name;
6467                    } else {
6468                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6469                    }
6470                }
6471                return res;
6472            } else if (obj instanceof PackageSetting) {
6473                final PackageSetting ps = (PackageSetting) obj;
6474                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6475                    return new String[]{ps.name};
6476                }
6477            }
6478        }
6479        return null;
6480    }
6481
6482    @Override
6483    public String getNameForUid(int uid) {
6484        final int callingUid = Binder.getCallingUid();
6485        if (getInstantAppPackageName(callingUid) != null) {
6486            return null;
6487        }
6488        synchronized (mPackages) {
6489            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6490            if (obj instanceof SharedUserSetting) {
6491                final SharedUserSetting sus = (SharedUserSetting) obj;
6492                return sus.name + ":" + sus.userId;
6493            } else if (obj instanceof PackageSetting) {
6494                final PackageSetting ps = (PackageSetting) obj;
6495                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6496                    return null;
6497                }
6498                return ps.name;
6499            }
6500            return null;
6501        }
6502    }
6503
6504    @Override
6505    public String[] getNamesForUids(int[] uids) {
6506        if (uids == null || uids.length == 0) {
6507            return null;
6508        }
6509        final int callingUid = Binder.getCallingUid();
6510        if (getInstantAppPackageName(callingUid) != null) {
6511            return null;
6512        }
6513        final String[] names = new String[uids.length];
6514        synchronized (mPackages) {
6515            for (int i = uids.length - 1; i >= 0; i--) {
6516                final int uid = uids[i];
6517                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6518                if (obj instanceof SharedUserSetting) {
6519                    final SharedUserSetting sus = (SharedUserSetting) obj;
6520                    names[i] = "shared:" + sus.name;
6521                } else if (obj instanceof PackageSetting) {
6522                    final PackageSetting ps = (PackageSetting) obj;
6523                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6524                        names[i] = null;
6525                    } else {
6526                        names[i] = ps.name;
6527                    }
6528                } else {
6529                    names[i] = null;
6530                }
6531            }
6532        }
6533        return names;
6534    }
6535
6536    @Override
6537    public int getUidForSharedUser(String sharedUserName) {
6538        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6539            return -1;
6540        }
6541        if (sharedUserName == null) {
6542            return -1;
6543        }
6544        // reader
6545        synchronized (mPackages) {
6546            SharedUserSetting suid;
6547            try {
6548                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6549                if (suid != null) {
6550                    return suid.userId;
6551                }
6552            } catch (PackageManagerException ignore) {
6553                // can't happen, but, still need to catch it
6554            }
6555            return -1;
6556        }
6557    }
6558
6559    @Override
6560    public int getFlagsForUid(int uid) {
6561        final int callingUid = Binder.getCallingUid();
6562        if (getInstantAppPackageName(callingUid) != null) {
6563            return 0;
6564        }
6565        synchronized (mPackages) {
6566            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6567            if (obj instanceof SharedUserSetting) {
6568                final SharedUserSetting sus = (SharedUserSetting) obj;
6569                return sus.pkgFlags;
6570            } else if (obj instanceof PackageSetting) {
6571                final PackageSetting ps = (PackageSetting) obj;
6572                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6573                    return 0;
6574                }
6575                return ps.pkgFlags;
6576            }
6577        }
6578        return 0;
6579    }
6580
6581    @Override
6582    public int getPrivateFlagsForUid(int uid) {
6583        final int callingUid = Binder.getCallingUid();
6584        if (getInstantAppPackageName(callingUid) != null) {
6585            return 0;
6586        }
6587        synchronized (mPackages) {
6588            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6589            if (obj instanceof SharedUserSetting) {
6590                final SharedUserSetting sus = (SharedUserSetting) obj;
6591                return sus.pkgPrivateFlags;
6592            } else if (obj instanceof PackageSetting) {
6593                final PackageSetting ps = (PackageSetting) obj;
6594                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6595                    return 0;
6596                }
6597                return ps.pkgPrivateFlags;
6598            }
6599        }
6600        return 0;
6601    }
6602
6603    @Override
6604    public boolean isUidPrivileged(int uid) {
6605        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6606            return false;
6607        }
6608        uid = UserHandle.getAppId(uid);
6609        // reader
6610        synchronized (mPackages) {
6611            Object obj = mSettings.getUserIdLPr(uid);
6612            if (obj instanceof SharedUserSetting) {
6613                final SharedUserSetting sus = (SharedUserSetting) obj;
6614                final Iterator<PackageSetting> it = sus.packages.iterator();
6615                while (it.hasNext()) {
6616                    if (it.next().isPrivileged()) {
6617                        return true;
6618                    }
6619                }
6620            } else if (obj instanceof PackageSetting) {
6621                final PackageSetting ps = (PackageSetting) obj;
6622                return ps.isPrivileged();
6623            }
6624        }
6625        return false;
6626    }
6627
6628    @Override
6629    public String[] getAppOpPermissionPackages(String permissionName) {
6630        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6631            return null;
6632        }
6633        synchronized (mPackages) {
6634            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6635            if (pkgs == null) {
6636                return null;
6637            }
6638            return pkgs.toArray(new String[pkgs.size()]);
6639        }
6640    }
6641
6642    @Override
6643    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6644            int flags, int userId) {
6645        return resolveIntentInternal(
6646                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6647    }
6648
6649    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6650            int flags, int userId, boolean resolveForStart) {
6651        try {
6652            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6653
6654            if (!sUserManager.exists(userId)) return null;
6655            final int callingUid = Binder.getCallingUid();
6656            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6657            enforceCrossUserPermission(callingUid, userId,
6658                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6659
6660            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6661            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6662                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6663            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6664
6665            final ResolveInfo bestChoice =
6666                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6667            return bestChoice;
6668        } finally {
6669            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6670        }
6671    }
6672
6673    @Override
6674    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6675        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6676            throw new SecurityException(
6677                    "findPersistentPreferredActivity can only be run by the system");
6678        }
6679        if (!sUserManager.exists(userId)) {
6680            return null;
6681        }
6682        final int callingUid = Binder.getCallingUid();
6683        intent = updateIntentForResolve(intent);
6684        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6685        final int flags = updateFlagsForResolve(
6686                0, userId, intent, callingUid, false /*includeInstantApps*/);
6687        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6688                userId);
6689        synchronized (mPackages) {
6690            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6691                    userId);
6692        }
6693    }
6694
6695    @Override
6696    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6697            IntentFilter filter, int match, ComponentName activity) {
6698        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6699            return;
6700        }
6701        final int userId = UserHandle.getCallingUserId();
6702        if (DEBUG_PREFERRED) {
6703            Log.v(TAG, "setLastChosenActivity intent=" + intent
6704                + " resolvedType=" + resolvedType
6705                + " flags=" + flags
6706                + " filter=" + filter
6707                + " match=" + match
6708                + " activity=" + activity);
6709            filter.dump(new PrintStreamPrinter(System.out), "    ");
6710        }
6711        intent.setComponent(null);
6712        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6713                userId);
6714        // Find any earlier preferred or last chosen entries and nuke them
6715        findPreferredActivity(intent, resolvedType,
6716                flags, query, 0, false, true, false, userId);
6717        // Add the new activity as the last chosen for this filter
6718        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6719                "Setting last chosen");
6720    }
6721
6722    @Override
6723    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6724        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6725            return null;
6726        }
6727        final int userId = UserHandle.getCallingUserId();
6728        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6729        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6730                userId);
6731        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6732                false, false, false, userId);
6733    }
6734
6735    /**
6736     * Returns whether or not instant apps have been disabled remotely.
6737     */
6738    private boolean isEphemeralDisabled() {
6739        return mEphemeralAppsDisabled;
6740    }
6741
6742    private boolean isInstantAppAllowed(
6743            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6744            boolean skipPackageCheck) {
6745        if (mInstantAppResolverConnection == null) {
6746            return false;
6747        }
6748        if (mInstantAppInstallerActivity == null) {
6749            return false;
6750        }
6751        if (intent.getComponent() != null) {
6752            return false;
6753        }
6754        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6755            return false;
6756        }
6757        if (!skipPackageCheck && intent.getPackage() != null) {
6758            return false;
6759        }
6760        final boolean isWebUri = hasWebURI(intent);
6761        if (!isWebUri || intent.getData().getHost() == null) {
6762            return false;
6763        }
6764        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6765        // Or if there's already an ephemeral app installed that handles the action
6766        synchronized (mPackages) {
6767            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6768            for (int n = 0; n < count; n++) {
6769                final ResolveInfo info = resolvedActivities.get(n);
6770                final String packageName = info.activityInfo.packageName;
6771                final PackageSetting ps = mSettings.mPackages.get(packageName);
6772                if (ps != null) {
6773                    // only check domain verification status if the app is not a browser
6774                    if (!info.handleAllWebDataURI) {
6775                        // Try to get the status from User settings first
6776                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6777                        final int status = (int) (packedStatus >> 32);
6778                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6779                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6780                            if (DEBUG_EPHEMERAL) {
6781                                Slog.v(TAG, "DENY instant app;"
6782                                    + " pkg: " + packageName + ", status: " + status);
6783                            }
6784                            return false;
6785                        }
6786                    }
6787                    if (ps.getInstantApp(userId)) {
6788                        if (DEBUG_EPHEMERAL) {
6789                            Slog.v(TAG, "DENY instant app installed;"
6790                                    + " pkg: " + packageName);
6791                        }
6792                        return false;
6793                    }
6794                }
6795            }
6796        }
6797        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6798        return true;
6799    }
6800
6801    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6802            Intent origIntent, String resolvedType, String callingPackage,
6803            Bundle verificationBundle, int userId) {
6804        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6805                new InstantAppRequest(responseObj, origIntent, resolvedType,
6806                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6807        mHandler.sendMessage(msg);
6808    }
6809
6810    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6811            int flags, List<ResolveInfo> query, int userId) {
6812        if (query != null) {
6813            final int N = query.size();
6814            if (N == 1) {
6815                return query.get(0);
6816            } else if (N > 1) {
6817                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6818                // If there is more than one activity with the same priority,
6819                // then let the user decide between them.
6820                ResolveInfo r0 = query.get(0);
6821                ResolveInfo r1 = query.get(1);
6822                if (DEBUG_INTENT_MATCHING || debug) {
6823                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6824                            + r1.activityInfo.name + "=" + r1.priority);
6825                }
6826                // If the first activity has a higher priority, or a different
6827                // default, then it is always desirable to pick it.
6828                if (r0.priority != r1.priority
6829                        || r0.preferredOrder != r1.preferredOrder
6830                        || r0.isDefault != r1.isDefault) {
6831                    return query.get(0);
6832                }
6833                // If we have saved a preference for a preferred activity for
6834                // this Intent, use that.
6835                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6836                        flags, query, r0.priority, true, false, debug, userId);
6837                if (ri != null) {
6838                    return ri;
6839                }
6840                // If we have an ephemeral app, use it
6841                for (int i = 0; i < N; i++) {
6842                    ri = query.get(i);
6843                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6844                        final String packageName = ri.activityInfo.packageName;
6845                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6846                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6847                        final int status = (int)(packedStatus >> 32);
6848                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6849                            return ri;
6850                        }
6851                    }
6852                }
6853                ri = new ResolveInfo(mResolveInfo);
6854                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6855                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6856                // If all of the options come from the same package, show the application's
6857                // label and icon instead of the generic resolver's.
6858                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6859                // and then throw away the ResolveInfo itself, meaning that the caller loses
6860                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6861                // a fallback for this case; we only set the target package's resources on
6862                // the ResolveInfo, not the ActivityInfo.
6863                final String intentPackage = intent.getPackage();
6864                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6865                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6866                    ri.resolvePackageName = intentPackage;
6867                    if (userNeedsBadging(userId)) {
6868                        ri.noResourceId = true;
6869                    } else {
6870                        ri.icon = appi.icon;
6871                    }
6872                    ri.iconResourceId = appi.icon;
6873                    ri.labelRes = appi.labelRes;
6874                }
6875                ri.activityInfo.applicationInfo = new ApplicationInfo(
6876                        ri.activityInfo.applicationInfo);
6877                if (userId != 0) {
6878                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6879                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6880                }
6881                // Make sure that the resolver is displayable in car mode
6882                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6883                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6884                return ri;
6885            }
6886        }
6887        return null;
6888    }
6889
6890    /**
6891     * Return true if the given list is not empty and all of its contents have
6892     * an activityInfo with the given package name.
6893     */
6894    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6895        if (ArrayUtils.isEmpty(list)) {
6896            return false;
6897        }
6898        for (int i = 0, N = list.size(); i < N; i++) {
6899            final ResolveInfo ri = list.get(i);
6900            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6901            if (ai == null || !packageName.equals(ai.packageName)) {
6902                return false;
6903            }
6904        }
6905        return true;
6906    }
6907
6908    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6909            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6910        final int N = query.size();
6911        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6912                .get(userId);
6913        // Get the list of persistent preferred activities that handle the intent
6914        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6915        List<PersistentPreferredActivity> pprefs = ppir != null
6916                ? ppir.queryIntent(intent, resolvedType,
6917                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6918                        userId)
6919                : null;
6920        if (pprefs != null && pprefs.size() > 0) {
6921            final int M = pprefs.size();
6922            for (int i=0; i<M; i++) {
6923                final PersistentPreferredActivity ppa = pprefs.get(i);
6924                if (DEBUG_PREFERRED || debug) {
6925                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6926                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6927                            + "\n  component=" + ppa.mComponent);
6928                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6929                }
6930                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6931                        flags | MATCH_DISABLED_COMPONENTS, userId);
6932                if (DEBUG_PREFERRED || debug) {
6933                    Slog.v(TAG, "Found persistent preferred activity:");
6934                    if (ai != null) {
6935                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6936                    } else {
6937                        Slog.v(TAG, "  null");
6938                    }
6939                }
6940                if (ai == null) {
6941                    // This previously registered persistent preferred activity
6942                    // component is no longer known. Ignore it and do NOT remove it.
6943                    continue;
6944                }
6945                for (int j=0; j<N; j++) {
6946                    final ResolveInfo ri = query.get(j);
6947                    if (!ri.activityInfo.applicationInfo.packageName
6948                            .equals(ai.applicationInfo.packageName)) {
6949                        continue;
6950                    }
6951                    if (!ri.activityInfo.name.equals(ai.name)) {
6952                        continue;
6953                    }
6954                    //  Found a persistent preference that can handle the intent.
6955                    if (DEBUG_PREFERRED || debug) {
6956                        Slog.v(TAG, "Returning persistent preferred activity: " +
6957                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6958                    }
6959                    return ri;
6960                }
6961            }
6962        }
6963        return null;
6964    }
6965
6966    // TODO: handle preferred activities missing while user has amnesia
6967    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6968            List<ResolveInfo> query, int priority, boolean always,
6969            boolean removeMatches, boolean debug, int userId) {
6970        if (!sUserManager.exists(userId)) return null;
6971        final int callingUid = Binder.getCallingUid();
6972        flags = updateFlagsForResolve(
6973                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6974        intent = updateIntentForResolve(intent);
6975        // writer
6976        synchronized (mPackages) {
6977            // Try to find a matching persistent preferred activity.
6978            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6979                    debug, userId);
6980
6981            // If a persistent preferred activity matched, use it.
6982            if (pri != null) {
6983                return pri;
6984            }
6985
6986            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6987            // Get the list of preferred activities that handle the intent
6988            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6989            List<PreferredActivity> prefs = pir != null
6990                    ? pir.queryIntent(intent, resolvedType,
6991                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6992                            userId)
6993                    : null;
6994            if (prefs != null && prefs.size() > 0) {
6995                boolean changed = false;
6996                try {
6997                    // First figure out how good the original match set is.
6998                    // We will only allow preferred activities that came
6999                    // from the same match quality.
7000                    int match = 0;
7001
7002                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
7003
7004                    final int N = query.size();
7005                    for (int j=0; j<N; j++) {
7006                        final ResolveInfo ri = query.get(j);
7007                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
7008                                + ": 0x" + Integer.toHexString(match));
7009                        if (ri.match > match) {
7010                            match = ri.match;
7011                        }
7012                    }
7013
7014                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
7015                            + Integer.toHexString(match));
7016
7017                    match &= IntentFilter.MATCH_CATEGORY_MASK;
7018                    final int M = prefs.size();
7019                    for (int i=0; i<M; i++) {
7020                        final PreferredActivity pa = prefs.get(i);
7021                        if (DEBUG_PREFERRED || debug) {
7022                            Slog.v(TAG, "Checking PreferredActivity ds="
7023                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
7024                                    + "\n  component=" + pa.mPref.mComponent);
7025                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7026                        }
7027                        if (pa.mPref.mMatch != match) {
7028                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
7029                                    + Integer.toHexString(pa.mPref.mMatch));
7030                            continue;
7031                        }
7032                        // If it's not an "always" type preferred activity and that's what we're
7033                        // looking for, skip it.
7034                        if (always && !pa.mPref.mAlways) {
7035                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
7036                            continue;
7037                        }
7038                        final ActivityInfo ai = getActivityInfo(
7039                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
7040                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
7041                                userId);
7042                        if (DEBUG_PREFERRED || debug) {
7043                            Slog.v(TAG, "Found preferred activity:");
7044                            if (ai != null) {
7045                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7046                            } else {
7047                                Slog.v(TAG, "  null");
7048                            }
7049                        }
7050                        if (ai == null) {
7051                            // This previously registered preferred activity
7052                            // component is no longer known.  Most likely an update
7053                            // to the app was installed and in the new version this
7054                            // component no longer exists.  Clean it up by removing
7055                            // it from the preferred activities list, and skip it.
7056                            Slog.w(TAG, "Removing dangling preferred activity: "
7057                                    + pa.mPref.mComponent);
7058                            pir.removeFilter(pa);
7059                            changed = true;
7060                            continue;
7061                        }
7062                        for (int j=0; j<N; j++) {
7063                            final ResolveInfo ri = query.get(j);
7064                            if (!ri.activityInfo.applicationInfo.packageName
7065                                    .equals(ai.applicationInfo.packageName)) {
7066                                continue;
7067                            }
7068                            if (!ri.activityInfo.name.equals(ai.name)) {
7069                                continue;
7070                            }
7071
7072                            if (removeMatches) {
7073                                pir.removeFilter(pa);
7074                                changed = true;
7075                                if (DEBUG_PREFERRED) {
7076                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7077                                }
7078                                break;
7079                            }
7080
7081                            // Okay we found a previously set preferred or last chosen app.
7082                            // If the result set is different from when this
7083                            // was created, and is not a subset of the preferred set, we need to
7084                            // clear it and re-ask the user their preference, if we're looking for
7085                            // an "always" type entry.
7086                            if (always && !pa.mPref.sameSet(query)) {
7087                                if (pa.mPref.isSuperset(query)) {
7088                                    // some components of the set are no longer present in
7089                                    // the query, but the preferred activity can still be reused
7090                                    if (DEBUG_PREFERRED) {
7091                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
7092                                                + " still valid as only non-preferred components"
7093                                                + " were removed for " + intent + " type "
7094                                                + resolvedType);
7095                                    }
7096                                    // remove obsolete components and re-add the up-to-date filter
7097                                    PreferredActivity freshPa = new PreferredActivity(pa,
7098                                            pa.mPref.mMatch,
7099                                            pa.mPref.discardObsoleteComponents(query),
7100                                            pa.mPref.mComponent,
7101                                            pa.mPref.mAlways);
7102                                    pir.removeFilter(pa);
7103                                    pir.addFilter(freshPa);
7104                                    changed = true;
7105                                } else {
7106                                    Slog.i(TAG,
7107                                            "Result set changed, dropping preferred activity for "
7108                                                    + intent + " type " + resolvedType);
7109                                    if (DEBUG_PREFERRED) {
7110                                        Slog.v(TAG, "Removing preferred activity since set changed "
7111                                                + pa.mPref.mComponent);
7112                                    }
7113                                    pir.removeFilter(pa);
7114                                    // Re-add the filter as a "last chosen" entry (!always)
7115                                    PreferredActivity lastChosen = new PreferredActivity(
7116                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7117                                    pir.addFilter(lastChosen);
7118                                    changed = true;
7119                                    return null;
7120                                }
7121                            }
7122
7123                            // Yay! Either the set matched or we're looking for the last chosen
7124                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7125                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7126                            return ri;
7127                        }
7128                    }
7129                } finally {
7130                    if (changed) {
7131                        if (DEBUG_PREFERRED) {
7132                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7133                        }
7134                        scheduleWritePackageRestrictionsLocked(userId);
7135                    }
7136                }
7137            }
7138        }
7139        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7140        return null;
7141    }
7142
7143    /*
7144     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7145     */
7146    @Override
7147    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7148            int targetUserId) {
7149        mContext.enforceCallingOrSelfPermission(
7150                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7151        List<CrossProfileIntentFilter> matches =
7152                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7153        if (matches != null) {
7154            int size = matches.size();
7155            for (int i = 0; i < size; i++) {
7156                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7157            }
7158        }
7159        if (hasWebURI(intent)) {
7160            // cross-profile app linking works only towards the parent.
7161            final int callingUid = Binder.getCallingUid();
7162            final UserInfo parent = getProfileParent(sourceUserId);
7163            synchronized(mPackages) {
7164                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7165                        false /*includeInstantApps*/);
7166                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7167                        intent, resolvedType, flags, sourceUserId, parent.id);
7168                return xpDomainInfo != null;
7169            }
7170        }
7171        return false;
7172    }
7173
7174    private UserInfo getProfileParent(int userId) {
7175        final long identity = Binder.clearCallingIdentity();
7176        try {
7177            return sUserManager.getProfileParent(userId);
7178        } finally {
7179            Binder.restoreCallingIdentity(identity);
7180        }
7181    }
7182
7183    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7184            String resolvedType, int userId) {
7185        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7186        if (resolver != null) {
7187            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7188        }
7189        return null;
7190    }
7191
7192    @Override
7193    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7194            String resolvedType, int flags, int userId) {
7195        try {
7196            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7197
7198            return new ParceledListSlice<>(
7199                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7200        } finally {
7201            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7202        }
7203    }
7204
7205    /**
7206     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7207     * instant, returns {@code null}.
7208     */
7209    private String getInstantAppPackageName(int callingUid) {
7210        synchronized (mPackages) {
7211            // If the caller is an isolated app use the owner's uid for the lookup.
7212            if (Process.isIsolated(callingUid)) {
7213                callingUid = mIsolatedOwners.get(callingUid);
7214            }
7215            final int appId = UserHandle.getAppId(callingUid);
7216            final Object obj = mSettings.getUserIdLPr(appId);
7217            if (obj instanceof PackageSetting) {
7218                final PackageSetting ps = (PackageSetting) obj;
7219                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7220                return isInstantApp ? ps.pkg.packageName : null;
7221            }
7222        }
7223        return null;
7224    }
7225
7226    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7227            String resolvedType, int flags, int userId) {
7228        return queryIntentActivitiesInternal(
7229                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7230                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7231    }
7232
7233    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7234            String resolvedType, int flags, int filterCallingUid, int userId,
7235            boolean resolveForStart, boolean allowDynamicSplits) {
7236        if (!sUserManager.exists(userId)) return Collections.emptyList();
7237        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7238        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7239                false /* requireFullPermission */, false /* checkShell */,
7240                "query intent activities");
7241        final String pkgName = intent.getPackage();
7242        ComponentName comp = intent.getComponent();
7243        if (comp == null) {
7244            if (intent.getSelector() != null) {
7245                intent = intent.getSelector();
7246                comp = intent.getComponent();
7247            }
7248        }
7249
7250        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7251                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7252        if (comp != null) {
7253            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7254            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7255            if (ai != null) {
7256                // When specifying an explicit component, we prevent the activity from being
7257                // used when either 1) the calling package is normal and the activity is within
7258                // an ephemeral application or 2) the calling package is ephemeral and the
7259                // activity is not visible to ephemeral applications.
7260                final boolean matchInstantApp =
7261                        (flags & PackageManager.MATCH_INSTANT) != 0;
7262                final boolean matchVisibleToInstantAppOnly =
7263                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7264                final boolean matchExplicitlyVisibleOnly =
7265                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7266                final boolean isCallerInstantApp =
7267                        instantAppPkgName != null;
7268                final boolean isTargetSameInstantApp =
7269                        comp.getPackageName().equals(instantAppPkgName);
7270                final boolean isTargetInstantApp =
7271                        (ai.applicationInfo.privateFlags
7272                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7273                final boolean isTargetVisibleToInstantApp =
7274                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7275                final boolean isTargetExplicitlyVisibleToInstantApp =
7276                        isTargetVisibleToInstantApp
7277                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7278                final boolean isTargetHiddenFromInstantApp =
7279                        !isTargetVisibleToInstantApp
7280                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7281                final boolean blockResolution =
7282                        !isTargetSameInstantApp
7283                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7284                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7285                                        && isTargetHiddenFromInstantApp));
7286                if (!blockResolution) {
7287                    final ResolveInfo ri = new ResolveInfo();
7288                    ri.activityInfo = ai;
7289                    list.add(ri);
7290                }
7291            }
7292            return applyPostResolutionFilter(
7293                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7294        }
7295
7296        // reader
7297        boolean sortResult = false;
7298        boolean addEphemeral = false;
7299        List<ResolveInfo> result;
7300        final boolean ephemeralDisabled = isEphemeralDisabled();
7301        synchronized (mPackages) {
7302            if (pkgName == null) {
7303                List<CrossProfileIntentFilter> matchingFilters =
7304                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7305                // Check for results that need to skip the current profile.
7306                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7307                        resolvedType, flags, userId);
7308                if (xpResolveInfo != null) {
7309                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7310                    xpResult.add(xpResolveInfo);
7311                    return applyPostResolutionFilter(
7312                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7313                            allowDynamicSplits, filterCallingUid, userId);
7314                }
7315
7316                // Check for results in the current profile.
7317                result = filterIfNotSystemUser(mActivities.queryIntent(
7318                        intent, resolvedType, flags, userId), userId);
7319                addEphemeral = !ephemeralDisabled
7320                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7321                // Check for cross profile results.
7322                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7323                xpResolveInfo = queryCrossProfileIntents(
7324                        matchingFilters, intent, resolvedType, flags, userId,
7325                        hasNonNegativePriorityResult);
7326                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7327                    boolean isVisibleToUser = filterIfNotSystemUser(
7328                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7329                    if (isVisibleToUser) {
7330                        result.add(xpResolveInfo);
7331                        sortResult = true;
7332                    }
7333                }
7334                if (hasWebURI(intent)) {
7335                    CrossProfileDomainInfo xpDomainInfo = null;
7336                    final UserInfo parent = getProfileParent(userId);
7337                    if (parent != null) {
7338                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7339                                flags, userId, parent.id);
7340                    }
7341                    if (xpDomainInfo != null) {
7342                        if (xpResolveInfo != null) {
7343                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7344                            // in the result.
7345                            result.remove(xpResolveInfo);
7346                        }
7347                        if (result.size() == 0 && !addEphemeral) {
7348                            // No result in current profile, but found candidate in parent user.
7349                            // And we are not going to add emphemeral app, so we can return the
7350                            // result straight away.
7351                            result.add(xpDomainInfo.resolveInfo);
7352                            return applyPostResolutionFilter(result, instantAppPkgName,
7353                                    allowDynamicSplits, filterCallingUid, userId);
7354                        }
7355                    } else if (result.size() <= 1 && !addEphemeral) {
7356                        // No result in parent user and <= 1 result in current profile, and we
7357                        // are not going to add emphemeral app, so we can return the result without
7358                        // further processing.
7359                        return applyPostResolutionFilter(result, instantAppPkgName,
7360                                allowDynamicSplits, filterCallingUid, userId);
7361                    }
7362                    // We have more than one candidate (combining results from current and parent
7363                    // profile), so we need filtering and sorting.
7364                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7365                            intent, flags, result, xpDomainInfo, userId);
7366                    sortResult = true;
7367                }
7368            } else {
7369                final PackageParser.Package pkg = mPackages.get(pkgName);
7370                result = null;
7371                if (pkg != null) {
7372                    result = filterIfNotSystemUser(
7373                            mActivities.queryIntentForPackage(
7374                                    intent, resolvedType, flags, pkg.activities, userId),
7375                            userId);
7376                }
7377                if (result == null || result.size() == 0) {
7378                    // the caller wants to resolve for a particular package; however, there
7379                    // were no installed results, so, try to find an ephemeral result
7380                    addEphemeral = !ephemeralDisabled
7381                            && isInstantAppAllowed(
7382                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7383                    if (result == null) {
7384                        result = new ArrayList<>();
7385                    }
7386                }
7387            }
7388        }
7389        if (addEphemeral) {
7390            result = maybeAddInstantAppInstaller(
7391                    result, intent, resolvedType, flags, userId, resolveForStart);
7392        }
7393        if (sortResult) {
7394            Collections.sort(result, mResolvePrioritySorter);
7395        }
7396        return applyPostResolutionFilter(
7397                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7398    }
7399
7400    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7401            String resolvedType, int flags, int userId, boolean resolveForStart) {
7402        // first, check to see if we've got an instant app already installed
7403        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7404        ResolveInfo localInstantApp = null;
7405        boolean blockResolution = false;
7406        if (!alreadyResolvedLocally) {
7407            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7408                    flags
7409                        | PackageManager.GET_RESOLVED_FILTER
7410                        | PackageManager.MATCH_INSTANT
7411                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7412                    userId);
7413            for (int i = instantApps.size() - 1; i >= 0; --i) {
7414                final ResolveInfo info = instantApps.get(i);
7415                final String packageName = info.activityInfo.packageName;
7416                final PackageSetting ps = mSettings.mPackages.get(packageName);
7417                if (ps.getInstantApp(userId)) {
7418                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7419                    final int status = (int)(packedStatus >> 32);
7420                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7421                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7422                        // there's a local instant application installed, but, the user has
7423                        // chosen to never use it; skip resolution and don't acknowledge
7424                        // an instant application is even available
7425                        if (DEBUG_EPHEMERAL) {
7426                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7427                        }
7428                        blockResolution = true;
7429                        break;
7430                    } else {
7431                        // we have a locally installed instant application; skip resolution
7432                        // but acknowledge there's an instant application available
7433                        if (DEBUG_EPHEMERAL) {
7434                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7435                        }
7436                        localInstantApp = info;
7437                        break;
7438                    }
7439                }
7440            }
7441        }
7442        // no app installed, let's see if one's available
7443        AuxiliaryResolveInfo auxiliaryResponse = null;
7444        if (!blockResolution) {
7445            if (localInstantApp == null) {
7446                // we don't have an instant app locally, resolve externally
7447                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7448                final InstantAppRequest requestObject = new InstantAppRequest(
7449                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7450                        null /*callingPackage*/, userId, null /*verificationBundle*/,
7451                        resolveForStart);
7452                auxiliaryResponse =
7453                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7454                                mContext, mInstantAppResolverConnection, requestObject);
7455                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7456            } else {
7457                // we have an instant application locally, but, we can't admit that since
7458                // callers shouldn't be able to determine prior browsing. create a dummy
7459                // auxiliary response so the downstream code behaves as if there's an
7460                // instant application available externally. when it comes time to start
7461                // the instant application, we'll do the right thing.
7462                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7463                auxiliaryResponse = new AuxiliaryResolveInfo(
7464                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7465                        ai.versionCode, null /*failureIntent*/);
7466            }
7467        }
7468        if (auxiliaryResponse != null) {
7469            if (DEBUG_EPHEMERAL) {
7470                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7471            }
7472            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7473            final PackageSetting ps =
7474                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7475            if (ps != null) {
7476                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7477                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7478                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7479                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7480                // make sure this resolver is the default
7481                ephemeralInstaller.isDefault = true;
7482                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7483                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7484                // add a non-generic filter
7485                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7486                ephemeralInstaller.filter.addDataPath(
7487                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7488                ephemeralInstaller.isInstantAppAvailable = true;
7489                result.add(ephemeralInstaller);
7490            }
7491        }
7492        return result;
7493    }
7494
7495    private static class CrossProfileDomainInfo {
7496        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7497        ResolveInfo resolveInfo;
7498        /* Best domain verification status of the activities found in the other profile */
7499        int bestDomainVerificationStatus;
7500    }
7501
7502    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7503            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7504        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7505                sourceUserId)) {
7506            return null;
7507        }
7508        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7509                resolvedType, flags, parentUserId);
7510
7511        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7512            return null;
7513        }
7514        CrossProfileDomainInfo result = null;
7515        int size = resultTargetUser.size();
7516        for (int i = 0; i < size; i++) {
7517            ResolveInfo riTargetUser = resultTargetUser.get(i);
7518            // Intent filter verification is only for filters that specify a host. So don't return
7519            // those that handle all web uris.
7520            if (riTargetUser.handleAllWebDataURI) {
7521                continue;
7522            }
7523            String packageName = riTargetUser.activityInfo.packageName;
7524            PackageSetting ps = mSettings.mPackages.get(packageName);
7525            if (ps == null) {
7526                continue;
7527            }
7528            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7529            int status = (int)(verificationState >> 32);
7530            if (result == null) {
7531                result = new CrossProfileDomainInfo();
7532                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7533                        sourceUserId, parentUserId);
7534                result.bestDomainVerificationStatus = status;
7535            } else {
7536                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7537                        result.bestDomainVerificationStatus);
7538            }
7539        }
7540        // Don't consider matches with status NEVER across profiles.
7541        if (result != null && result.bestDomainVerificationStatus
7542                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7543            return null;
7544        }
7545        return result;
7546    }
7547
7548    /**
7549     * Verification statuses are ordered from the worse to the best, except for
7550     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7551     */
7552    private int bestDomainVerificationStatus(int status1, int status2) {
7553        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7554            return status2;
7555        }
7556        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7557            return status1;
7558        }
7559        return (int) MathUtils.max(status1, status2);
7560    }
7561
7562    private boolean isUserEnabled(int userId) {
7563        long callingId = Binder.clearCallingIdentity();
7564        try {
7565            UserInfo userInfo = sUserManager.getUserInfo(userId);
7566            return userInfo != null && userInfo.isEnabled();
7567        } finally {
7568            Binder.restoreCallingIdentity(callingId);
7569        }
7570    }
7571
7572    /**
7573     * Filter out activities with systemUserOnly flag set, when current user is not System.
7574     *
7575     * @return filtered list
7576     */
7577    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7578        if (userId == UserHandle.USER_SYSTEM) {
7579            return resolveInfos;
7580        }
7581        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7582            ResolveInfo info = resolveInfos.get(i);
7583            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7584                resolveInfos.remove(i);
7585            }
7586        }
7587        return resolveInfos;
7588    }
7589
7590    /**
7591     * Filters out ephemeral activities.
7592     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7593     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7594     *
7595     * @param resolveInfos The pre-filtered list of resolved activities
7596     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7597     *          is performed.
7598     * @return A filtered list of resolved activities.
7599     */
7600    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7601            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7602        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7603            final ResolveInfo info = resolveInfos.get(i);
7604            // allow activities that are defined in the provided package
7605            if (allowDynamicSplits
7606                    && info.activityInfo.splitName != null
7607                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7608                            info.activityInfo.splitName)) {
7609                // requested activity is defined in a split that hasn't been installed yet.
7610                // add the installer to the resolve list
7611                if (DEBUG_INSTALL) {
7612                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7613                }
7614                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7615                final ComponentName installFailureActivity = findInstallFailureActivity(
7616                        info.activityInfo.packageName,  filterCallingUid, userId);
7617                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7618                        info.activityInfo.packageName, info.activityInfo.splitName,
7619                        installFailureActivity,
7620                        info.activityInfo.applicationInfo.versionCode,
7621                        null /*failureIntent*/);
7622                // make sure this resolver is the default
7623                installerInfo.isDefault = true;
7624                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7625                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7626                // add a non-generic filter
7627                installerInfo.filter = new IntentFilter();
7628                // load resources from the correct package
7629                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7630                resolveInfos.set(i, installerInfo);
7631                continue;
7632            }
7633            // caller is a full app, don't need to apply any other filtering
7634            if (ephemeralPkgName == null) {
7635                continue;
7636            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7637                // caller is same app; don't need to apply any other filtering
7638                continue;
7639            }
7640            // allow activities that have been explicitly exposed to ephemeral apps
7641            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7642            if (!isEphemeralApp
7643                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7644                continue;
7645            }
7646            resolveInfos.remove(i);
7647        }
7648        return resolveInfos;
7649    }
7650
7651    /**
7652     * Returns the activity component that can handle install failures.
7653     * <p>By default, the instant application installer handles failures. However, an
7654     * application may want to handle failures on its own. Applications do this by
7655     * creating an activity with an intent filter that handles the action
7656     * {@link Intent#ACTION_INSTALL_FAILURE}.
7657     */
7658    private @Nullable ComponentName findInstallFailureActivity(
7659            String packageName, int filterCallingUid, int userId) {
7660        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7661        failureActivityIntent.setPackage(packageName);
7662        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7663        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7664                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7665                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7666        final int NR = result.size();
7667        if (NR > 0) {
7668            for (int i = 0; i < NR; i++) {
7669                final ResolveInfo info = result.get(i);
7670                if (info.activityInfo.splitName != null) {
7671                    continue;
7672                }
7673                return new ComponentName(packageName, info.activityInfo.name);
7674            }
7675        }
7676        return null;
7677    }
7678
7679    /**
7680     * @param resolveInfos list of resolve infos in descending priority order
7681     * @return if the list contains a resolve info with non-negative priority
7682     */
7683    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7684        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7685    }
7686
7687    private static boolean hasWebURI(Intent intent) {
7688        if (intent.getData() == null) {
7689            return false;
7690        }
7691        final String scheme = intent.getScheme();
7692        if (TextUtils.isEmpty(scheme)) {
7693            return false;
7694        }
7695        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7696    }
7697
7698    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7699            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7700            int userId) {
7701        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7702
7703        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7704            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7705                    candidates.size());
7706        }
7707
7708        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7709        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7710        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7711        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7712        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7713        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7714
7715        synchronized (mPackages) {
7716            final int count = candidates.size();
7717            // First, try to use linked apps. Partition the candidates into four lists:
7718            // one for the final results, one for the "do not use ever", one for "undefined status"
7719            // and finally one for "browser app type".
7720            for (int n=0; n<count; n++) {
7721                ResolveInfo info = candidates.get(n);
7722                String packageName = info.activityInfo.packageName;
7723                PackageSetting ps = mSettings.mPackages.get(packageName);
7724                if (ps != null) {
7725                    // Add to the special match all list (Browser use case)
7726                    if (info.handleAllWebDataURI) {
7727                        matchAllList.add(info);
7728                        continue;
7729                    }
7730                    // Try to get the status from User settings first
7731                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7732                    int status = (int)(packedStatus >> 32);
7733                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7734                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7735                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7736                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7737                                    + " : linkgen=" + linkGeneration);
7738                        }
7739                        // Use link-enabled generation as preferredOrder, i.e.
7740                        // prefer newly-enabled over earlier-enabled.
7741                        info.preferredOrder = linkGeneration;
7742                        alwaysList.add(info);
7743                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7744                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7745                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7746                        }
7747                        neverList.add(info);
7748                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7749                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7750                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7751                        }
7752                        alwaysAskList.add(info);
7753                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7754                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7755                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7756                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7757                        }
7758                        undefinedList.add(info);
7759                    }
7760                }
7761            }
7762
7763            // We'll want to include browser possibilities in a few cases
7764            boolean includeBrowser = false;
7765
7766            // First try to add the "always" resolution(s) for the current user, if any
7767            if (alwaysList.size() > 0) {
7768                result.addAll(alwaysList);
7769            } else {
7770                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7771                result.addAll(undefinedList);
7772                // Maybe add one for the other profile.
7773                if (xpDomainInfo != null && (
7774                        xpDomainInfo.bestDomainVerificationStatus
7775                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7776                    result.add(xpDomainInfo.resolveInfo);
7777                }
7778                includeBrowser = true;
7779            }
7780
7781            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7782            // If there were 'always' entries their preferred order has been set, so we also
7783            // back that off to make the alternatives equivalent
7784            if (alwaysAskList.size() > 0) {
7785                for (ResolveInfo i : result) {
7786                    i.preferredOrder = 0;
7787                }
7788                result.addAll(alwaysAskList);
7789                includeBrowser = true;
7790            }
7791
7792            if (includeBrowser) {
7793                // Also add browsers (all of them or only the default one)
7794                if (DEBUG_DOMAIN_VERIFICATION) {
7795                    Slog.v(TAG, "   ...including browsers in candidate set");
7796                }
7797                if ((matchFlags & MATCH_ALL) != 0) {
7798                    result.addAll(matchAllList);
7799                } else {
7800                    // Browser/generic handling case.  If there's a default browser, go straight
7801                    // to that (but only if there is no other higher-priority match).
7802                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7803                    int maxMatchPrio = 0;
7804                    ResolveInfo defaultBrowserMatch = null;
7805                    final int numCandidates = matchAllList.size();
7806                    for (int n = 0; n < numCandidates; n++) {
7807                        ResolveInfo info = matchAllList.get(n);
7808                        // track the highest overall match priority...
7809                        if (info.priority > maxMatchPrio) {
7810                            maxMatchPrio = info.priority;
7811                        }
7812                        // ...and the highest-priority default browser match
7813                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7814                            if (defaultBrowserMatch == null
7815                                    || (defaultBrowserMatch.priority < info.priority)) {
7816                                if (debug) {
7817                                    Slog.v(TAG, "Considering default browser match " + info);
7818                                }
7819                                defaultBrowserMatch = info;
7820                            }
7821                        }
7822                    }
7823                    if (defaultBrowserMatch != null
7824                            && defaultBrowserMatch.priority >= maxMatchPrio
7825                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7826                    {
7827                        if (debug) {
7828                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7829                        }
7830                        result.add(defaultBrowserMatch);
7831                    } else {
7832                        result.addAll(matchAllList);
7833                    }
7834                }
7835
7836                // If there is nothing selected, add all candidates and remove the ones that the user
7837                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7838                if (result.size() == 0) {
7839                    result.addAll(candidates);
7840                    result.removeAll(neverList);
7841                }
7842            }
7843        }
7844        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7845            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7846                    result.size());
7847            for (ResolveInfo info : result) {
7848                Slog.v(TAG, "  + " + info.activityInfo);
7849            }
7850        }
7851        return result;
7852    }
7853
7854    // Returns a packed value as a long:
7855    //
7856    // high 'int'-sized word: link status: undefined/ask/never/always.
7857    // low 'int'-sized word: relative priority among 'always' results.
7858    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7859        long result = ps.getDomainVerificationStatusForUser(userId);
7860        // if none available, get the master status
7861        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7862            if (ps.getIntentFilterVerificationInfo() != null) {
7863                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7864            }
7865        }
7866        return result;
7867    }
7868
7869    private ResolveInfo querySkipCurrentProfileIntents(
7870            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7871            int flags, int sourceUserId) {
7872        if (matchingFilters != null) {
7873            int size = matchingFilters.size();
7874            for (int i = 0; i < size; i ++) {
7875                CrossProfileIntentFilter filter = matchingFilters.get(i);
7876                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7877                    // Checking if there are activities in the target user that can handle the
7878                    // intent.
7879                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7880                            resolvedType, flags, sourceUserId);
7881                    if (resolveInfo != null) {
7882                        return resolveInfo;
7883                    }
7884                }
7885            }
7886        }
7887        return null;
7888    }
7889
7890    // Return matching ResolveInfo in target user if any.
7891    private ResolveInfo queryCrossProfileIntents(
7892            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7893            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7894        if (matchingFilters != null) {
7895            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7896            // match the same intent. For performance reasons, it is better not to
7897            // run queryIntent twice for the same userId
7898            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7899            int size = matchingFilters.size();
7900            for (int i = 0; i < size; i++) {
7901                CrossProfileIntentFilter filter = matchingFilters.get(i);
7902                int targetUserId = filter.getTargetUserId();
7903                boolean skipCurrentProfile =
7904                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7905                boolean skipCurrentProfileIfNoMatchFound =
7906                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7907                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7908                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7909                    // Checking if there are activities in the target user that can handle the
7910                    // intent.
7911                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7912                            resolvedType, flags, sourceUserId);
7913                    if (resolveInfo != null) return resolveInfo;
7914                    alreadyTriedUserIds.put(targetUserId, true);
7915                }
7916            }
7917        }
7918        return null;
7919    }
7920
7921    /**
7922     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7923     * will forward the intent to the filter's target user.
7924     * Otherwise, returns null.
7925     */
7926    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7927            String resolvedType, int flags, int sourceUserId) {
7928        int targetUserId = filter.getTargetUserId();
7929        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7930                resolvedType, flags, targetUserId);
7931        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7932            // If all the matches in the target profile are suspended, return null.
7933            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7934                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7935                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7936                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7937                            targetUserId);
7938                }
7939            }
7940        }
7941        return null;
7942    }
7943
7944    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7945            int sourceUserId, int targetUserId) {
7946        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7947        long ident = Binder.clearCallingIdentity();
7948        boolean targetIsProfile;
7949        try {
7950            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7951        } finally {
7952            Binder.restoreCallingIdentity(ident);
7953        }
7954        String className;
7955        if (targetIsProfile) {
7956            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7957        } else {
7958            className = FORWARD_INTENT_TO_PARENT;
7959        }
7960        ComponentName forwardingActivityComponentName = new ComponentName(
7961                mAndroidApplication.packageName, className);
7962        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7963                sourceUserId);
7964        if (!targetIsProfile) {
7965            forwardingActivityInfo.showUserIcon = targetUserId;
7966            forwardingResolveInfo.noResourceId = true;
7967        }
7968        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7969        forwardingResolveInfo.priority = 0;
7970        forwardingResolveInfo.preferredOrder = 0;
7971        forwardingResolveInfo.match = 0;
7972        forwardingResolveInfo.isDefault = true;
7973        forwardingResolveInfo.filter = filter;
7974        forwardingResolveInfo.targetUserId = targetUserId;
7975        return forwardingResolveInfo;
7976    }
7977
7978    @Override
7979    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7980            Intent[] specifics, String[] specificTypes, Intent intent,
7981            String resolvedType, int flags, int userId) {
7982        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7983                specificTypes, intent, resolvedType, flags, userId));
7984    }
7985
7986    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7987            Intent[] specifics, String[] specificTypes, Intent intent,
7988            String resolvedType, int flags, int userId) {
7989        if (!sUserManager.exists(userId)) return Collections.emptyList();
7990        final int callingUid = Binder.getCallingUid();
7991        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7992                false /*includeInstantApps*/);
7993        enforceCrossUserPermission(callingUid, userId,
7994                false /*requireFullPermission*/, false /*checkShell*/,
7995                "query intent activity options");
7996        final String resultsAction = intent.getAction();
7997
7998        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7999                | PackageManager.GET_RESOLVED_FILTER, userId);
8000
8001        if (DEBUG_INTENT_MATCHING) {
8002            Log.v(TAG, "Query " + intent + ": " + results);
8003        }
8004
8005        int specificsPos = 0;
8006        int N;
8007
8008        // todo: note that the algorithm used here is O(N^2).  This
8009        // isn't a problem in our current environment, but if we start running
8010        // into situations where we have more than 5 or 10 matches then this
8011        // should probably be changed to something smarter...
8012
8013        // First we go through and resolve each of the specific items
8014        // that were supplied, taking care of removing any corresponding
8015        // duplicate items in the generic resolve list.
8016        if (specifics != null) {
8017            for (int i=0; i<specifics.length; i++) {
8018                final Intent sintent = specifics[i];
8019                if (sintent == null) {
8020                    continue;
8021                }
8022
8023                if (DEBUG_INTENT_MATCHING) {
8024                    Log.v(TAG, "Specific #" + i + ": " + sintent);
8025                }
8026
8027                String action = sintent.getAction();
8028                if (resultsAction != null && resultsAction.equals(action)) {
8029                    // If this action was explicitly requested, then don't
8030                    // remove things that have it.
8031                    action = null;
8032                }
8033
8034                ResolveInfo ri = null;
8035                ActivityInfo ai = null;
8036
8037                ComponentName comp = sintent.getComponent();
8038                if (comp == null) {
8039                    ri = resolveIntent(
8040                        sintent,
8041                        specificTypes != null ? specificTypes[i] : null,
8042                            flags, userId);
8043                    if (ri == null) {
8044                        continue;
8045                    }
8046                    if (ri == mResolveInfo) {
8047                        // ACK!  Must do something better with this.
8048                    }
8049                    ai = ri.activityInfo;
8050                    comp = new ComponentName(ai.applicationInfo.packageName,
8051                            ai.name);
8052                } else {
8053                    ai = getActivityInfo(comp, flags, userId);
8054                    if (ai == null) {
8055                        continue;
8056                    }
8057                }
8058
8059                // Look for any generic query activities that are duplicates
8060                // of this specific one, and remove them from the results.
8061                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
8062                N = results.size();
8063                int j;
8064                for (j=specificsPos; j<N; j++) {
8065                    ResolveInfo sri = results.get(j);
8066                    if ((sri.activityInfo.name.equals(comp.getClassName())
8067                            && sri.activityInfo.applicationInfo.packageName.equals(
8068                                    comp.getPackageName()))
8069                        || (action != null && sri.filter.matchAction(action))) {
8070                        results.remove(j);
8071                        if (DEBUG_INTENT_MATCHING) Log.v(
8072                            TAG, "Removing duplicate item from " + j
8073                            + " due to specific " + specificsPos);
8074                        if (ri == null) {
8075                            ri = sri;
8076                        }
8077                        j--;
8078                        N--;
8079                    }
8080                }
8081
8082                // Add this specific item to its proper place.
8083                if (ri == null) {
8084                    ri = new ResolveInfo();
8085                    ri.activityInfo = ai;
8086                }
8087                results.add(specificsPos, ri);
8088                ri.specificIndex = i;
8089                specificsPos++;
8090            }
8091        }
8092
8093        // Now we go through the remaining generic results and remove any
8094        // duplicate actions that are found here.
8095        N = results.size();
8096        for (int i=specificsPos; i<N-1; i++) {
8097            final ResolveInfo rii = results.get(i);
8098            if (rii.filter == null) {
8099                continue;
8100            }
8101
8102            // Iterate over all of the actions of this result's intent
8103            // filter...  typically this should be just one.
8104            final Iterator<String> it = rii.filter.actionsIterator();
8105            if (it == null) {
8106                continue;
8107            }
8108            while (it.hasNext()) {
8109                final String action = it.next();
8110                if (resultsAction != null && resultsAction.equals(action)) {
8111                    // If this action was explicitly requested, then don't
8112                    // remove things that have it.
8113                    continue;
8114                }
8115                for (int j=i+1; j<N; j++) {
8116                    final ResolveInfo rij = results.get(j);
8117                    if (rij.filter != null && rij.filter.hasAction(action)) {
8118                        results.remove(j);
8119                        if (DEBUG_INTENT_MATCHING) Log.v(
8120                            TAG, "Removing duplicate item from " + j
8121                            + " due to action " + action + " at " + i);
8122                        j--;
8123                        N--;
8124                    }
8125                }
8126            }
8127
8128            // If the caller didn't request filter information, drop it now
8129            // so we don't have to marshall/unmarshall it.
8130            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8131                rii.filter = null;
8132            }
8133        }
8134
8135        // Filter out the caller activity if so requested.
8136        if (caller != null) {
8137            N = results.size();
8138            for (int i=0; i<N; i++) {
8139                ActivityInfo ainfo = results.get(i).activityInfo;
8140                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8141                        && caller.getClassName().equals(ainfo.name)) {
8142                    results.remove(i);
8143                    break;
8144                }
8145            }
8146        }
8147
8148        // If the caller didn't request filter information,
8149        // drop them now so we don't have to
8150        // marshall/unmarshall it.
8151        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8152            N = results.size();
8153            for (int i=0; i<N; i++) {
8154                results.get(i).filter = null;
8155            }
8156        }
8157
8158        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8159        return results;
8160    }
8161
8162    @Override
8163    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8164            String resolvedType, int flags, int userId) {
8165        return new ParceledListSlice<>(
8166                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8167                        false /*allowDynamicSplits*/));
8168    }
8169
8170    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8171            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8172        if (!sUserManager.exists(userId)) return Collections.emptyList();
8173        final int callingUid = Binder.getCallingUid();
8174        enforceCrossUserPermission(callingUid, userId,
8175                false /*requireFullPermission*/, false /*checkShell*/,
8176                "query intent receivers");
8177        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8178        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8179                false /*includeInstantApps*/);
8180        ComponentName comp = intent.getComponent();
8181        if (comp == null) {
8182            if (intent.getSelector() != null) {
8183                intent = intent.getSelector();
8184                comp = intent.getComponent();
8185            }
8186        }
8187        if (comp != null) {
8188            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8189            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8190            if (ai != null) {
8191                // When specifying an explicit component, we prevent the activity from being
8192                // used when either 1) the calling package is normal and the activity is within
8193                // an instant application or 2) the calling package is ephemeral and the
8194                // activity is not visible to instant applications.
8195                final boolean matchInstantApp =
8196                        (flags & PackageManager.MATCH_INSTANT) != 0;
8197                final boolean matchVisibleToInstantAppOnly =
8198                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8199                final boolean matchExplicitlyVisibleOnly =
8200                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8201                final boolean isCallerInstantApp =
8202                        instantAppPkgName != null;
8203                final boolean isTargetSameInstantApp =
8204                        comp.getPackageName().equals(instantAppPkgName);
8205                final boolean isTargetInstantApp =
8206                        (ai.applicationInfo.privateFlags
8207                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8208                final boolean isTargetVisibleToInstantApp =
8209                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8210                final boolean isTargetExplicitlyVisibleToInstantApp =
8211                        isTargetVisibleToInstantApp
8212                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8213                final boolean isTargetHiddenFromInstantApp =
8214                        !isTargetVisibleToInstantApp
8215                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8216                final boolean blockResolution =
8217                        !isTargetSameInstantApp
8218                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8219                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8220                                        && isTargetHiddenFromInstantApp));
8221                if (!blockResolution) {
8222                    ResolveInfo ri = new ResolveInfo();
8223                    ri.activityInfo = ai;
8224                    list.add(ri);
8225                }
8226            }
8227            return applyPostResolutionFilter(
8228                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8229        }
8230
8231        // reader
8232        synchronized (mPackages) {
8233            String pkgName = intent.getPackage();
8234            if (pkgName == null) {
8235                final List<ResolveInfo> result =
8236                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8237                return applyPostResolutionFilter(
8238                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8239            }
8240            final PackageParser.Package pkg = mPackages.get(pkgName);
8241            if (pkg != null) {
8242                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8243                        intent, resolvedType, flags, pkg.receivers, userId);
8244                return applyPostResolutionFilter(
8245                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8246            }
8247            return Collections.emptyList();
8248        }
8249    }
8250
8251    @Override
8252    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8253        final int callingUid = Binder.getCallingUid();
8254        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8255    }
8256
8257    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8258            int userId, int callingUid) {
8259        if (!sUserManager.exists(userId)) return null;
8260        flags = updateFlagsForResolve(
8261                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8262        List<ResolveInfo> query = queryIntentServicesInternal(
8263                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8264        if (query != null) {
8265            if (query.size() >= 1) {
8266                // If there is more than one service with the same priority,
8267                // just arbitrarily pick the first one.
8268                return query.get(0);
8269            }
8270        }
8271        return null;
8272    }
8273
8274    @Override
8275    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8276            String resolvedType, int flags, int userId) {
8277        final int callingUid = Binder.getCallingUid();
8278        return new ParceledListSlice<>(queryIntentServicesInternal(
8279                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8280    }
8281
8282    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8283            String resolvedType, int flags, int userId, int callingUid,
8284            boolean includeInstantApps) {
8285        if (!sUserManager.exists(userId)) return Collections.emptyList();
8286        enforceCrossUserPermission(callingUid, userId,
8287                false /*requireFullPermission*/, false /*checkShell*/,
8288                "query intent receivers");
8289        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8290        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8291        ComponentName comp = intent.getComponent();
8292        if (comp == null) {
8293            if (intent.getSelector() != null) {
8294                intent = intent.getSelector();
8295                comp = intent.getComponent();
8296            }
8297        }
8298        if (comp != null) {
8299            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8300            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8301            if (si != null) {
8302                // When specifying an explicit component, we prevent the service from being
8303                // used when either 1) the service is in an instant application and the
8304                // caller is not the same instant application or 2) the calling package is
8305                // ephemeral and the activity is not visible to ephemeral applications.
8306                final boolean matchInstantApp =
8307                        (flags & PackageManager.MATCH_INSTANT) != 0;
8308                final boolean matchVisibleToInstantAppOnly =
8309                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8310                final boolean isCallerInstantApp =
8311                        instantAppPkgName != null;
8312                final boolean isTargetSameInstantApp =
8313                        comp.getPackageName().equals(instantAppPkgName);
8314                final boolean isTargetInstantApp =
8315                        (si.applicationInfo.privateFlags
8316                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8317                final boolean isTargetHiddenFromInstantApp =
8318                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8319                final boolean blockResolution =
8320                        !isTargetSameInstantApp
8321                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8322                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8323                                        && isTargetHiddenFromInstantApp));
8324                if (!blockResolution) {
8325                    final ResolveInfo ri = new ResolveInfo();
8326                    ri.serviceInfo = si;
8327                    list.add(ri);
8328                }
8329            }
8330            return list;
8331        }
8332
8333        // reader
8334        synchronized (mPackages) {
8335            String pkgName = intent.getPackage();
8336            if (pkgName == null) {
8337                return applyPostServiceResolutionFilter(
8338                        mServices.queryIntent(intent, resolvedType, flags, userId),
8339                        instantAppPkgName);
8340            }
8341            final PackageParser.Package pkg = mPackages.get(pkgName);
8342            if (pkg != null) {
8343                return applyPostServiceResolutionFilter(
8344                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8345                                userId),
8346                        instantAppPkgName);
8347            }
8348            return Collections.emptyList();
8349        }
8350    }
8351
8352    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8353            String instantAppPkgName) {
8354        if (instantAppPkgName == null) {
8355            return resolveInfos;
8356        }
8357        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8358            final ResolveInfo info = resolveInfos.get(i);
8359            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8360            // allow services that are defined in the provided package
8361            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8362                if (info.serviceInfo.splitName != null
8363                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8364                                info.serviceInfo.splitName)) {
8365                    // requested service is defined in a split that hasn't been installed yet.
8366                    // add the installer to the resolve list
8367                    if (DEBUG_EPHEMERAL) {
8368                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8369                    }
8370                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8371                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8372                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8373                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8374                            null /*failureIntent*/);
8375                    // make sure this resolver is the default
8376                    installerInfo.isDefault = true;
8377                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8378                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8379                    // add a non-generic filter
8380                    installerInfo.filter = new IntentFilter();
8381                    // load resources from the correct package
8382                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8383                    resolveInfos.set(i, installerInfo);
8384                }
8385                continue;
8386            }
8387            // allow services that have been explicitly exposed to ephemeral apps
8388            if (!isEphemeralApp
8389                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8390                continue;
8391            }
8392            resolveInfos.remove(i);
8393        }
8394        return resolveInfos;
8395    }
8396
8397    @Override
8398    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8399            String resolvedType, int flags, int userId) {
8400        return new ParceledListSlice<>(
8401                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8402    }
8403
8404    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8405            Intent intent, String resolvedType, int flags, int userId) {
8406        if (!sUserManager.exists(userId)) return Collections.emptyList();
8407        final int callingUid = Binder.getCallingUid();
8408        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8409        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8410                false /*includeInstantApps*/);
8411        ComponentName comp = intent.getComponent();
8412        if (comp == null) {
8413            if (intent.getSelector() != null) {
8414                intent = intent.getSelector();
8415                comp = intent.getComponent();
8416            }
8417        }
8418        if (comp != null) {
8419            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8420            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8421            if (pi != null) {
8422                // When specifying an explicit component, we prevent the provider from being
8423                // used when either 1) the provider is in an instant application and the
8424                // caller is not the same instant application or 2) the calling package is an
8425                // instant application and the provider is not visible to instant applications.
8426                final boolean matchInstantApp =
8427                        (flags & PackageManager.MATCH_INSTANT) != 0;
8428                final boolean matchVisibleToInstantAppOnly =
8429                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8430                final boolean isCallerInstantApp =
8431                        instantAppPkgName != null;
8432                final boolean isTargetSameInstantApp =
8433                        comp.getPackageName().equals(instantAppPkgName);
8434                final boolean isTargetInstantApp =
8435                        (pi.applicationInfo.privateFlags
8436                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8437                final boolean isTargetHiddenFromInstantApp =
8438                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8439                final boolean blockResolution =
8440                        !isTargetSameInstantApp
8441                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8442                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8443                                        && isTargetHiddenFromInstantApp));
8444                if (!blockResolution) {
8445                    final ResolveInfo ri = new ResolveInfo();
8446                    ri.providerInfo = pi;
8447                    list.add(ri);
8448                }
8449            }
8450            return list;
8451        }
8452
8453        // reader
8454        synchronized (mPackages) {
8455            String pkgName = intent.getPackage();
8456            if (pkgName == null) {
8457                return applyPostContentProviderResolutionFilter(
8458                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8459                        instantAppPkgName);
8460            }
8461            final PackageParser.Package pkg = mPackages.get(pkgName);
8462            if (pkg != null) {
8463                return applyPostContentProviderResolutionFilter(
8464                        mProviders.queryIntentForPackage(
8465                        intent, resolvedType, flags, pkg.providers, userId),
8466                        instantAppPkgName);
8467            }
8468            return Collections.emptyList();
8469        }
8470    }
8471
8472    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8473            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8474        if (instantAppPkgName == null) {
8475            return resolveInfos;
8476        }
8477        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8478            final ResolveInfo info = resolveInfos.get(i);
8479            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8480            // allow providers that are defined in the provided package
8481            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8482                if (info.providerInfo.splitName != null
8483                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8484                                info.providerInfo.splitName)) {
8485                    // requested provider is defined in a split that hasn't been installed yet.
8486                    // add the installer to the resolve list
8487                    if (DEBUG_EPHEMERAL) {
8488                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8489                    }
8490                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8491                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8492                            info.providerInfo.packageName, info.providerInfo.splitName,
8493                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8494                            null /*failureIntent*/);
8495                    // make sure this resolver is the default
8496                    installerInfo.isDefault = true;
8497                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8498                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8499                    // add a non-generic filter
8500                    installerInfo.filter = new IntentFilter();
8501                    // load resources from the correct package
8502                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8503                    resolveInfos.set(i, installerInfo);
8504                }
8505                continue;
8506            }
8507            // allow providers that have been explicitly exposed to instant applications
8508            if (!isEphemeralApp
8509                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8510                continue;
8511            }
8512            resolveInfos.remove(i);
8513        }
8514        return resolveInfos;
8515    }
8516
8517    @Override
8518    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8519        final int callingUid = Binder.getCallingUid();
8520        if (getInstantAppPackageName(callingUid) != null) {
8521            return ParceledListSlice.emptyList();
8522        }
8523        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8524        flags = updateFlagsForPackage(flags, userId, null);
8525        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8526        enforceCrossUserPermission(callingUid, userId,
8527                true /* requireFullPermission */, false /* checkShell */,
8528                "get installed packages");
8529
8530        // writer
8531        synchronized (mPackages) {
8532            ArrayList<PackageInfo> list;
8533            if (listUninstalled) {
8534                list = new ArrayList<>(mSettings.mPackages.size());
8535                for (PackageSetting ps : mSettings.mPackages.values()) {
8536                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8537                        continue;
8538                    }
8539                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8540                        continue;
8541                    }
8542                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8543                    if (pi != null) {
8544                        list.add(pi);
8545                    }
8546                }
8547            } else {
8548                list = new ArrayList<>(mPackages.size());
8549                for (PackageParser.Package p : mPackages.values()) {
8550                    final PackageSetting ps = (PackageSetting) p.mExtras;
8551                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8552                        continue;
8553                    }
8554                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8555                        continue;
8556                    }
8557                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8558                            p.mExtras, flags, userId);
8559                    if (pi != null) {
8560                        list.add(pi);
8561                    }
8562                }
8563            }
8564
8565            return new ParceledListSlice<>(list);
8566        }
8567    }
8568
8569    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8570            String[] permissions, boolean[] tmp, int flags, int userId) {
8571        int numMatch = 0;
8572        final PermissionsState permissionsState = ps.getPermissionsState();
8573        for (int i=0; i<permissions.length; i++) {
8574            final String permission = permissions[i];
8575            if (permissionsState.hasPermission(permission, userId)) {
8576                tmp[i] = true;
8577                numMatch++;
8578            } else {
8579                tmp[i] = false;
8580            }
8581        }
8582        if (numMatch == 0) {
8583            return;
8584        }
8585        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8586
8587        // The above might return null in cases of uninstalled apps or install-state
8588        // skew across users/profiles.
8589        if (pi != null) {
8590            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8591                if (numMatch == permissions.length) {
8592                    pi.requestedPermissions = permissions;
8593                } else {
8594                    pi.requestedPermissions = new String[numMatch];
8595                    numMatch = 0;
8596                    for (int i=0; i<permissions.length; i++) {
8597                        if (tmp[i]) {
8598                            pi.requestedPermissions[numMatch] = permissions[i];
8599                            numMatch++;
8600                        }
8601                    }
8602                }
8603            }
8604            list.add(pi);
8605        }
8606    }
8607
8608    @Override
8609    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8610            String[] permissions, int flags, int userId) {
8611        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8612        flags = updateFlagsForPackage(flags, userId, permissions);
8613        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8614                true /* requireFullPermission */, false /* checkShell */,
8615                "get packages holding permissions");
8616        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8617
8618        // writer
8619        synchronized (mPackages) {
8620            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8621            boolean[] tmpBools = new boolean[permissions.length];
8622            if (listUninstalled) {
8623                for (PackageSetting ps : mSettings.mPackages.values()) {
8624                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8625                            userId);
8626                }
8627            } else {
8628                for (PackageParser.Package pkg : mPackages.values()) {
8629                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8630                    if (ps != null) {
8631                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8632                                userId);
8633                    }
8634                }
8635            }
8636
8637            return new ParceledListSlice<PackageInfo>(list);
8638        }
8639    }
8640
8641    @Override
8642    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8643        final int callingUid = Binder.getCallingUid();
8644        if (getInstantAppPackageName(callingUid) != null) {
8645            return ParceledListSlice.emptyList();
8646        }
8647        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8648        flags = updateFlagsForApplication(flags, userId, null);
8649        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8650
8651        // writer
8652        synchronized (mPackages) {
8653            ArrayList<ApplicationInfo> list;
8654            if (listUninstalled) {
8655                list = new ArrayList<>(mSettings.mPackages.size());
8656                for (PackageSetting ps : mSettings.mPackages.values()) {
8657                    ApplicationInfo ai;
8658                    int effectiveFlags = flags;
8659                    if (ps.isSystem()) {
8660                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8661                    }
8662                    if (ps.pkg != null) {
8663                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8664                            continue;
8665                        }
8666                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8667                            continue;
8668                        }
8669                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8670                                ps.readUserState(userId), userId);
8671                        if (ai != null) {
8672                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8673                        }
8674                    } else {
8675                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8676                        // and already converts to externally visible package name
8677                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8678                                callingUid, effectiveFlags, userId);
8679                    }
8680                    if (ai != null) {
8681                        list.add(ai);
8682                    }
8683                }
8684            } else {
8685                list = new ArrayList<>(mPackages.size());
8686                for (PackageParser.Package p : mPackages.values()) {
8687                    if (p.mExtras != null) {
8688                        PackageSetting ps = (PackageSetting) p.mExtras;
8689                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8690                            continue;
8691                        }
8692                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8693                            continue;
8694                        }
8695                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8696                                ps.readUserState(userId), userId);
8697                        if (ai != null) {
8698                            ai.packageName = resolveExternalPackageNameLPr(p);
8699                            list.add(ai);
8700                        }
8701                    }
8702                }
8703            }
8704
8705            return new ParceledListSlice<>(list);
8706        }
8707    }
8708
8709    @Override
8710    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8711        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8712            return null;
8713        }
8714        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8715            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8716                    "getEphemeralApplications");
8717        }
8718        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8719                true /* requireFullPermission */, false /* checkShell */,
8720                "getEphemeralApplications");
8721        synchronized (mPackages) {
8722            List<InstantAppInfo> instantApps = mInstantAppRegistry
8723                    .getInstantAppsLPr(userId);
8724            if (instantApps != null) {
8725                return new ParceledListSlice<>(instantApps);
8726            }
8727        }
8728        return null;
8729    }
8730
8731    @Override
8732    public boolean isInstantApp(String packageName, int userId) {
8733        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8734                true /* requireFullPermission */, false /* checkShell */,
8735                "isInstantApp");
8736        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8737            return false;
8738        }
8739
8740        synchronized (mPackages) {
8741            int callingUid = Binder.getCallingUid();
8742            if (Process.isIsolated(callingUid)) {
8743                callingUid = mIsolatedOwners.get(callingUid);
8744            }
8745            final PackageSetting ps = mSettings.mPackages.get(packageName);
8746            PackageParser.Package pkg = mPackages.get(packageName);
8747            final boolean returnAllowed =
8748                    ps != null
8749                    && (isCallerSameApp(packageName, callingUid)
8750                            || canViewInstantApps(callingUid, userId)
8751                            || mInstantAppRegistry.isInstantAccessGranted(
8752                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8753            if (returnAllowed) {
8754                return ps.getInstantApp(userId);
8755            }
8756        }
8757        return false;
8758    }
8759
8760    @Override
8761    public byte[] getInstantAppCookie(String packageName, int userId) {
8762        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8763            return null;
8764        }
8765
8766        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8767                true /* requireFullPermission */, false /* checkShell */,
8768                "getInstantAppCookie");
8769        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8770            return null;
8771        }
8772        synchronized (mPackages) {
8773            return mInstantAppRegistry.getInstantAppCookieLPw(
8774                    packageName, userId);
8775        }
8776    }
8777
8778    @Override
8779    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8780        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8781            return true;
8782        }
8783
8784        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8785                true /* requireFullPermission */, true /* checkShell */,
8786                "setInstantAppCookie");
8787        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8788            return false;
8789        }
8790        synchronized (mPackages) {
8791            return mInstantAppRegistry.setInstantAppCookieLPw(
8792                    packageName, cookie, userId);
8793        }
8794    }
8795
8796    @Override
8797    public Bitmap getInstantAppIcon(String packageName, int userId) {
8798        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8799            return null;
8800        }
8801
8802        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8803            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8804                    "getInstantAppIcon");
8805        }
8806        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8807                true /* requireFullPermission */, false /* checkShell */,
8808                "getInstantAppIcon");
8809
8810        synchronized (mPackages) {
8811            return mInstantAppRegistry.getInstantAppIconLPw(
8812                    packageName, userId);
8813        }
8814    }
8815
8816    private boolean isCallerSameApp(String packageName, int uid) {
8817        PackageParser.Package pkg = mPackages.get(packageName);
8818        return pkg != null
8819                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8820    }
8821
8822    @Override
8823    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8824        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8825            return ParceledListSlice.emptyList();
8826        }
8827        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8828    }
8829
8830    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8831        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8832
8833        // reader
8834        synchronized (mPackages) {
8835            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8836            final int userId = UserHandle.getCallingUserId();
8837            while (i.hasNext()) {
8838                final PackageParser.Package p = i.next();
8839                if (p.applicationInfo == null) continue;
8840
8841                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8842                        && !p.applicationInfo.isDirectBootAware();
8843                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8844                        && p.applicationInfo.isDirectBootAware();
8845
8846                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8847                        && (!mSafeMode || isSystemApp(p))
8848                        && (matchesUnaware || matchesAware)) {
8849                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8850                    if (ps != null) {
8851                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8852                                ps.readUserState(userId), userId);
8853                        if (ai != null) {
8854                            finalList.add(ai);
8855                        }
8856                    }
8857                }
8858            }
8859        }
8860
8861        return finalList;
8862    }
8863
8864    @Override
8865    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8866        if (!sUserManager.exists(userId)) return null;
8867        flags = updateFlagsForComponent(flags, userId, name);
8868        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8869        // reader
8870        synchronized (mPackages) {
8871            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8872            PackageSetting ps = provider != null
8873                    ? mSettings.mPackages.get(provider.owner.packageName)
8874                    : null;
8875            if (ps != null) {
8876                final boolean isInstantApp = ps.getInstantApp(userId);
8877                // normal application; filter out instant application provider
8878                if (instantAppPkgName == null && isInstantApp) {
8879                    return null;
8880                }
8881                // instant application; filter out other instant applications
8882                if (instantAppPkgName != null
8883                        && isInstantApp
8884                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8885                    return null;
8886                }
8887                // instant application; filter out non-exposed provider
8888                if (instantAppPkgName != null
8889                        && !isInstantApp
8890                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8891                    return null;
8892                }
8893                // provider not enabled
8894                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8895                    return null;
8896                }
8897                return PackageParser.generateProviderInfo(
8898                        provider, flags, ps.readUserState(userId), userId);
8899            }
8900            return null;
8901        }
8902    }
8903
8904    /**
8905     * @deprecated
8906     */
8907    @Deprecated
8908    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8909        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8910            return;
8911        }
8912        // reader
8913        synchronized (mPackages) {
8914            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8915                    .entrySet().iterator();
8916            final int userId = UserHandle.getCallingUserId();
8917            while (i.hasNext()) {
8918                Map.Entry<String, PackageParser.Provider> entry = i.next();
8919                PackageParser.Provider p = entry.getValue();
8920                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8921
8922                if (ps != null && p.syncable
8923                        && (!mSafeMode || (p.info.applicationInfo.flags
8924                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8925                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8926                            ps.readUserState(userId), userId);
8927                    if (info != null) {
8928                        outNames.add(entry.getKey());
8929                        outInfo.add(info);
8930                    }
8931                }
8932            }
8933        }
8934    }
8935
8936    @Override
8937    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8938            int uid, int flags, String metaDataKey) {
8939        final int callingUid = Binder.getCallingUid();
8940        final int userId = processName != null ? UserHandle.getUserId(uid)
8941                : UserHandle.getCallingUserId();
8942        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8943        flags = updateFlagsForComponent(flags, userId, processName);
8944        ArrayList<ProviderInfo> finalList = null;
8945        // reader
8946        synchronized (mPackages) {
8947            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8948            while (i.hasNext()) {
8949                final PackageParser.Provider p = i.next();
8950                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8951                if (ps != null && p.info.authority != null
8952                        && (processName == null
8953                                || (p.info.processName.equals(processName)
8954                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8955                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8956
8957                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8958                    // parameter.
8959                    if (metaDataKey != null
8960                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8961                        continue;
8962                    }
8963                    final ComponentName component =
8964                            new ComponentName(p.info.packageName, p.info.name);
8965                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8966                        continue;
8967                    }
8968                    if (finalList == null) {
8969                        finalList = new ArrayList<ProviderInfo>(3);
8970                    }
8971                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8972                            ps.readUserState(userId), userId);
8973                    if (info != null) {
8974                        finalList.add(info);
8975                    }
8976                }
8977            }
8978        }
8979
8980        if (finalList != null) {
8981            Collections.sort(finalList, mProviderInitOrderSorter);
8982            return new ParceledListSlice<ProviderInfo>(finalList);
8983        }
8984
8985        return ParceledListSlice.emptyList();
8986    }
8987
8988    @Override
8989    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8990        // reader
8991        synchronized (mPackages) {
8992            final int callingUid = Binder.getCallingUid();
8993            final int callingUserId = UserHandle.getUserId(callingUid);
8994            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8995            if (ps == null) return null;
8996            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8997                return null;
8998            }
8999            final PackageParser.Instrumentation i = mInstrumentation.get(component);
9000            return PackageParser.generateInstrumentationInfo(i, flags);
9001        }
9002    }
9003
9004    @Override
9005    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
9006            String targetPackage, int flags) {
9007        final int callingUid = Binder.getCallingUid();
9008        final int callingUserId = UserHandle.getUserId(callingUid);
9009        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
9010        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
9011            return ParceledListSlice.emptyList();
9012        }
9013        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
9014    }
9015
9016    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
9017            int flags) {
9018        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
9019
9020        // reader
9021        synchronized (mPackages) {
9022            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
9023            while (i.hasNext()) {
9024                final PackageParser.Instrumentation p = i.next();
9025                if (targetPackage == null
9026                        || targetPackage.equals(p.info.targetPackage)) {
9027                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
9028                            flags);
9029                    if (ii != null) {
9030                        finalList.add(ii);
9031                    }
9032                }
9033            }
9034        }
9035
9036        return finalList;
9037    }
9038
9039    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
9040        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
9041        try {
9042            scanDirLI(dir, parseFlags, scanFlags, currentTime);
9043        } finally {
9044            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9045        }
9046    }
9047
9048    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
9049        final File[] files = dir.listFiles();
9050        if (ArrayUtils.isEmpty(files)) {
9051            Log.d(TAG, "No files in app dir " + dir);
9052            return;
9053        }
9054
9055        if (DEBUG_PACKAGE_SCANNING) {
9056            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
9057                    + " flags=0x" + Integer.toHexString(parseFlags));
9058        }
9059        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
9060                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
9061                mParallelPackageParserCallback);
9062
9063        // Submit files for parsing in parallel
9064        int fileCount = 0;
9065        for (File file : files) {
9066            final boolean isPackage = (isApkFile(file) || file.isDirectory())
9067                    && !PackageInstallerService.isStageName(file.getName());
9068            if (!isPackage) {
9069                // Ignore entries which are not packages
9070                continue;
9071            }
9072            parallelPackageParser.submit(file, parseFlags);
9073            fileCount++;
9074        }
9075
9076        // Process results one by one
9077        for (; fileCount > 0; fileCount--) {
9078            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
9079            Throwable throwable = parseResult.throwable;
9080            int errorCode = PackageManager.INSTALL_SUCCEEDED;
9081
9082            if (throwable == null) {
9083                // Static shared libraries have synthetic package names
9084                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
9085                    renameStaticSharedLibraryPackage(parseResult.pkg);
9086                }
9087                try {
9088                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
9089                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
9090                                currentTime, null);
9091                    }
9092                } catch (PackageManagerException e) {
9093                    errorCode = e.error;
9094                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
9095                }
9096            } else if (throwable instanceof PackageParser.PackageParserException) {
9097                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9098                        throwable;
9099                errorCode = e.error;
9100                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9101            } else {
9102                throw new IllegalStateException("Unexpected exception occurred while parsing "
9103                        + parseResult.scanFile, throwable);
9104            }
9105
9106            // Delete invalid userdata apps
9107            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
9108                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
9109                logCriticalInfo(Log.WARN,
9110                        "Deleting invalid package at " + parseResult.scanFile);
9111                removeCodePathLI(parseResult.scanFile);
9112            }
9113        }
9114        parallelPackageParser.close();
9115    }
9116
9117    private static File getSettingsProblemFile() {
9118        File dataDir = Environment.getDataDirectory();
9119        File systemDir = new File(dataDir, "system");
9120        File fname = new File(systemDir, "uiderrors.txt");
9121        return fname;
9122    }
9123
9124    static void reportSettingsProblem(int priority, String msg) {
9125        logCriticalInfo(priority, msg);
9126    }
9127
9128    public static void logCriticalInfo(int priority, String msg) {
9129        Slog.println(priority, TAG, msg);
9130        EventLogTags.writePmCriticalInfo(msg);
9131        try {
9132            File fname = getSettingsProblemFile();
9133            FileOutputStream out = new FileOutputStream(fname, true);
9134            PrintWriter pw = new FastPrintWriter(out);
9135            SimpleDateFormat formatter = new SimpleDateFormat();
9136            String dateString = formatter.format(new Date(System.currentTimeMillis()));
9137            pw.println(dateString + ": " + msg);
9138            pw.close();
9139            FileUtils.setPermissions(
9140                    fname.toString(),
9141                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9142                    -1, -1);
9143        } catch (java.io.IOException e) {
9144        }
9145    }
9146
9147    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9148        if (srcFile.isDirectory()) {
9149            final File baseFile = new File(pkg.baseCodePath);
9150            long maxModifiedTime = baseFile.lastModified();
9151            if (pkg.splitCodePaths != null) {
9152                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9153                    final File splitFile = new File(pkg.splitCodePaths[i]);
9154                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9155                }
9156            }
9157            return maxModifiedTime;
9158        }
9159        return srcFile.lastModified();
9160    }
9161
9162    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9163            final int policyFlags) throws PackageManagerException {
9164        // When upgrading from pre-N MR1, verify the package time stamp using the package
9165        // directory and not the APK file.
9166        final long lastModifiedTime = mIsPreNMR1Upgrade
9167                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9168        if (ps != null
9169                && ps.codePath.equals(srcFile)
9170                && ps.timeStamp == lastModifiedTime
9171                && !isCompatSignatureUpdateNeeded(pkg)
9172                && !isRecoverSignatureUpdateNeeded(pkg)) {
9173            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9174            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9175            ArraySet<PublicKey> signingKs;
9176            synchronized (mPackages) {
9177                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9178            }
9179            if (ps.signatures.mSignatures != null
9180                    && ps.signatures.mSignatures.length != 0
9181                    && signingKs != null) {
9182                // Optimization: reuse the existing cached certificates
9183                // if the package appears to be unchanged.
9184                pkg.mSignatures = ps.signatures.mSignatures;
9185                pkg.mSigningKeys = signingKs;
9186                return;
9187            }
9188
9189            Slog.w(TAG, "PackageSetting for " + ps.name
9190                    + " is missing signatures.  Collecting certs again to recover them.");
9191        } else {
9192            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9193        }
9194
9195        try {
9196            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9197            PackageParser.collectCertificates(pkg, policyFlags);
9198        } catch (PackageParserException e) {
9199            throw PackageManagerException.from(e);
9200        } finally {
9201            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9202        }
9203    }
9204
9205    /**
9206     *  Traces a package scan.
9207     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9208     */
9209    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9210            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9211        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9212        try {
9213            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9214        } finally {
9215            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9216        }
9217    }
9218
9219    /**
9220     *  Scans a package and returns the newly parsed package.
9221     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9222     */
9223    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9224            long currentTime, UserHandle user) throws PackageManagerException {
9225        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9226        PackageParser pp = new PackageParser();
9227        pp.setSeparateProcesses(mSeparateProcesses);
9228        pp.setOnlyCoreApps(mOnlyCore);
9229        pp.setDisplayMetrics(mMetrics);
9230        pp.setCallback(mPackageParserCallback);
9231
9232        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9233            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9234        }
9235
9236        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9237        final PackageParser.Package pkg;
9238        try {
9239            pkg = pp.parsePackage(scanFile, parseFlags);
9240        } catch (PackageParserException e) {
9241            throw PackageManagerException.from(e);
9242        } finally {
9243            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9244        }
9245
9246        // Static shared libraries have synthetic package names
9247        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9248            renameStaticSharedLibraryPackage(pkg);
9249        }
9250
9251        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9252    }
9253
9254    /**
9255     *  Scans a package and returns the newly parsed package.
9256     *  @throws PackageManagerException on a parse error.
9257     */
9258    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9259            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9260            throws PackageManagerException {
9261        // If the package has children and this is the first dive in the function
9262        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9263        // packages (parent and children) would be successfully scanned before the
9264        // actual scan since scanning mutates internal state and we want to atomically
9265        // install the package and its children.
9266        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9267            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9268                scanFlags |= SCAN_CHECK_ONLY;
9269            }
9270        } else {
9271            scanFlags &= ~SCAN_CHECK_ONLY;
9272        }
9273
9274        // Scan the parent
9275        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9276                scanFlags, currentTime, user);
9277
9278        // Scan the children
9279        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9280        for (int i = 0; i < childCount; i++) {
9281            PackageParser.Package childPackage = pkg.childPackages.get(i);
9282            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9283                    currentTime, user);
9284        }
9285
9286
9287        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9288            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9289        }
9290
9291        return scannedPkg;
9292    }
9293
9294    /**
9295     *  Scans a package and returns the newly parsed package.
9296     *  @throws PackageManagerException on a parse error.
9297     */
9298    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9299            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9300            throws PackageManagerException {
9301        PackageSetting ps = null;
9302        PackageSetting updatedPkg;
9303        // reader
9304        synchronized (mPackages) {
9305            // Look to see if we already know about this package.
9306            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9307            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9308                // This package has been renamed to its original name.  Let's
9309                // use that.
9310                ps = mSettings.getPackageLPr(oldName);
9311            }
9312            // If there was no original package, see one for the real package name.
9313            if (ps == null) {
9314                ps = mSettings.getPackageLPr(pkg.packageName);
9315            }
9316            // Check to see if this package could be hiding/updating a system
9317            // package.  Must look for it either under the original or real
9318            // package name depending on our state.
9319            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9320            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9321
9322            // If this is a package we don't know about on the system partition, we
9323            // may need to remove disabled child packages on the system partition
9324            // or may need to not add child packages if the parent apk is updated
9325            // on the data partition and no longer defines this child package.
9326            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9327                // If this is a parent package for an updated system app and this system
9328                // app got an OTA update which no longer defines some of the child packages
9329                // we have to prune them from the disabled system packages.
9330                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9331                if (disabledPs != null) {
9332                    final int scannedChildCount = (pkg.childPackages != null)
9333                            ? pkg.childPackages.size() : 0;
9334                    final int disabledChildCount = disabledPs.childPackageNames != null
9335                            ? disabledPs.childPackageNames.size() : 0;
9336                    for (int i = 0; i < disabledChildCount; i++) {
9337                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9338                        boolean disabledPackageAvailable = false;
9339                        for (int j = 0; j < scannedChildCount; j++) {
9340                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9341                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9342                                disabledPackageAvailable = true;
9343                                break;
9344                            }
9345                         }
9346                         if (!disabledPackageAvailable) {
9347                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9348                         }
9349                    }
9350                }
9351            }
9352        }
9353
9354        final boolean isUpdatedPkg = updatedPkg != null;
9355        final boolean isUpdatedSystemPkg = isUpdatedPkg
9356                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9357        boolean isUpdatedPkgBetter = false;
9358        // First check if this is a system package that may involve an update
9359        if (isUpdatedSystemPkg) {
9360            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9361            // it needs to drop FLAG_PRIVILEGED.
9362            if (locationIsPrivileged(scanFile)) {
9363                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9364            } else {
9365                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9366            }
9367
9368            if (ps != null && !ps.codePath.equals(scanFile)) {
9369                // The path has changed from what was last scanned...  check the
9370                // version of the new path against what we have stored to determine
9371                // what to do.
9372                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9373                if (pkg.mVersionCode <= ps.versionCode) {
9374                    // The system package has been updated and the code path does not match
9375                    // Ignore entry. Skip it.
9376                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9377                            + " ignored: updated version " + ps.versionCode
9378                            + " better than this " + pkg.mVersionCode);
9379                    if (!updatedPkg.codePath.equals(scanFile)) {
9380                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9381                                + ps.name + " changing from " + updatedPkg.codePathString
9382                                + " to " + scanFile);
9383                        updatedPkg.codePath = scanFile;
9384                        updatedPkg.codePathString = scanFile.toString();
9385                        updatedPkg.resourcePath = scanFile;
9386                        updatedPkg.resourcePathString = scanFile.toString();
9387                    }
9388                    updatedPkg.pkg = pkg;
9389                    updatedPkg.versionCode = pkg.mVersionCode;
9390
9391                    // Update the disabled system child packages to point to the package too.
9392                    final int childCount = updatedPkg.childPackageNames != null
9393                            ? updatedPkg.childPackageNames.size() : 0;
9394                    for (int i = 0; i < childCount; i++) {
9395                        String childPackageName = updatedPkg.childPackageNames.get(i);
9396                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9397                                childPackageName);
9398                        if (updatedChildPkg != null) {
9399                            updatedChildPkg.pkg = pkg;
9400                            updatedChildPkg.versionCode = pkg.mVersionCode;
9401                        }
9402                    }
9403                } else {
9404                    // The current app on the system partition is better than
9405                    // what we have updated to on the data partition; switch
9406                    // back to the system partition version.
9407                    // At this point, its safely assumed that package installation for
9408                    // apps in system partition will go through. If not there won't be a working
9409                    // version of the app
9410                    // writer
9411                    synchronized (mPackages) {
9412                        // Just remove the loaded entries from package lists.
9413                        mPackages.remove(ps.name);
9414                    }
9415
9416                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9417                            + " reverting from " + ps.codePathString
9418                            + ": new version " + pkg.mVersionCode
9419                            + " better than installed " + ps.versionCode);
9420
9421                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9422                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9423                    synchronized (mInstallLock) {
9424                        args.cleanUpResourcesLI();
9425                    }
9426                    synchronized (mPackages) {
9427                        mSettings.enableSystemPackageLPw(ps.name);
9428                    }
9429                    isUpdatedPkgBetter = true;
9430                }
9431            }
9432        }
9433
9434        String resourcePath = null;
9435        String baseResourcePath = null;
9436        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9437            if (ps != null && ps.resourcePathString != null) {
9438                resourcePath = ps.resourcePathString;
9439                baseResourcePath = ps.resourcePathString;
9440            } else {
9441                // Should not happen at all. Just log an error.
9442                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9443            }
9444        } else {
9445            resourcePath = pkg.codePath;
9446            baseResourcePath = pkg.baseCodePath;
9447        }
9448
9449        // Set application objects path explicitly.
9450        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9451        pkg.setApplicationInfoCodePath(pkg.codePath);
9452        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9453        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9454        pkg.setApplicationInfoResourcePath(resourcePath);
9455        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9456        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9457
9458        // throw an exception if we have an update to a system application, but, it's not more
9459        // recent than the package we've already scanned
9460        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9461            // Set CPU Abis to application info.
9462            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9463                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
9464                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
9465            } else {
9466                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
9467                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
9468            }
9469
9470            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9471                    + scanFile + " ignored: updated version " + ps.versionCode
9472                    + " better than this " + pkg.mVersionCode);
9473        }
9474
9475        if (isUpdatedPkg) {
9476            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9477            // initially
9478            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9479
9480            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9481            // flag set initially
9482            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9483                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9484            }
9485        }
9486
9487        // Verify certificates against what was last scanned
9488        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9489
9490        /*
9491         * A new system app appeared, but we already had a non-system one of the
9492         * same name installed earlier.
9493         */
9494        boolean shouldHideSystemApp = false;
9495        if (!isUpdatedPkg && ps != null
9496                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9497            /*
9498             * Check to make sure the signatures match first. If they don't,
9499             * wipe the installed application and its data.
9500             */
9501            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9502                    != PackageManager.SIGNATURE_MATCH) {
9503                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9504                        + " signatures don't match existing userdata copy; removing");
9505                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9506                        "scanPackageInternalLI")) {
9507                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9508                }
9509                ps = null;
9510            } else {
9511                /*
9512                 * If the newly-added system app is an older version than the
9513                 * already installed version, hide it. It will be scanned later
9514                 * and re-added like an update.
9515                 */
9516                if (pkg.mVersionCode <= ps.versionCode) {
9517                    shouldHideSystemApp = true;
9518                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9519                            + " but new version " + pkg.mVersionCode + " better than installed "
9520                            + ps.versionCode + "; hiding system");
9521                } else {
9522                    /*
9523                     * The newly found system app is a newer version that the
9524                     * one previously installed. Simply remove the
9525                     * already-installed application and replace it with our own
9526                     * while keeping the application data.
9527                     */
9528                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9529                            + " reverting from " + ps.codePathString + ": new version "
9530                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9531                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9532                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9533                    synchronized (mInstallLock) {
9534                        args.cleanUpResourcesLI();
9535                    }
9536                }
9537            }
9538        }
9539
9540        // The apk is forward locked (not public) if its code and resources
9541        // are kept in different files. (except for app in either system or
9542        // vendor path).
9543        // TODO grab this value from PackageSettings
9544        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9545            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9546                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9547            }
9548        }
9549
9550        final int userId = ((user == null) ? 0 : user.getIdentifier());
9551        if (ps != null && ps.getInstantApp(userId)) {
9552            scanFlags |= SCAN_AS_INSTANT_APP;
9553        }
9554        if (ps != null && ps.getVirtulalPreload(userId)) {
9555            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9556        }
9557
9558        // Note that we invoke the following method only if we are about to unpack an application
9559        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9560                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9561
9562        /*
9563         * If the system app should be overridden by a previously installed
9564         * data, hide the system app now and let the /data/app scan pick it up
9565         * again.
9566         */
9567        if (shouldHideSystemApp) {
9568            synchronized (mPackages) {
9569                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9570            }
9571        }
9572
9573        return scannedPkg;
9574    }
9575
9576    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9577        // Derive the new package synthetic package name
9578        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9579                + pkg.staticSharedLibVersion);
9580    }
9581
9582    private static String fixProcessName(String defProcessName,
9583            String processName) {
9584        if (processName == null) {
9585            return defProcessName;
9586        }
9587        return processName;
9588    }
9589
9590    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9591            throws PackageManagerException {
9592        if (pkgSetting.signatures.mSignatures != null) {
9593            // Already existing package. Make sure signatures match
9594            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9595                    == PackageManager.SIGNATURE_MATCH;
9596            if (!match) {
9597                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9598                        == PackageManager.SIGNATURE_MATCH;
9599            }
9600            if (!match) {
9601                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9602                        == PackageManager.SIGNATURE_MATCH;
9603            }
9604            if (!match) {
9605                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9606                        + pkg.packageName + " signatures do not match the "
9607                        + "previously installed version; ignoring!");
9608            }
9609        }
9610
9611        // Check for shared user signatures
9612        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9613            // Already existing package. Make sure signatures match
9614            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9615                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9616            if (!match) {
9617                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9618                        == PackageManager.SIGNATURE_MATCH;
9619            }
9620            if (!match) {
9621                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9622                        == PackageManager.SIGNATURE_MATCH;
9623            }
9624            if (!match) {
9625                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9626                        "Package " + pkg.packageName
9627                        + " has no signatures that match those in shared user "
9628                        + pkgSetting.sharedUser.name + "; ignoring!");
9629            }
9630        }
9631    }
9632
9633    /**
9634     * Enforces that only the system UID or root's UID can call a method exposed
9635     * via Binder.
9636     *
9637     * @param message used as message if SecurityException is thrown
9638     * @throws SecurityException if the caller is not system or root
9639     */
9640    private static final void enforceSystemOrRoot(String message) {
9641        final int uid = Binder.getCallingUid();
9642        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9643            throw new SecurityException(message);
9644        }
9645    }
9646
9647    @Override
9648    public void performFstrimIfNeeded() {
9649        enforceSystemOrRoot("Only the system can request fstrim");
9650
9651        // Before everything else, see whether we need to fstrim.
9652        try {
9653            IStorageManager sm = PackageHelper.getStorageManager();
9654            if (sm != null) {
9655                boolean doTrim = false;
9656                final long interval = android.provider.Settings.Global.getLong(
9657                        mContext.getContentResolver(),
9658                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9659                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9660                if (interval > 0) {
9661                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9662                    if (timeSinceLast > interval) {
9663                        doTrim = true;
9664                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9665                                + "; running immediately");
9666                    }
9667                }
9668                if (doTrim) {
9669                    final boolean dexOptDialogShown;
9670                    synchronized (mPackages) {
9671                        dexOptDialogShown = mDexOptDialogShown;
9672                    }
9673                    if (!isFirstBoot() && dexOptDialogShown) {
9674                        try {
9675                            ActivityManager.getService().showBootMessage(
9676                                    mContext.getResources().getString(
9677                                            R.string.android_upgrading_fstrim), true);
9678                        } catch (RemoteException e) {
9679                        }
9680                    }
9681                    sm.runMaintenance();
9682                }
9683            } else {
9684                Slog.e(TAG, "storageManager service unavailable!");
9685            }
9686        } catch (RemoteException e) {
9687            // Can't happen; StorageManagerService is local
9688        }
9689    }
9690
9691    @Override
9692    public void updatePackagesIfNeeded() {
9693        enforceSystemOrRoot("Only the system can request package update");
9694
9695        // We need to re-extract after an OTA.
9696        boolean causeUpgrade = isUpgrade();
9697
9698        // First boot or factory reset.
9699        // Note: we also handle devices that are upgrading to N right now as if it is their
9700        //       first boot, as they do not have profile data.
9701        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9702
9703        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9704        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9705
9706        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9707            return;
9708        }
9709
9710        List<PackageParser.Package> pkgs;
9711        synchronized (mPackages) {
9712            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9713        }
9714
9715        final long startTime = System.nanoTime();
9716        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9717                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9718                    false /* bootComplete */);
9719
9720        final int elapsedTimeSeconds =
9721                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9722
9723        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9724        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9725        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9726        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9727        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9728    }
9729
9730    /*
9731     * Return the prebuilt profile path given a package base code path.
9732     */
9733    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9734        return pkg.baseCodePath + ".prof";
9735    }
9736
9737    /**
9738     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9739     * containing statistics about the invocation. The array consists of three elements,
9740     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9741     * and {@code numberOfPackagesFailed}.
9742     */
9743    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9744            final String compilerFilter, boolean bootComplete) {
9745
9746        int numberOfPackagesVisited = 0;
9747        int numberOfPackagesOptimized = 0;
9748        int numberOfPackagesSkipped = 0;
9749        int numberOfPackagesFailed = 0;
9750        final int numberOfPackagesToDexopt = pkgs.size();
9751
9752        for (PackageParser.Package pkg : pkgs) {
9753            numberOfPackagesVisited++;
9754
9755            boolean useProfileForDexopt = false;
9756
9757            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9758                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9759                // that are already compiled.
9760                File profileFile = new File(getPrebuildProfilePath(pkg));
9761                // Copy profile if it exists.
9762                if (profileFile.exists()) {
9763                    try {
9764                        // We could also do this lazily before calling dexopt in
9765                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9766                        // is that we don't have a good way to say "do this only once".
9767                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9768                                pkg.applicationInfo.uid, pkg.packageName)) {
9769                            Log.e(TAG, "Installer failed to copy system profile!");
9770                        } else {
9771                            // Disabled as this causes speed-profile compilation during first boot
9772                            // even if things are already compiled.
9773                            // useProfileForDexopt = true;
9774                        }
9775                    } catch (Exception e) {
9776                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9777                                e);
9778                    }
9779                } else {
9780                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9781                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9782                    // minimize the number off apps being speed-profile compiled during first boot.
9783                    // The other paths will not change the filter.
9784                    if (disabledPs != null && disabledPs.pkg.isStub) {
9785                        // The package is the stub one, remove the stub suffix to get the normal
9786                        // package and APK names.
9787                        String systemProfilePath =
9788                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9789                        File systemProfile = new File(systemProfilePath);
9790                        // Use the profile for compilation if there exists one for the same package
9791                        // in the system partition.
9792                        useProfileForDexopt = systemProfile.exists();
9793                    }
9794                }
9795            }
9796
9797            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9798                if (DEBUG_DEXOPT) {
9799                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9800                }
9801                numberOfPackagesSkipped++;
9802                continue;
9803            }
9804
9805            if (DEBUG_DEXOPT) {
9806                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9807                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9808            }
9809
9810            if (showDialog) {
9811                try {
9812                    ActivityManager.getService().showBootMessage(
9813                            mContext.getResources().getString(R.string.android_upgrading_apk,
9814                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9815                } catch (RemoteException e) {
9816                }
9817                synchronized (mPackages) {
9818                    mDexOptDialogShown = true;
9819                }
9820            }
9821
9822            String pkgCompilerFilter = compilerFilter;
9823            if (useProfileForDexopt) {
9824                // Use background dexopt mode to try and use the profile. Note that this does not
9825                // guarantee usage of the profile.
9826                pkgCompilerFilter =
9827                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9828                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
9829            }
9830
9831            // checkProfiles is false to avoid merging profiles during boot which
9832            // might interfere with background compilation (b/28612421).
9833            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9834            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9835            // trade-off worth doing to save boot time work.
9836            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9837            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9838                    pkg.packageName,
9839                    pkgCompilerFilter,
9840                    dexoptFlags));
9841
9842            switch (primaryDexOptStaus) {
9843                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9844                    numberOfPackagesOptimized++;
9845                    break;
9846                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9847                    numberOfPackagesSkipped++;
9848                    break;
9849                case PackageDexOptimizer.DEX_OPT_FAILED:
9850                    numberOfPackagesFailed++;
9851                    break;
9852                default:
9853                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9854                    break;
9855            }
9856        }
9857
9858        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9859                numberOfPackagesFailed };
9860    }
9861
9862    @Override
9863    public void notifyPackageUse(String packageName, int reason) {
9864        synchronized (mPackages) {
9865            final int callingUid = Binder.getCallingUid();
9866            final int callingUserId = UserHandle.getUserId(callingUid);
9867            if (getInstantAppPackageName(callingUid) != null) {
9868                if (!isCallerSameApp(packageName, callingUid)) {
9869                    return;
9870                }
9871            } else {
9872                if (isInstantApp(packageName, callingUserId)) {
9873                    return;
9874                }
9875            }
9876            notifyPackageUseLocked(packageName, reason);
9877        }
9878    }
9879
9880    private void notifyPackageUseLocked(String packageName, int reason) {
9881        final PackageParser.Package p = mPackages.get(packageName);
9882        if (p == null) {
9883            return;
9884        }
9885        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9886    }
9887
9888    @Override
9889    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9890            List<String> classPaths, String loaderIsa) {
9891        int userId = UserHandle.getCallingUserId();
9892        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9893        if (ai == null) {
9894            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9895                + loadingPackageName + ", user=" + userId);
9896            return;
9897        }
9898        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9899    }
9900
9901    @Override
9902    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9903            IDexModuleRegisterCallback callback) {
9904        int userId = UserHandle.getCallingUserId();
9905        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9906        DexManager.RegisterDexModuleResult result;
9907        if (ai == null) {
9908            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9909                     " calling user. package=" + packageName + ", user=" + userId);
9910            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9911        } else {
9912            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9913        }
9914
9915        if (callback != null) {
9916            mHandler.post(() -> {
9917                try {
9918                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9919                } catch (RemoteException e) {
9920                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9921                }
9922            });
9923        }
9924    }
9925
9926    /**
9927     * Ask the package manager to perform a dex-opt with the given compiler filter.
9928     *
9929     * Note: exposed only for the shell command to allow moving packages explicitly to a
9930     *       definite state.
9931     */
9932    @Override
9933    public boolean performDexOptMode(String packageName,
9934            boolean checkProfiles, String targetCompilerFilter, boolean force,
9935            boolean bootComplete, String splitName) {
9936        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9937                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9938                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9939        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9940                splitName, flags));
9941    }
9942
9943    /**
9944     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9945     * secondary dex files belonging to the given package.
9946     *
9947     * Note: exposed only for the shell command to allow moving packages explicitly to a
9948     *       definite state.
9949     */
9950    @Override
9951    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9952            boolean force) {
9953        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9954                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9955                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9956                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9957        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9958    }
9959
9960    /*package*/ boolean performDexOpt(DexoptOptions options) {
9961        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9962            return false;
9963        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9964            return false;
9965        }
9966
9967        if (options.isDexoptOnlySecondaryDex()) {
9968            return mDexManager.dexoptSecondaryDex(options);
9969        } else {
9970            int dexoptStatus = performDexOptWithStatus(options);
9971            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9972        }
9973    }
9974
9975    /**
9976     * Perform dexopt on the given package and return one of following result:
9977     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9978     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9979     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9980     */
9981    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9982        return performDexOptTraced(options);
9983    }
9984
9985    private int performDexOptTraced(DexoptOptions options) {
9986        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9987        try {
9988            return performDexOptInternal(options);
9989        } finally {
9990            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9991        }
9992    }
9993
9994    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9995    // if the package can now be considered up to date for the given filter.
9996    private int performDexOptInternal(DexoptOptions options) {
9997        PackageParser.Package p;
9998        synchronized (mPackages) {
9999            p = mPackages.get(options.getPackageName());
10000            if (p == null) {
10001                // Package could not be found. Report failure.
10002                return PackageDexOptimizer.DEX_OPT_FAILED;
10003            }
10004            mPackageUsage.maybeWriteAsync(mPackages);
10005            mCompilerStats.maybeWriteAsync();
10006        }
10007        long callingId = Binder.clearCallingIdentity();
10008        try {
10009            synchronized (mInstallLock) {
10010                return performDexOptInternalWithDependenciesLI(p, options);
10011            }
10012        } finally {
10013            Binder.restoreCallingIdentity(callingId);
10014        }
10015    }
10016
10017    public ArraySet<String> getOptimizablePackages() {
10018        ArraySet<String> pkgs = new ArraySet<String>();
10019        synchronized (mPackages) {
10020            for (PackageParser.Package p : mPackages.values()) {
10021                if (PackageDexOptimizer.canOptimizePackage(p)) {
10022                    pkgs.add(p.packageName);
10023                }
10024            }
10025        }
10026        return pkgs;
10027    }
10028
10029    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
10030            DexoptOptions options) {
10031        // Select the dex optimizer based on the force parameter.
10032        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
10033        //       allocate an object here.
10034        PackageDexOptimizer pdo = options.isForce()
10035                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
10036                : mPackageDexOptimizer;
10037
10038        // Dexopt all dependencies first. Note: we ignore the return value and march on
10039        // on errors.
10040        // Note that we are going to call performDexOpt on those libraries as many times as
10041        // they are referenced in packages. When we do a batch of performDexOpt (for example
10042        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
10043        // and the first package that uses the library will dexopt it. The
10044        // others will see that the compiled code for the library is up to date.
10045        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
10046        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
10047        if (!deps.isEmpty()) {
10048            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
10049                    options.getCompilerFilter(), options.getSplitName(),
10050                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
10051            for (PackageParser.Package depPackage : deps) {
10052                // TODO: Analyze and investigate if we (should) profile libraries.
10053                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
10054                        getOrCreateCompilerPackageStats(depPackage),
10055                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
10056            }
10057        }
10058        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
10059                getOrCreateCompilerPackageStats(p),
10060                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
10061    }
10062
10063    /**
10064     * Reconcile the information we have about the secondary dex files belonging to
10065     * {@code packagName} and the actual dex files. For all dex files that were
10066     * deleted, update the internal records and delete the generated oat files.
10067     */
10068    @Override
10069    public void reconcileSecondaryDexFiles(String packageName) {
10070        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10071            return;
10072        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
10073            return;
10074        }
10075        mDexManager.reconcileSecondaryDexFiles(packageName);
10076    }
10077
10078    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
10079    // a reference there.
10080    /*package*/ DexManager getDexManager() {
10081        return mDexManager;
10082    }
10083
10084    /**
10085     * Execute the background dexopt job immediately.
10086     */
10087    @Override
10088    public boolean runBackgroundDexoptJob() {
10089        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10090            return false;
10091        }
10092        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
10093    }
10094
10095    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
10096        if (p.usesLibraries != null || p.usesOptionalLibraries != null
10097                || p.usesStaticLibraries != null) {
10098            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
10099            Set<String> collectedNames = new HashSet<>();
10100            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
10101
10102            retValue.remove(p);
10103
10104            return retValue;
10105        } else {
10106            return Collections.emptyList();
10107        }
10108    }
10109
10110    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
10111            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10112        if (!collectedNames.contains(p.packageName)) {
10113            collectedNames.add(p.packageName);
10114            collected.add(p);
10115
10116            if (p.usesLibraries != null) {
10117                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10118                        null, collected, collectedNames);
10119            }
10120            if (p.usesOptionalLibraries != null) {
10121                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10122                        null, collected, collectedNames);
10123            }
10124            if (p.usesStaticLibraries != null) {
10125                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10126                        p.usesStaticLibrariesVersions, collected, collectedNames);
10127            }
10128        }
10129    }
10130
10131    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10132            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10133        final int libNameCount = libs.size();
10134        for (int i = 0; i < libNameCount; i++) {
10135            String libName = libs.get(i);
10136            int version = (versions != null && versions.length == libNameCount)
10137                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10138            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10139            if (libPkg != null) {
10140                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10141            }
10142        }
10143    }
10144
10145    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10146        synchronized (mPackages) {
10147            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10148            if (libEntry != null) {
10149                return mPackages.get(libEntry.apk);
10150            }
10151            return null;
10152        }
10153    }
10154
10155    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10156        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10157        if (versionedLib == null) {
10158            return null;
10159        }
10160        return versionedLib.get(version);
10161    }
10162
10163    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10164        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10165                pkg.staticSharedLibName);
10166        if (versionedLib == null) {
10167            return null;
10168        }
10169        int previousLibVersion = -1;
10170        final int versionCount = versionedLib.size();
10171        for (int i = 0; i < versionCount; i++) {
10172            final int libVersion = versionedLib.keyAt(i);
10173            if (libVersion < pkg.staticSharedLibVersion) {
10174                previousLibVersion = Math.max(previousLibVersion, libVersion);
10175            }
10176        }
10177        if (previousLibVersion >= 0) {
10178            return versionedLib.get(previousLibVersion);
10179        }
10180        return null;
10181    }
10182
10183    public void shutdown() {
10184        mPackageUsage.writeNow(mPackages);
10185        mCompilerStats.writeNow();
10186        mDexManager.writePackageDexUsageNow();
10187    }
10188
10189    @Override
10190    public void dumpProfiles(String packageName) {
10191        PackageParser.Package pkg;
10192        synchronized (mPackages) {
10193            pkg = mPackages.get(packageName);
10194            if (pkg == null) {
10195                throw new IllegalArgumentException("Unknown package: " + packageName);
10196            }
10197        }
10198        /* Only the shell, root, or the app user should be able to dump profiles. */
10199        int callingUid = Binder.getCallingUid();
10200        if (callingUid != Process.SHELL_UID &&
10201            callingUid != Process.ROOT_UID &&
10202            callingUid != pkg.applicationInfo.uid) {
10203            throw new SecurityException("dumpProfiles");
10204        }
10205
10206        synchronized (mInstallLock) {
10207            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10208            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10209            try {
10210                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10211                String codePaths = TextUtils.join(";", allCodePaths);
10212                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10213            } catch (InstallerException e) {
10214                Slog.w(TAG, "Failed to dump profiles", e);
10215            }
10216            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10217        }
10218    }
10219
10220    @Override
10221    public void forceDexOpt(String packageName) {
10222        enforceSystemOrRoot("forceDexOpt");
10223
10224        PackageParser.Package pkg;
10225        synchronized (mPackages) {
10226            pkg = mPackages.get(packageName);
10227            if (pkg == null) {
10228                throw new IllegalArgumentException("Unknown package: " + packageName);
10229            }
10230        }
10231
10232        synchronized (mInstallLock) {
10233            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10234
10235            // Whoever is calling forceDexOpt wants a compiled package.
10236            // Don't use profiles since that may cause compilation to be skipped.
10237            final int res = performDexOptInternalWithDependenciesLI(
10238                    pkg,
10239                    new DexoptOptions(packageName,
10240                            getDefaultCompilerFilter(),
10241                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10242
10243            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10244            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10245                throw new IllegalStateException("Failed to dexopt: " + res);
10246            }
10247        }
10248    }
10249
10250    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10251        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10252            Slog.w(TAG, "Unable to update from " + oldPkg.name
10253                    + " to " + newPkg.packageName
10254                    + ": old package not in system partition");
10255            return false;
10256        } else if (mPackages.get(oldPkg.name) != null) {
10257            Slog.w(TAG, "Unable to update from " + oldPkg.name
10258                    + " to " + newPkg.packageName
10259                    + ": old package still exists");
10260            return false;
10261        }
10262        return true;
10263    }
10264
10265    void removeCodePathLI(File codePath) {
10266        if (codePath.isDirectory()) {
10267            try {
10268                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10269            } catch (InstallerException e) {
10270                Slog.w(TAG, "Failed to remove code path", e);
10271            }
10272        } else {
10273            codePath.delete();
10274        }
10275    }
10276
10277    private int[] resolveUserIds(int userId) {
10278        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10279    }
10280
10281    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10282        if (pkg == null) {
10283            Slog.wtf(TAG, "Package was null!", new Throwable());
10284            return;
10285        }
10286        clearAppDataLeafLIF(pkg, userId, flags);
10287        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10288        for (int i = 0; i < childCount; i++) {
10289            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10290        }
10291    }
10292
10293    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10294        final PackageSetting ps;
10295        synchronized (mPackages) {
10296            ps = mSettings.mPackages.get(pkg.packageName);
10297        }
10298        for (int realUserId : resolveUserIds(userId)) {
10299            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10300            try {
10301                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10302                        ceDataInode);
10303            } catch (InstallerException e) {
10304                Slog.w(TAG, String.valueOf(e));
10305            }
10306        }
10307    }
10308
10309    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10310        if (pkg == null) {
10311            Slog.wtf(TAG, "Package was null!", new Throwable());
10312            return;
10313        }
10314        destroyAppDataLeafLIF(pkg, userId, flags);
10315        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10316        for (int i = 0; i < childCount; i++) {
10317            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10318        }
10319    }
10320
10321    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10322        final PackageSetting ps;
10323        synchronized (mPackages) {
10324            ps = mSettings.mPackages.get(pkg.packageName);
10325        }
10326        for (int realUserId : resolveUserIds(userId)) {
10327            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10328            try {
10329                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10330                        ceDataInode);
10331            } catch (InstallerException e) {
10332                Slog.w(TAG, String.valueOf(e));
10333            }
10334            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10335        }
10336    }
10337
10338    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10339        if (pkg == null) {
10340            Slog.wtf(TAG, "Package was null!", new Throwable());
10341            return;
10342        }
10343        destroyAppProfilesLeafLIF(pkg);
10344        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10345        for (int i = 0; i < childCount; i++) {
10346            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10347        }
10348    }
10349
10350    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10351        try {
10352            mInstaller.destroyAppProfiles(pkg.packageName);
10353        } catch (InstallerException e) {
10354            Slog.w(TAG, String.valueOf(e));
10355        }
10356    }
10357
10358    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10359        if (pkg == null) {
10360            Slog.wtf(TAG, "Package was null!", new Throwable());
10361            return;
10362        }
10363        clearAppProfilesLeafLIF(pkg);
10364        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10365        for (int i = 0; i < childCount; i++) {
10366            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10367        }
10368    }
10369
10370    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10371        try {
10372            mInstaller.clearAppProfiles(pkg.packageName);
10373        } catch (InstallerException e) {
10374            Slog.w(TAG, String.valueOf(e));
10375        }
10376    }
10377
10378    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10379            long lastUpdateTime) {
10380        // Set parent install/update time
10381        PackageSetting ps = (PackageSetting) pkg.mExtras;
10382        if (ps != null) {
10383            ps.firstInstallTime = firstInstallTime;
10384            ps.lastUpdateTime = lastUpdateTime;
10385        }
10386        // Set children install/update time
10387        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10388        for (int i = 0; i < childCount; i++) {
10389            PackageParser.Package childPkg = pkg.childPackages.get(i);
10390            ps = (PackageSetting) childPkg.mExtras;
10391            if (ps != null) {
10392                ps.firstInstallTime = firstInstallTime;
10393                ps.lastUpdateTime = lastUpdateTime;
10394            }
10395        }
10396    }
10397
10398    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10399            PackageParser.Package changingLib) {
10400        if (file.path != null) {
10401            usesLibraryFiles.add(file.path);
10402            return;
10403        }
10404        PackageParser.Package p = mPackages.get(file.apk);
10405        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10406            // If we are doing this while in the middle of updating a library apk,
10407            // then we need to make sure to use that new apk for determining the
10408            // dependencies here.  (We haven't yet finished committing the new apk
10409            // to the package manager state.)
10410            if (p == null || p.packageName.equals(changingLib.packageName)) {
10411                p = changingLib;
10412            }
10413        }
10414        if (p != null) {
10415            usesLibraryFiles.addAll(p.getAllCodePaths());
10416            if (p.usesLibraryFiles != null) {
10417                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10418            }
10419        }
10420    }
10421
10422    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10423            PackageParser.Package changingLib) throws PackageManagerException {
10424        if (pkg == null) {
10425            return;
10426        }
10427        ArraySet<String> usesLibraryFiles = null;
10428        if (pkg.usesLibraries != null) {
10429            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10430                    null, null, pkg.packageName, changingLib, true,
10431                    pkg.applicationInfo.targetSdkVersion, null);
10432        }
10433        if (pkg.usesStaticLibraries != null) {
10434            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10435                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10436                    pkg.packageName, changingLib, true,
10437                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10438        }
10439        if (pkg.usesOptionalLibraries != null) {
10440            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10441                    null, null, pkg.packageName, changingLib, false,
10442                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10443        }
10444        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10445            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10446        } else {
10447            pkg.usesLibraryFiles = null;
10448        }
10449    }
10450
10451    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10452            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
10453            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10454            boolean required, int targetSdk, @Nullable ArraySet<String> outUsedLibraries)
10455            throws PackageManagerException {
10456        final int libCount = requestedLibraries.size();
10457        for (int i = 0; i < libCount; i++) {
10458            final String libName = requestedLibraries.get(i);
10459            final int libVersion = requiredVersions != null ? requiredVersions[i]
10460                    : SharedLibraryInfo.VERSION_UNDEFINED;
10461            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10462            if (libEntry == null) {
10463                if (required) {
10464                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10465                            "Package " + packageName + " requires unavailable shared library "
10466                                    + libName + "; failing!");
10467                } else if (DEBUG_SHARED_LIBRARIES) {
10468                    Slog.i(TAG, "Package " + packageName
10469                            + " desires unavailable shared library "
10470                            + libName + "; ignoring!");
10471                }
10472            } else {
10473                if (requiredVersions != null && requiredCertDigests != null) {
10474                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10475                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10476                            "Package " + packageName + " requires unavailable static shared"
10477                                    + " library " + libName + " version "
10478                                    + libEntry.info.getVersion() + "; failing!");
10479                    }
10480
10481                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10482                    if (libPkg == null) {
10483                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10484                                "Package " + packageName + " requires unavailable static shared"
10485                                        + " library; failing!");
10486                    }
10487
10488                    final String[] expectedCertDigests = requiredCertDigests[i];
10489                    // For apps targeting O MR1 we require explicit enumeration of all certs.
10490                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
10491                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
10492                            : PackageUtils.computeSignaturesSha256Digests(
10493                                    new Signature[]{libPkg.mSignatures[0]});
10494
10495                    // Take a shortcut if sizes don't match. Note that if an app doesn't
10496                    // target O we don't parse the "additional-certificate" tags similarly
10497                    // how we only consider all certs only for apps targeting O (see above).
10498                    // Therefore, the size check is safe to make.
10499                    if (expectedCertDigests.length != libCertDigests.length) {
10500                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10501                                "Package " + packageName + " requires differently signed" +
10502                                        " static sDexLoadReporter.java:45.19hared library; failing!");
10503                    }
10504
10505                    // Use a predictable order as signature order may vary
10506                    Arrays.sort(libCertDigests);
10507                    Arrays.sort(expectedCertDigests);
10508
10509                    final int certCount = libCertDigests.length;
10510                    for (int j = 0; j < certCount; j++) {
10511                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
10512                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10513                                    "Package " + packageName + " requires differently signed" +
10514                                            " static shared library; failing!");
10515                        }
10516                    }
10517                }
10518
10519                if (outUsedLibraries == null) {
10520                    outUsedLibraries = new ArraySet<>();
10521                }
10522                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10523            }
10524        }
10525        return outUsedLibraries;
10526    }
10527
10528    private static boolean hasString(List<String> list, List<String> which) {
10529        if (list == null) {
10530            return false;
10531        }
10532        for (int i=list.size()-1; i>=0; i--) {
10533            for (int j=which.size()-1; j>=0; j--) {
10534                if (which.get(j).equals(list.get(i))) {
10535                    return true;
10536                }
10537            }
10538        }
10539        return false;
10540    }
10541
10542    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10543            PackageParser.Package changingPkg) {
10544        ArrayList<PackageParser.Package> res = null;
10545        for (PackageParser.Package pkg : mPackages.values()) {
10546            if (changingPkg != null
10547                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10548                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10549                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10550                            changingPkg.staticSharedLibName)) {
10551                return null;
10552            }
10553            if (res == null) {
10554                res = new ArrayList<>();
10555            }
10556            res.add(pkg);
10557            try {
10558                updateSharedLibrariesLPr(pkg, changingPkg);
10559            } catch (PackageManagerException e) {
10560                // If a system app update or an app and a required lib missing we
10561                // delete the package and for updated system apps keep the data as
10562                // it is better for the user to reinstall than to be in an limbo
10563                // state. Also libs disappearing under an app should never happen
10564                // - just in case.
10565                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10566                    final int flags = pkg.isUpdatedSystemApp()
10567                            ? PackageManager.DELETE_KEEP_DATA : 0;
10568                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10569                            flags , null, true, null);
10570                }
10571                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10572            }
10573        }
10574        return res;
10575    }
10576
10577    /**
10578     * Derive the value of the {@code cpuAbiOverride} based on the provided
10579     * value and an optional stored value from the package settings.
10580     */
10581    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10582        String cpuAbiOverride = null;
10583
10584        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10585            cpuAbiOverride = null;
10586        } else if (abiOverride != null) {
10587            cpuAbiOverride = abiOverride;
10588        } else if (settings != null) {
10589            cpuAbiOverride = settings.cpuAbiOverrideString;
10590        }
10591
10592        return cpuAbiOverride;
10593    }
10594
10595    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10596            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10597                    throws PackageManagerException {
10598        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10599        // If the package has children and this is the first dive in the function
10600        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10601        // whether all packages (parent and children) would be successfully scanned
10602        // before the actual scan since scanning mutates internal state and we want
10603        // to atomically install the package and its children.
10604        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10605            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10606                scanFlags |= SCAN_CHECK_ONLY;
10607            }
10608        } else {
10609            scanFlags &= ~SCAN_CHECK_ONLY;
10610        }
10611
10612        final PackageParser.Package scannedPkg;
10613        try {
10614            // Scan the parent
10615            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10616            // Scan the children
10617            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10618            for (int i = 0; i < childCount; i++) {
10619                PackageParser.Package childPkg = pkg.childPackages.get(i);
10620                scanPackageLI(childPkg, policyFlags,
10621                        scanFlags, currentTime, user);
10622            }
10623        } finally {
10624            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10625        }
10626
10627        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10628            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10629        }
10630
10631        return scannedPkg;
10632    }
10633
10634    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10635            int scanFlags, long currentTime, @Nullable UserHandle user)
10636                    throws PackageManagerException {
10637        boolean success = false;
10638        try {
10639            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10640                    currentTime, user);
10641            success = true;
10642            return res;
10643        } finally {
10644            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10645                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10646                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10647                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10648                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10649            }
10650        }
10651    }
10652
10653    /**
10654     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10655     */
10656    private static boolean apkHasCode(String fileName) {
10657        StrictJarFile jarFile = null;
10658        try {
10659            jarFile = new StrictJarFile(fileName,
10660                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10661            return jarFile.findEntry("classes.dex") != null;
10662        } catch (IOException ignore) {
10663        } finally {
10664            try {
10665                if (jarFile != null) {
10666                    jarFile.close();
10667                }
10668            } catch (IOException ignore) {}
10669        }
10670        return false;
10671    }
10672
10673    /**
10674     * Enforces code policy for the package. This ensures that if an APK has
10675     * declared hasCode="true" in its manifest that the APK actually contains
10676     * code.
10677     *
10678     * @throws PackageManagerException If bytecode could not be found when it should exist
10679     */
10680    private static void assertCodePolicy(PackageParser.Package pkg)
10681            throws PackageManagerException {
10682        final boolean shouldHaveCode =
10683                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10684        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10685            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10686                    "Package " + pkg.baseCodePath + " code is missing");
10687        }
10688
10689        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10690            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10691                final boolean splitShouldHaveCode =
10692                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10693                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10694                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10695                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10696                }
10697            }
10698        }
10699    }
10700
10701    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10702            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10703                    throws PackageManagerException {
10704        if (DEBUG_PACKAGE_SCANNING) {
10705            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10706                Log.d(TAG, "Scanning package " + pkg.packageName);
10707        }
10708
10709        applyPolicy(pkg, policyFlags);
10710
10711        assertPackageIsValid(pkg, policyFlags, scanFlags);
10712
10713        // Initialize package source and resource directories
10714        final File scanFile = new File(pkg.codePath);
10715        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10716        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10717
10718        SharedUserSetting suid = null;
10719        PackageSetting pkgSetting = null;
10720
10721        // Getting the package setting may have a side-effect, so if we
10722        // are only checking if scan would succeed, stash a copy of the
10723        // old setting to restore at the end.
10724        PackageSetting nonMutatedPs = null;
10725
10726        // We keep references to the derived CPU Abis from settings in oder to reuse
10727        // them in the case where we're not upgrading or booting for the first time.
10728        String primaryCpuAbiFromSettings = null;
10729        String secondaryCpuAbiFromSettings = null;
10730
10731        // writer
10732        synchronized (mPackages) {
10733            if (pkg.mSharedUserId != null) {
10734                // SIDE EFFECTS; may potentially allocate a new shared user
10735                suid = mSettings.getSharedUserLPw(
10736                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10737                if (DEBUG_PACKAGE_SCANNING) {
10738                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10739                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10740                                + "): packages=" + suid.packages);
10741                }
10742            }
10743
10744            // Check if we are renaming from an original package name.
10745            PackageSetting origPackage = null;
10746            String realName = null;
10747            if (pkg.mOriginalPackages != null) {
10748                // This package may need to be renamed to a previously
10749                // installed name.  Let's check on that...
10750                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10751                if (pkg.mOriginalPackages.contains(renamed)) {
10752                    // This package had originally been installed as the
10753                    // original name, and we have already taken care of
10754                    // transitioning to the new one.  Just update the new
10755                    // one to continue using the old name.
10756                    realName = pkg.mRealPackage;
10757                    if (!pkg.packageName.equals(renamed)) {
10758                        // Callers into this function may have already taken
10759                        // care of renaming the package; only do it here if
10760                        // it is not already done.
10761                        pkg.setPackageName(renamed);
10762                    }
10763                } else {
10764                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10765                        if ((origPackage = mSettings.getPackageLPr(
10766                                pkg.mOriginalPackages.get(i))) != null) {
10767                            // We do have the package already installed under its
10768                            // original name...  should we use it?
10769                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10770                                // New package is not compatible with original.
10771                                origPackage = null;
10772                                continue;
10773                            } else if (origPackage.sharedUser != null) {
10774                                // Make sure uid is compatible between packages.
10775                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10776                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10777                                            + " to " + pkg.packageName + ": old uid "
10778                                            + origPackage.sharedUser.name
10779                                            + " differs from " + pkg.mSharedUserId);
10780                                    origPackage = null;
10781                                    continue;
10782                                }
10783                                // TODO: Add case when shared user id is added [b/28144775]
10784                            } else {
10785                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10786                                        + pkg.packageName + " to old name " + origPackage.name);
10787                            }
10788                            break;
10789                        }
10790                    }
10791                }
10792            }
10793
10794            if (mTransferedPackages.contains(pkg.packageName)) {
10795                Slog.w(TAG, "Package " + pkg.packageName
10796                        + " was transferred to another, but its .apk remains");
10797            }
10798
10799            // See comments in nonMutatedPs declaration
10800            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10801                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10802                if (foundPs != null) {
10803                    nonMutatedPs = new PackageSetting(foundPs);
10804                }
10805            }
10806
10807            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10808                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10809                if (foundPs != null) {
10810                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10811                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10812                }
10813            }
10814
10815            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10816            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10817                PackageManagerService.reportSettingsProblem(Log.WARN,
10818                        "Package " + pkg.packageName + " shared user changed from "
10819                                + (pkgSetting.sharedUser != null
10820                                        ? pkgSetting.sharedUser.name : "<nothing>")
10821                                + " to "
10822                                + (suid != null ? suid.name : "<nothing>")
10823                                + "; replacing with new");
10824                pkgSetting = null;
10825            }
10826            final PackageSetting oldPkgSetting =
10827                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10828            final PackageSetting disabledPkgSetting =
10829                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10830
10831            String[] usesStaticLibraries = null;
10832            if (pkg.usesStaticLibraries != null) {
10833                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10834                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10835            }
10836
10837            if (pkgSetting == null) {
10838                final String parentPackageName = (pkg.parentPackage != null)
10839                        ? pkg.parentPackage.packageName : null;
10840                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10841                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10842                // REMOVE SharedUserSetting from method; update in a separate call
10843                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10844                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10845                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10846                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10847                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10848                        true /*allowInstall*/, instantApp, virtualPreload,
10849                        parentPackageName, pkg.getChildPackageNames(),
10850                        UserManagerService.getInstance(), usesStaticLibraries,
10851                        pkg.usesStaticLibrariesVersions);
10852                // SIDE EFFECTS; updates system state; move elsewhere
10853                if (origPackage != null) {
10854                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10855                }
10856                mSettings.addUserToSettingLPw(pkgSetting);
10857            } else {
10858                // REMOVE SharedUserSetting from method; update in a separate call.
10859                //
10860                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10861                // secondaryCpuAbi are not known at this point so we always update them
10862                // to null here, only to reset them at a later point.
10863                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10864                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10865                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10866                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10867                        UserManagerService.getInstance(), usesStaticLibraries,
10868                        pkg.usesStaticLibrariesVersions);
10869            }
10870            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10871            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10872
10873            // SIDE EFFECTS; modifies system state; move elsewhere
10874            if (pkgSetting.origPackage != null) {
10875                // If we are first transitioning from an original package,
10876                // fix up the new package's name now.  We need to do this after
10877                // looking up the package under its new name, so getPackageLP
10878                // can take care of fiddling things correctly.
10879                pkg.setPackageName(origPackage.name);
10880
10881                // File a report about this.
10882                String msg = "New package " + pkgSetting.realName
10883                        + " renamed to replace old package " + pkgSetting.name;
10884                reportSettingsProblem(Log.WARN, msg);
10885
10886                // Make a note of it.
10887                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10888                    mTransferedPackages.add(origPackage.name);
10889                }
10890
10891                // No longer need to retain this.
10892                pkgSetting.origPackage = null;
10893            }
10894
10895            // SIDE EFFECTS; modifies system state; move elsewhere
10896            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10897                // Make a note of it.
10898                mTransferedPackages.add(pkg.packageName);
10899            }
10900
10901            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10902                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10903            }
10904
10905            if ((scanFlags & SCAN_BOOTING) == 0
10906                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10907                // Check all shared libraries and map to their actual file path.
10908                // We only do this here for apps not on a system dir, because those
10909                // are the only ones that can fail an install due to this.  We
10910                // will take care of the system apps by updating all of their
10911                // library paths after the scan is done. Also during the initial
10912                // scan don't update any libs as we do this wholesale after all
10913                // apps are scanned to avoid dependency based scanning.
10914                updateSharedLibrariesLPr(pkg, null);
10915            }
10916
10917            if (mFoundPolicyFile) {
10918                SELinuxMMAC.assignSeInfoValue(pkg);
10919            }
10920            pkg.applicationInfo.uid = pkgSetting.appId;
10921            pkg.mExtras = pkgSetting;
10922
10923
10924            // Static shared libs have same package with different versions where
10925            // we internally use a synthetic package name to allow multiple versions
10926            // of the same package, therefore we need to compare signatures against
10927            // the package setting for the latest library version.
10928            PackageSetting signatureCheckPs = pkgSetting;
10929            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10930                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10931                if (libraryEntry != null) {
10932                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10933                }
10934            }
10935
10936            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10937                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10938                    // We just determined the app is signed correctly, so bring
10939                    // over the latest parsed certs.
10940                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10941                } else {
10942                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10943                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10944                                "Package " + pkg.packageName + " upgrade keys do not match the "
10945                                + "previously installed version");
10946                    } else {
10947                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10948                        String msg = "System package " + pkg.packageName
10949                                + " signature changed; retaining data.";
10950                        reportSettingsProblem(Log.WARN, msg);
10951                    }
10952                }
10953            } else {
10954                try {
10955                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10956                    verifySignaturesLP(signatureCheckPs, pkg);
10957                    // We just determined the app is signed correctly, so bring
10958                    // over the latest parsed certs.
10959                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10960                } catch (PackageManagerException e) {
10961                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10962                        throw e;
10963                    }
10964                    // The signature has changed, but this package is in the system
10965                    // image...  let's recover!
10966                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10967                    // However...  if this package is part of a shared user, but it
10968                    // doesn't match the signature of the shared user, let's fail.
10969                    // What this means is that you can't change the signatures
10970                    // associated with an overall shared user, which doesn't seem all
10971                    // that unreasonable.
10972                    if (signatureCheckPs.sharedUser != null) {
10973                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10974                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10975                            throw new PackageManagerException(
10976                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10977                                    "Signature mismatch for shared user: "
10978                                            + pkgSetting.sharedUser);
10979                        }
10980                    }
10981                    // File a report about this.
10982                    String msg = "System package " + pkg.packageName
10983                            + " signature changed; retaining data.";
10984                    reportSettingsProblem(Log.WARN, msg);
10985                }
10986            }
10987
10988            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10989                // This package wants to adopt ownership of permissions from
10990                // another package.
10991                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10992                    final String origName = pkg.mAdoptPermissions.get(i);
10993                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10994                    if (orig != null) {
10995                        if (verifyPackageUpdateLPr(orig, pkg)) {
10996                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10997                                    + pkg.packageName);
10998                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10999                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
11000                        }
11001                    }
11002                }
11003            }
11004        }
11005
11006        pkg.applicationInfo.processName = fixProcessName(
11007                pkg.applicationInfo.packageName,
11008                pkg.applicationInfo.processName);
11009
11010        if (pkg != mPlatformPackage) {
11011            // Get all of our default paths setup
11012            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
11013        }
11014
11015        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
11016
11017        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
11018            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
11019                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
11020                final boolean extractNativeLibs = !pkg.isLibrary();
11021                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
11022                        mAppLib32InstallDir);
11023                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11024
11025                // Some system apps still use directory structure for native libraries
11026                // in which case we might end up not detecting abi solely based on apk
11027                // structure. Try to detect abi based on directory structure.
11028                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
11029                        pkg.applicationInfo.primaryCpuAbi == null) {
11030                    setBundledAppAbisAndRoots(pkg, pkgSetting);
11031                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11032                }
11033            } else {
11034                // This is not a first boot or an upgrade, don't bother deriving the
11035                // ABI during the scan. Instead, trust the value that was stored in the
11036                // package setting.
11037                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
11038                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
11039
11040                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11041
11042                if (DEBUG_ABI_SELECTION) {
11043                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
11044                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
11045                        pkg.applicationInfo.secondaryCpuAbi);
11046                }
11047            }
11048        } else {
11049            if ((scanFlags & SCAN_MOVE) != 0) {
11050                // We haven't run dex-opt for this move (since we've moved the compiled output too)
11051                // but we already have this packages package info in the PackageSetting. We just
11052                // use that and derive the native library path based on the new codepath.
11053                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
11054                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
11055            }
11056
11057            // Set native library paths again. For moves, the path will be updated based on the
11058            // ABIs we've determined above. For non-moves, the path will be updated based on the
11059            // ABIs we determined during compilation, but the path will depend on the final
11060            // package path (after the rename away from the stage path).
11061            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11062        }
11063
11064        // This is a special case for the "system" package, where the ABI is
11065        // dictated by the zygote configuration (and init.rc). We should keep track
11066        // of this ABI so that we can deal with "normal" applications that run under
11067        // the same UID correctly.
11068        if (mPlatformPackage == pkg) {
11069            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
11070                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
11071        }
11072
11073        // If there's a mismatch between the abi-override in the package setting
11074        // and the abiOverride specified for the install. Warn about this because we
11075        // would've already compiled the app without taking the package setting into
11076        // account.
11077        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
11078            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
11079                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
11080                        " for package " + pkg.packageName);
11081            }
11082        }
11083
11084        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11085        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11086        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
11087
11088        // Copy the derived override back to the parsed package, so that we can
11089        // update the package settings accordingly.
11090        pkg.cpuAbiOverride = cpuAbiOverride;
11091
11092        if (DEBUG_ABI_SELECTION) {
11093            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
11094                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
11095                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
11096        }
11097
11098        // Push the derived path down into PackageSettings so we know what to
11099        // clean up at uninstall time.
11100        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
11101
11102        if (DEBUG_ABI_SELECTION) {
11103            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
11104                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
11105                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
11106        }
11107
11108        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
11109        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
11110            // We don't do this here during boot because we can do it all
11111            // at once after scanning all existing packages.
11112            //
11113            // We also do this *before* we perform dexopt on this package, so that
11114            // we can avoid redundant dexopts, and also to make sure we've got the
11115            // code and package path correct.
11116            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
11117        }
11118
11119        if (mFactoryTest && pkg.requestedPermissions.contains(
11120                android.Manifest.permission.FACTORY_TEST)) {
11121            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
11122        }
11123
11124        if (isSystemApp(pkg)) {
11125            pkgSetting.isOrphaned = true;
11126        }
11127
11128        // Take care of first install / last update times.
11129        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
11130        if (currentTime != 0) {
11131            if (pkgSetting.firstInstallTime == 0) {
11132                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
11133            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11134                pkgSetting.lastUpdateTime = currentTime;
11135            }
11136        } else if (pkgSetting.firstInstallTime == 0) {
11137            // We need *something*.  Take time time stamp of the file.
11138            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11139        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11140            if (scanFileTime != pkgSetting.timeStamp) {
11141                // A package on the system image has changed; consider this
11142                // to be an update.
11143                pkgSetting.lastUpdateTime = scanFileTime;
11144            }
11145        }
11146        pkgSetting.setTimeStamp(scanFileTime);
11147
11148        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11149            if (nonMutatedPs != null) {
11150                synchronized (mPackages) {
11151                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11152                }
11153            }
11154        } else {
11155            final int userId = user == null ? 0 : user.getIdentifier();
11156            // Modify state for the given package setting
11157            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11158                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11159            if (pkgSetting.getInstantApp(userId)) {
11160                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11161            }
11162        }
11163        return pkg;
11164    }
11165
11166    /**
11167     * Applies policy to the parsed package based upon the given policy flags.
11168     * Ensures the package is in a good state.
11169     * <p>
11170     * Implementation detail: This method must NOT have any side effect. It would
11171     * ideally be static, but, it requires locks to read system state.
11172     */
11173    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11174        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11175            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11176            if (pkg.applicationInfo.isDirectBootAware()) {
11177                // we're direct boot aware; set for all components
11178                for (PackageParser.Service s : pkg.services) {
11179                    s.info.encryptionAware = s.info.directBootAware = true;
11180                }
11181                for (PackageParser.Provider p : pkg.providers) {
11182                    p.info.encryptionAware = p.info.directBootAware = true;
11183                }
11184                for (PackageParser.Activity a : pkg.activities) {
11185                    a.info.encryptionAware = a.info.directBootAware = true;
11186                }
11187                for (PackageParser.Activity r : pkg.receivers) {
11188                    r.info.encryptionAware = r.info.directBootAware = true;
11189                }
11190            }
11191            if (compressedFileExists(pkg.codePath)) {
11192                pkg.isStub = true;
11193            }
11194        } else {
11195            // Only allow system apps to be flagged as core apps.
11196            pkg.coreApp = false;
11197            // clear flags not applicable to regular apps
11198            pkg.applicationInfo.privateFlags &=
11199                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11200            pkg.applicationInfo.privateFlags &=
11201                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11202        }
11203        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11204
11205        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11206            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11207        }
11208
11209        if (!isSystemApp(pkg)) {
11210            // Only system apps can use these features.
11211            pkg.mOriginalPackages = null;
11212            pkg.mRealPackage = null;
11213            pkg.mAdoptPermissions = null;
11214        }
11215    }
11216
11217    /**
11218     * Asserts the parsed package is valid according to the given policy. If the
11219     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11220     * <p>
11221     * Implementation detail: This method must NOT have any side effects. It would
11222     * ideally be static, but, it requires locks to read system state.
11223     *
11224     * @throws PackageManagerException If the package fails any of the validation checks
11225     */
11226    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11227            throws PackageManagerException {
11228        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11229            assertCodePolicy(pkg);
11230        }
11231
11232        if (pkg.applicationInfo.getCodePath() == null ||
11233                pkg.applicationInfo.getResourcePath() == null) {
11234            // Bail out. The resource and code paths haven't been set.
11235            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11236                    "Code and resource paths haven't been set correctly");
11237        }
11238
11239        // Make sure we're not adding any bogus keyset info
11240        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11241        ksms.assertScannedPackageValid(pkg);
11242
11243        synchronized (mPackages) {
11244            // The special "android" package can only be defined once
11245            if (pkg.packageName.equals("android")) {
11246                if (mAndroidApplication != null) {
11247                    Slog.w(TAG, "*************************************************");
11248                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11249                    Slog.w(TAG, " codePath=" + pkg.codePath);
11250                    Slog.w(TAG, "*************************************************");
11251                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11252                            "Core android package being redefined.  Skipping.");
11253                }
11254            }
11255
11256            // A package name must be unique; don't allow duplicates
11257            if (mPackages.containsKey(pkg.packageName)) {
11258                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11259                        "Application package " + pkg.packageName
11260                        + " already installed.  Skipping duplicate.");
11261            }
11262
11263            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11264                // Static libs have a synthetic package name containing the version
11265                // but we still want the base name to be unique.
11266                if (mPackages.containsKey(pkg.manifestPackageName)) {
11267                    throw new PackageManagerException(
11268                            "Duplicate static shared lib provider package");
11269                }
11270
11271                // Static shared libraries should have at least O target SDK
11272                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11273                    throw new PackageManagerException(
11274                            "Packages declaring static-shared libs must target O SDK or higher");
11275                }
11276
11277                // Package declaring static a shared lib cannot be instant apps
11278                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11279                    throw new PackageManagerException(
11280                            "Packages declaring static-shared libs cannot be instant apps");
11281                }
11282
11283                // Package declaring static a shared lib cannot be renamed since the package
11284                // name is synthetic and apps can't code around package manager internals.
11285                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11286                    throw new PackageManagerException(
11287                            "Packages declaring static-shared libs cannot be renamed");
11288                }
11289
11290                // Package declaring static a shared lib cannot declare child packages
11291                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11292                    throw new PackageManagerException(
11293                            "Packages declaring static-shared libs cannot have child packages");
11294                }
11295
11296                // Package declaring static a shared lib cannot declare dynamic libs
11297                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11298                    throw new PackageManagerException(
11299                            "Packages declaring static-shared libs cannot declare dynamic libs");
11300                }
11301
11302                // Package declaring static a shared lib cannot declare shared users
11303                if (pkg.mSharedUserId != null) {
11304                    throw new PackageManagerException(
11305                            "Packages declaring static-shared libs cannot declare shared users");
11306                }
11307
11308                // Static shared libs cannot declare activities
11309                if (!pkg.activities.isEmpty()) {
11310                    throw new PackageManagerException(
11311                            "Static shared libs cannot declare activities");
11312                }
11313
11314                // Static shared libs cannot declare services
11315                if (!pkg.services.isEmpty()) {
11316                    throw new PackageManagerException(
11317                            "Static shared libs cannot declare services");
11318                }
11319
11320                // Static shared libs cannot declare providers
11321                if (!pkg.providers.isEmpty()) {
11322                    throw new PackageManagerException(
11323                            "Static shared libs cannot declare content providers");
11324                }
11325
11326                // Static shared libs cannot declare receivers
11327                if (!pkg.receivers.isEmpty()) {
11328                    throw new PackageManagerException(
11329                            "Static shared libs cannot declare broadcast receivers");
11330                }
11331
11332                // Static shared libs cannot declare permission groups
11333                if (!pkg.permissionGroups.isEmpty()) {
11334                    throw new PackageManagerException(
11335                            "Static shared libs cannot declare permission groups");
11336                }
11337
11338                // Static shared libs cannot declare permissions
11339                if (!pkg.permissions.isEmpty()) {
11340                    throw new PackageManagerException(
11341                            "Static shared libs cannot declare permissions");
11342                }
11343
11344                // Static shared libs cannot declare protected broadcasts
11345                if (pkg.protectedBroadcasts != null) {
11346                    throw new PackageManagerException(
11347                            "Static shared libs cannot declare protected broadcasts");
11348                }
11349
11350                // Static shared libs cannot be overlay targets
11351                if (pkg.mOverlayTarget != null) {
11352                    throw new PackageManagerException(
11353                            "Static shared libs cannot be overlay targets");
11354                }
11355
11356                // The version codes must be ordered as lib versions
11357                int minVersionCode = Integer.MIN_VALUE;
11358                int maxVersionCode = Integer.MAX_VALUE;
11359
11360                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11361                        pkg.staticSharedLibName);
11362                if (versionedLib != null) {
11363                    final int versionCount = versionedLib.size();
11364                    for (int i = 0; i < versionCount; i++) {
11365                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11366                        final int libVersionCode = libInfo.getDeclaringPackage()
11367                                .getVersionCode();
11368                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11369                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11370                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11371                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11372                        } else {
11373                            minVersionCode = maxVersionCode = libVersionCode;
11374                            break;
11375                        }
11376                    }
11377                }
11378                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11379                    throw new PackageManagerException("Static shared"
11380                            + " lib version codes must be ordered as lib versions");
11381                }
11382            }
11383
11384            // Only privileged apps and updated privileged apps can add child packages.
11385            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11386                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11387                    throw new PackageManagerException("Only privileged apps can add child "
11388                            + "packages. Ignoring package " + pkg.packageName);
11389                }
11390                final int childCount = pkg.childPackages.size();
11391                for (int i = 0; i < childCount; i++) {
11392                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11393                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11394                            childPkg.packageName)) {
11395                        throw new PackageManagerException("Can't override child of "
11396                                + "another disabled app. Ignoring package " + pkg.packageName);
11397                    }
11398                }
11399            }
11400
11401            // If we're only installing presumed-existing packages, require that the
11402            // scanned APK is both already known and at the path previously established
11403            // for it.  Previously unknown packages we pick up normally, but if we have an
11404            // a priori expectation about this package's install presence, enforce it.
11405            // With a singular exception for new system packages. When an OTA contains
11406            // a new system package, we allow the codepath to change from a system location
11407            // to the user-installed location. If we don't allow this change, any newer,
11408            // user-installed version of the application will be ignored.
11409            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11410                if (mExpectingBetter.containsKey(pkg.packageName)) {
11411                    logCriticalInfo(Log.WARN,
11412                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11413                } else {
11414                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11415                    if (known != null) {
11416                        if (DEBUG_PACKAGE_SCANNING) {
11417                            Log.d(TAG, "Examining " + pkg.codePath
11418                                    + " and requiring known paths " + known.codePathString
11419                                    + " & " + known.resourcePathString);
11420                        }
11421                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11422                                || !pkg.applicationInfo.getResourcePath().equals(
11423                                        known.resourcePathString)) {
11424                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11425                                    "Application package " + pkg.packageName
11426                                    + " found at " + pkg.applicationInfo.getCodePath()
11427                                    + " but expected at " + known.codePathString
11428                                    + "; ignoring.");
11429                        }
11430                    } else {
11431                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11432                                "Application package " + pkg.packageName
11433                                + " not found; ignoring.");
11434                    }
11435                }
11436            }
11437
11438            // Verify that this new package doesn't have any content providers
11439            // that conflict with existing packages.  Only do this if the
11440            // package isn't already installed, since we don't want to break
11441            // things that are installed.
11442            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11443                final int N = pkg.providers.size();
11444                int i;
11445                for (i=0; i<N; i++) {
11446                    PackageParser.Provider p = pkg.providers.get(i);
11447                    if (p.info.authority != null) {
11448                        String names[] = p.info.authority.split(";");
11449                        for (int j = 0; j < names.length; j++) {
11450                            if (mProvidersByAuthority.containsKey(names[j])) {
11451                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11452                                final String otherPackageName =
11453                                        ((other != null && other.getComponentName() != null) ?
11454                                                other.getComponentName().getPackageName() : "?");
11455                                throw new PackageManagerException(
11456                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11457                                        "Can't install because provider name " + names[j]
11458                                                + " (in package " + pkg.applicationInfo.packageName
11459                                                + ") is already used by " + otherPackageName);
11460                            }
11461                        }
11462                    }
11463                }
11464            }
11465        }
11466    }
11467
11468    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11469            int type, String declaringPackageName, int declaringVersionCode) {
11470        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11471        if (versionedLib == null) {
11472            versionedLib = new SparseArray<>();
11473            mSharedLibraries.put(name, versionedLib);
11474            if (type == SharedLibraryInfo.TYPE_STATIC) {
11475                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11476            }
11477        } else if (versionedLib.indexOfKey(version) >= 0) {
11478            return false;
11479        }
11480        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11481                version, type, declaringPackageName, declaringVersionCode);
11482        versionedLib.put(version, libEntry);
11483        return true;
11484    }
11485
11486    private boolean removeSharedLibraryLPw(String name, int version) {
11487        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11488        if (versionedLib == null) {
11489            return false;
11490        }
11491        final int libIdx = versionedLib.indexOfKey(version);
11492        if (libIdx < 0) {
11493            return false;
11494        }
11495        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11496        versionedLib.remove(version);
11497        if (versionedLib.size() <= 0) {
11498            mSharedLibraries.remove(name);
11499            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11500                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11501                        .getPackageName());
11502            }
11503        }
11504        return true;
11505    }
11506
11507    /**
11508     * Adds a scanned package to the system. When this method is finished, the package will
11509     * be available for query, resolution, etc...
11510     */
11511    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11512            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11513        final String pkgName = pkg.packageName;
11514        if (mCustomResolverComponentName != null &&
11515                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11516            setUpCustomResolverActivity(pkg);
11517        }
11518
11519        if (pkg.packageName.equals("android")) {
11520            synchronized (mPackages) {
11521                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11522                    // Set up information for our fall-back user intent resolution activity.
11523                    mPlatformPackage = pkg;
11524                    pkg.mVersionCode = mSdkVersion;
11525                    mAndroidApplication = pkg.applicationInfo;
11526                    if (!mResolverReplaced) {
11527                        mResolveActivity.applicationInfo = mAndroidApplication;
11528                        mResolveActivity.name = ResolverActivity.class.getName();
11529                        mResolveActivity.packageName = mAndroidApplication.packageName;
11530                        mResolveActivity.processName = "system:ui";
11531                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11532                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11533                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11534                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11535                        mResolveActivity.exported = true;
11536                        mResolveActivity.enabled = true;
11537                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11538                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11539                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11540                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11541                                | ActivityInfo.CONFIG_ORIENTATION
11542                                | ActivityInfo.CONFIG_KEYBOARD
11543                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11544                        mResolveInfo.activityInfo = mResolveActivity;
11545                        mResolveInfo.priority = 0;
11546                        mResolveInfo.preferredOrder = 0;
11547                        mResolveInfo.match = 0;
11548                        mResolveComponentName = new ComponentName(
11549                                mAndroidApplication.packageName, mResolveActivity.name);
11550                    }
11551                }
11552            }
11553        }
11554
11555        ArrayList<PackageParser.Package> clientLibPkgs = null;
11556        // writer
11557        synchronized (mPackages) {
11558            boolean hasStaticSharedLibs = false;
11559
11560            // Any app can add new static shared libraries
11561            if (pkg.staticSharedLibName != null) {
11562                // Static shared libs don't allow renaming as they have synthetic package
11563                // names to allow install of multiple versions, so use name from manifest.
11564                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11565                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11566                        pkg.manifestPackageName, pkg.mVersionCode)) {
11567                    hasStaticSharedLibs = true;
11568                } else {
11569                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11570                                + pkg.staticSharedLibName + " already exists; skipping");
11571                }
11572                // Static shared libs cannot be updated once installed since they
11573                // use synthetic package name which includes the version code, so
11574                // not need to update other packages's shared lib dependencies.
11575            }
11576
11577            if (!hasStaticSharedLibs
11578                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11579                // Only system apps can add new dynamic shared libraries.
11580                if (pkg.libraryNames != null) {
11581                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11582                        String name = pkg.libraryNames.get(i);
11583                        boolean allowed = false;
11584                        if (pkg.isUpdatedSystemApp()) {
11585                            // New library entries can only be added through the
11586                            // system image.  This is important to get rid of a lot
11587                            // of nasty edge cases: for example if we allowed a non-
11588                            // system update of the app to add a library, then uninstalling
11589                            // the update would make the library go away, and assumptions
11590                            // we made such as through app install filtering would now
11591                            // have allowed apps on the device which aren't compatible
11592                            // with it.  Better to just have the restriction here, be
11593                            // conservative, and create many fewer cases that can negatively
11594                            // impact the user experience.
11595                            final PackageSetting sysPs = mSettings
11596                                    .getDisabledSystemPkgLPr(pkg.packageName);
11597                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11598                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11599                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11600                                        allowed = true;
11601                                        break;
11602                                    }
11603                                }
11604                            }
11605                        } else {
11606                            allowed = true;
11607                        }
11608                        if (allowed) {
11609                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11610                                    SharedLibraryInfo.VERSION_UNDEFINED,
11611                                    SharedLibraryInfo.TYPE_DYNAMIC,
11612                                    pkg.packageName, pkg.mVersionCode)) {
11613                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11614                                        + name + " already exists; skipping");
11615                            }
11616                        } else {
11617                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11618                                    + name + " that is not declared on system image; skipping");
11619                        }
11620                    }
11621
11622                    if ((scanFlags & SCAN_BOOTING) == 0) {
11623                        // If we are not booting, we need to update any applications
11624                        // that are clients of our shared library.  If we are booting,
11625                        // this will all be done once the scan is complete.
11626                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11627                    }
11628                }
11629            }
11630        }
11631
11632        if ((scanFlags & SCAN_BOOTING) != 0) {
11633            // No apps can run during boot scan, so they don't need to be frozen
11634        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11635            // Caller asked to not kill app, so it's probably not frozen
11636        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11637            // Caller asked us to ignore frozen check for some reason; they
11638            // probably didn't know the package name
11639        } else {
11640            // We're doing major surgery on this package, so it better be frozen
11641            // right now to keep it from launching
11642            checkPackageFrozen(pkgName);
11643        }
11644
11645        // Also need to kill any apps that are dependent on the library.
11646        if (clientLibPkgs != null) {
11647            for (int i=0; i<clientLibPkgs.size(); i++) {
11648                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11649                killApplication(clientPkg.applicationInfo.packageName,
11650                        clientPkg.applicationInfo.uid, "update lib");
11651            }
11652        }
11653
11654        // writer
11655        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11656
11657        synchronized (mPackages) {
11658            // We don't expect installation to fail beyond this point
11659
11660            // Add the new setting to mSettings
11661            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11662            // Add the new setting to mPackages
11663            mPackages.put(pkg.applicationInfo.packageName, pkg);
11664            // Make sure we don't accidentally delete its data.
11665            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11666            while (iter.hasNext()) {
11667                PackageCleanItem item = iter.next();
11668                if (pkgName.equals(item.packageName)) {
11669                    iter.remove();
11670                }
11671            }
11672
11673            // Add the package's KeySets to the global KeySetManagerService
11674            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11675            ksms.addScannedPackageLPw(pkg);
11676
11677            int N = pkg.providers.size();
11678            StringBuilder r = null;
11679            int i;
11680            for (i=0; i<N; i++) {
11681                PackageParser.Provider p = pkg.providers.get(i);
11682                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11683                        p.info.processName);
11684                mProviders.addProvider(p);
11685                p.syncable = p.info.isSyncable;
11686                if (p.info.authority != null) {
11687                    String names[] = p.info.authority.split(";");
11688                    p.info.authority = null;
11689                    for (int j = 0; j < names.length; j++) {
11690                        if (j == 1 && p.syncable) {
11691                            // We only want the first authority for a provider to possibly be
11692                            // syncable, so if we already added this provider using a different
11693                            // authority clear the syncable flag. We copy the provider before
11694                            // changing it because the mProviders object contains a reference
11695                            // to a provider that we don't want to change.
11696                            // Only do this for the second authority since the resulting provider
11697                            // object can be the same for all future authorities for this provider.
11698                            p = new PackageParser.Provider(p);
11699                            p.syncable = false;
11700                        }
11701                        if (!mProvidersByAuthority.containsKey(names[j])) {
11702                            mProvidersByAuthority.put(names[j], p);
11703                            if (p.info.authority == null) {
11704                                p.info.authority = names[j];
11705                            } else {
11706                                p.info.authority = p.info.authority + ";" + names[j];
11707                            }
11708                            if (DEBUG_PACKAGE_SCANNING) {
11709                                if (chatty)
11710                                    Log.d(TAG, "Registered content provider: " + names[j]
11711                                            + ", className = " + p.info.name + ", isSyncable = "
11712                                            + p.info.isSyncable);
11713                            }
11714                        } else {
11715                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11716                            Slog.w(TAG, "Skipping provider name " + names[j] +
11717                                    " (in package " + pkg.applicationInfo.packageName +
11718                                    "): name already used by "
11719                                    + ((other != null && other.getComponentName() != null)
11720                                            ? other.getComponentName().getPackageName() : "?"));
11721                        }
11722                    }
11723                }
11724                if (chatty) {
11725                    if (r == null) {
11726                        r = new StringBuilder(256);
11727                    } else {
11728                        r.append(' ');
11729                    }
11730                    r.append(p.info.name);
11731                }
11732            }
11733            if (r != null) {
11734                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11735            }
11736
11737            N = pkg.services.size();
11738            r = null;
11739            for (i=0; i<N; i++) {
11740                PackageParser.Service s = pkg.services.get(i);
11741                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11742                        s.info.processName);
11743                mServices.addService(s);
11744                if (chatty) {
11745                    if (r == null) {
11746                        r = new StringBuilder(256);
11747                    } else {
11748                        r.append(' ');
11749                    }
11750                    r.append(s.info.name);
11751                }
11752            }
11753            if (r != null) {
11754                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11755            }
11756
11757            N = pkg.receivers.size();
11758            r = null;
11759            for (i=0; i<N; i++) {
11760                PackageParser.Activity a = pkg.receivers.get(i);
11761                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11762                        a.info.processName);
11763                mReceivers.addActivity(a, "receiver");
11764                if (chatty) {
11765                    if (r == null) {
11766                        r = new StringBuilder(256);
11767                    } else {
11768                        r.append(' ');
11769                    }
11770                    r.append(a.info.name);
11771                }
11772            }
11773            if (r != null) {
11774                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11775            }
11776
11777            N = pkg.activities.size();
11778            r = null;
11779            for (i=0; i<N; i++) {
11780                PackageParser.Activity a = pkg.activities.get(i);
11781                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11782                        a.info.processName);
11783                mActivities.addActivity(a, "activity");
11784                if (chatty) {
11785                    if (r == null) {
11786                        r = new StringBuilder(256);
11787                    } else {
11788                        r.append(' ');
11789                    }
11790                    r.append(a.info.name);
11791                }
11792            }
11793            if (r != null) {
11794                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11795            }
11796
11797            N = pkg.permissionGroups.size();
11798            r = null;
11799            for (i=0; i<N; i++) {
11800                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11801                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11802                final String curPackageName = cur == null ? null : cur.info.packageName;
11803                // Dont allow ephemeral apps to define new permission groups.
11804                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11805                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11806                            + pg.info.packageName
11807                            + " ignored: instant apps cannot define new permission groups.");
11808                    continue;
11809                }
11810                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11811                if (cur == null || isPackageUpdate) {
11812                    mPermissionGroups.put(pg.info.name, pg);
11813                    if (chatty) {
11814                        if (r == null) {
11815                            r = new StringBuilder(256);
11816                        } else {
11817                            r.append(' ');
11818                        }
11819                        if (isPackageUpdate) {
11820                            r.append("UPD:");
11821                        }
11822                        r.append(pg.info.name);
11823                    }
11824                } else {
11825                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11826                            + pg.info.packageName + " ignored: original from "
11827                            + cur.info.packageName);
11828                    if (chatty) {
11829                        if (r == null) {
11830                            r = new StringBuilder(256);
11831                        } else {
11832                            r.append(' ');
11833                        }
11834                        r.append("DUP:");
11835                        r.append(pg.info.name);
11836                    }
11837                }
11838            }
11839            if (r != null) {
11840                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11841            }
11842
11843            N = pkg.permissions.size();
11844            r = null;
11845            for (i=0; i<N; i++) {
11846                PackageParser.Permission p = pkg.permissions.get(i);
11847
11848                // Dont allow ephemeral apps to define new permissions.
11849                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11850                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11851                            + p.info.packageName
11852                            + " ignored: instant apps cannot define new permissions.");
11853                    continue;
11854                }
11855
11856                // Assume by default that we did not install this permission into the system.
11857                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11858
11859                // Now that permission groups have a special meaning, we ignore permission
11860                // groups for legacy apps to prevent unexpected behavior. In particular,
11861                // permissions for one app being granted to someone just because they happen
11862                // to be in a group defined by another app (before this had no implications).
11863                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11864                    p.group = mPermissionGroups.get(p.info.group);
11865                    // Warn for a permission in an unknown group.
11866                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11867                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11868                                + p.info.packageName + " in an unknown group " + p.info.group);
11869                    }
11870                }
11871
11872                ArrayMap<String, BasePermission> permissionMap =
11873                        p.tree ? mSettings.mPermissionTrees
11874                                : mSettings.mPermissions;
11875                BasePermission bp = permissionMap.get(p.info.name);
11876
11877                // Allow system apps to redefine non-system permissions
11878                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11879                    final boolean currentOwnerIsSystem = (bp.perm != null
11880                            && isSystemApp(bp.perm.owner));
11881                    if (isSystemApp(p.owner)) {
11882                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11883                            // It's a built-in permission and no owner, take ownership now
11884                            bp.packageSetting = pkgSetting;
11885                            bp.perm = p;
11886                            bp.uid = pkg.applicationInfo.uid;
11887                            bp.sourcePackage = p.info.packageName;
11888                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11889                        } else if (!currentOwnerIsSystem) {
11890                            String msg = "New decl " + p.owner + " of permission  "
11891                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11892                            reportSettingsProblem(Log.WARN, msg);
11893                            bp = null;
11894                        }
11895                    }
11896                }
11897
11898                if (bp == null) {
11899                    bp = new BasePermission(p.info.name, p.info.packageName,
11900                            BasePermission.TYPE_NORMAL);
11901                    permissionMap.put(p.info.name, bp);
11902                }
11903
11904                if (bp.perm == null) {
11905                    if (bp.sourcePackage == null
11906                            || bp.sourcePackage.equals(p.info.packageName)) {
11907                        BasePermission tree = findPermissionTreeLP(p.info.name);
11908                        if (tree == null
11909                                || tree.sourcePackage.equals(p.info.packageName)) {
11910                            bp.packageSetting = pkgSetting;
11911                            bp.perm = p;
11912                            bp.uid = pkg.applicationInfo.uid;
11913                            bp.sourcePackage = p.info.packageName;
11914                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11915                            if (chatty) {
11916                                if (r == null) {
11917                                    r = new StringBuilder(256);
11918                                } else {
11919                                    r.append(' ');
11920                                }
11921                                r.append(p.info.name);
11922                            }
11923                        } else {
11924                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11925                                    + p.info.packageName + " ignored: base tree "
11926                                    + tree.name + " is from package "
11927                                    + tree.sourcePackage);
11928                        }
11929                    } else {
11930                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11931                                + p.info.packageName + " ignored: original from "
11932                                + bp.sourcePackage);
11933                    }
11934                } else if (chatty) {
11935                    if (r == null) {
11936                        r = new StringBuilder(256);
11937                    } else {
11938                        r.append(' ');
11939                    }
11940                    r.append("DUP:");
11941                    r.append(p.info.name);
11942                }
11943                if (bp.perm == p) {
11944                    bp.protectionLevel = p.info.protectionLevel;
11945                }
11946            }
11947
11948            if (r != null) {
11949                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11950            }
11951
11952            N = pkg.instrumentation.size();
11953            r = null;
11954            for (i=0; i<N; i++) {
11955                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11956                a.info.packageName = pkg.applicationInfo.packageName;
11957                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11958                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11959                a.info.splitNames = pkg.splitNames;
11960                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11961                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11962                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11963                a.info.dataDir = pkg.applicationInfo.dataDir;
11964                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11965                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11966                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11967                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11968                mInstrumentation.put(a.getComponentName(), a);
11969                if (chatty) {
11970                    if (r == null) {
11971                        r = new StringBuilder(256);
11972                    } else {
11973                        r.append(' ');
11974                    }
11975                    r.append(a.info.name);
11976                }
11977            }
11978            if (r != null) {
11979                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11980            }
11981
11982            if (pkg.protectedBroadcasts != null) {
11983                N = pkg.protectedBroadcasts.size();
11984                synchronized (mProtectedBroadcasts) {
11985                    for (i = 0; i < N; i++) {
11986                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11987                    }
11988                }
11989            }
11990        }
11991
11992        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11993    }
11994
11995    /**
11996     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11997     * is derived purely on the basis of the contents of {@code scanFile} and
11998     * {@code cpuAbiOverride}.
11999     *
12000     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
12001     */
12002    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
12003                                 String cpuAbiOverride, boolean extractLibs,
12004                                 File appLib32InstallDir)
12005            throws PackageManagerException {
12006        // Give ourselves some initial paths; we'll come back for another
12007        // pass once we've determined ABI below.
12008        setNativeLibraryPaths(pkg, appLib32InstallDir);
12009
12010        // We would never need to extract libs for forward-locked and external packages,
12011        // since the container service will do it for us. We shouldn't attempt to
12012        // extract libs from system app when it was not updated.
12013        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
12014                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
12015            extractLibs = false;
12016        }
12017
12018        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
12019        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
12020
12021        NativeLibraryHelper.Handle handle = null;
12022        try {
12023            handle = NativeLibraryHelper.Handle.create(pkg);
12024            // TODO(multiArch): This can be null for apps that didn't go through the
12025            // usual installation process. We can calculate it again, like we
12026            // do during install time.
12027            //
12028            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
12029            // unnecessary.
12030            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
12031
12032            // Null out the abis so that they can be recalculated.
12033            pkg.applicationInfo.primaryCpuAbi = null;
12034            pkg.applicationInfo.secondaryCpuAbi = null;
12035            if (isMultiArch(pkg.applicationInfo)) {
12036                // Warn if we've set an abiOverride for multi-lib packages..
12037                // By definition, we need to copy both 32 and 64 bit libraries for
12038                // such packages.
12039                if (pkg.cpuAbiOverride != null
12040                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
12041                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
12042                }
12043
12044                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
12045                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
12046                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
12047                    if (extractLibs) {
12048                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12049                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12050                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
12051                                useIsaSpecificSubdirs);
12052                    } else {
12053                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12054                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
12055                    }
12056                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12057                }
12058
12059                // Shared library native code should be in the APK zip aligned
12060                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
12061                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12062                            "Shared library native lib extraction not supported");
12063                }
12064
12065                maybeThrowExceptionForMultiArchCopy(
12066                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
12067
12068                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
12069                    if (extractLibs) {
12070                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12071                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12072                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
12073                                useIsaSpecificSubdirs);
12074                    } else {
12075                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12076                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
12077                    }
12078                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12079                }
12080
12081                maybeThrowExceptionForMultiArchCopy(
12082                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
12083
12084                if (abi64 >= 0) {
12085                    // Shared library native libs should be in the APK zip aligned
12086                    if (extractLibs && pkg.isLibrary()) {
12087                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12088                                "Shared library native lib extraction not supported");
12089                    }
12090                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
12091                }
12092
12093                if (abi32 >= 0) {
12094                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
12095                    if (abi64 >= 0) {
12096                        if (pkg.use32bitAbi) {
12097                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
12098                            pkg.applicationInfo.primaryCpuAbi = abi;
12099                        } else {
12100                            pkg.applicationInfo.secondaryCpuAbi = abi;
12101                        }
12102                    } else {
12103                        pkg.applicationInfo.primaryCpuAbi = abi;
12104                    }
12105                }
12106            } else {
12107                String[] abiList = (cpuAbiOverride != null) ?
12108                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
12109
12110                // Enable gross and lame hacks for apps that are built with old
12111                // SDK tools. We must scan their APKs for renderscript bitcode and
12112                // not launch them if it's present. Don't bother checking on devices
12113                // that don't have 64 bit support.
12114                boolean needsRenderScriptOverride = false;
12115                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
12116                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
12117                    abiList = Build.SUPPORTED_32_BIT_ABIS;
12118                    needsRenderScriptOverride = true;
12119                }
12120
12121                final int copyRet;
12122                if (extractLibs) {
12123                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12124                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12125                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
12126                } else {
12127                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12128                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
12129                }
12130                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12131
12132                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
12133                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12134                            "Error unpackaging native libs for app, errorCode=" + copyRet);
12135                }
12136
12137                if (copyRet >= 0) {
12138                    // Shared libraries that have native libs must be multi-architecture
12139                    if (pkg.isLibrary()) {
12140                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12141                                "Shared library with native libs must be multiarch");
12142                    }
12143                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12144                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12145                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12146                } else if (needsRenderScriptOverride) {
12147                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
12148                }
12149            }
12150        } catch (IOException ioe) {
12151            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12152        } finally {
12153            IoUtils.closeQuietly(handle);
12154        }
12155
12156        // Now that we've calculated the ABIs and determined if it's an internal app,
12157        // we will go ahead and populate the nativeLibraryPath.
12158        setNativeLibraryPaths(pkg, appLib32InstallDir);
12159    }
12160
12161    /**
12162     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12163     * i.e, so that all packages can be run inside a single process if required.
12164     *
12165     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12166     * this function will either try and make the ABI for all packages in {@code packagesForUser}
12167     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12168     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12169     * updating a package that belongs to a shared user.
12170     *
12171     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12172     * adds unnecessary complexity.
12173     */
12174    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
12175            PackageParser.Package scannedPackage) {
12176        String requiredInstructionSet = null;
12177        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12178            requiredInstructionSet = VMRuntime.getInstructionSet(
12179                     scannedPackage.applicationInfo.primaryCpuAbi);
12180        }
12181
12182        PackageSetting requirer = null;
12183        for (PackageSetting ps : packagesForUser) {
12184            // If packagesForUser contains scannedPackage, we skip it. This will happen
12185            // when scannedPackage is an update of an existing package. Without this check,
12186            // we will never be able to change the ABI of any package belonging to a shared
12187            // user, even if it's compatible with other packages.
12188            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12189                if (ps.primaryCpuAbiString == null) {
12190                    continue;
12191                }
12192
12193                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12194                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12195                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12196                    // this but there's not much we can do.
12197                    String errorMessage = "Instruction set mismatch, "
12198                            + ((requirer == null) ? "[caller]" : requirer)
12199                            + " requires " + requiredInstructionSet + " whereas " + ps
12200                            + " requires " + instructionSet;
12201                    Slog.w(TAG, errorMessage);
12202                }
12203
12204                if (requiredInstructionSet == null) {
12205                    requiredInstructionSet = instructionSet;
12206                    requirer = ps;
12207                }
12208            }
12209        }
12210
12211        if (requiredInstructionSet != null) {
12212            String adjustedAbi;
12213            if (requirer != null) {
12214                // requirer != null implies that either scannedPackage was null or that scannedPackage
12215                // did not require an ABI, in which case we have to adjust scannedPackage to match
12216                // the ABI of the set (which is the same as requirer's ABI)
12217                adjustedAbi = requirer.primaryCpuAbiString;
12218                if (scannedPackage != null) {
12219                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12220                }
12221            } else {
12222                // requirer == null implies that we're updating all ABIs in the set to
12223                // match scannedPackage.
12224                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12225            }
12226
12227            for (PackageSetting ps : packagesForUser) {
12228                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12229                    if (ps.primaryCpuAbiString != null) {
12230                        continue;
12231                    }
12232
12233                    ps.primaryCpuAbiString = adjustedAbi;
12234                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12235                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12236                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12237                        if (DEBUG_ABI_SELECTION) {
12238                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12239                                    + " (requirer="
12240                                    + (requirer != null ? requirer.pkg : "null")
12241                                    + ", scannedPackage="
12242                                    + (scannedPackage != null ? scannedPackage : "null")
12243                                    + ")");
12244                        }
12245                        try {
12246                            mInstaller.rmdex(ps.codePathString,
12247                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12248                        } catch (InstallerException ignored) {
12249                        }
12250                    }
12251                }
12252            }
12253        }
12254    }
12255
12256    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12257        synchronized (mPackages) {
12258            mResolverReplaced = true;
12259            // Set up information for custom user intent resolution activity.
12260            mResolveActivity.applicationInfo = pkg.applicationInfo;
12261            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12262            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12263            mResolveActivity.processName = pkg.applicationInfo.packageName;
12264            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12265            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12266                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12267            mResolveActivity.theme = 0;
12268            mResolveActivity.exported = true;
12269            mResolveActivity.enabled = true;
12270            mResolveInfo.activityInfo = mResolveActivity;
12271            mResolveInfo.priority = 0;
12272            mResolveInfo.preferredOrder = 0;
12273            mResolveInfo.match = 0;
12274            mResolveComponentName = mCustomResolverComponentName;
12275            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12276                    mResolveComponentName);
12277        }
12278    }
12279
12280    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12281        if (installerActivity == null) {
12282            if (DEBUG_EPHEMERAL) {
12283                Slog.d(TAG, "Clear ephemeral installer activity");
12284            }
12285            mInstantAppInstallerActivity = null;
12286            return;
12287        }
12288
12289        if (DEBUG_EPHEMERAL) {
12290            Slog.d(TAG, "Set ephemeral installer activity: "
12291                    + installerActivity.getComponentName());
12292        }
12293        // Set up information for ephemeral installer activity
12294        mInstantAppInstallerActivity = installerActivity;
12295        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12296                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12297        mInstantAppInstallerActivity.exported = true;
12298        mInstantAppInstallerActivity.enabled = true;
12299        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12300        mInstantAppInstallerInfo.priority = 0;
12301        mInstantAppInstallerInfo.preferredOrder = 1;
12302        mInstantAppInstallerInfo.isDefault = true;
12303        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12304                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12305    }
12306
12307    private static String calculateBundledApkRoot(final String codePathString) {
12308        final File codePath = new File(codePathString);
12309        final File codeRoot;
12310        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12311            codeRoot = Environment.getRootDirectory();
12312        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12313            codeRoot = Environment.getOemDirectory();
12314        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12315            codeRoot = Environment.getVendorDirectory();
12316        } else {
12317            // Unrecognized code path; take its top real segment as the apk root:
12318            // e.g. /something/app/blah.apk => /something
12319            try {
12320                File f = codePath.getCanonicalFile();
12321                File parent = f.getParentFile();    // non-null because codePath is a file
12322                File tmp;
12323                while ((tmp = parent.getParentFile()) != null) {
12324                    f = parent;
12325                    parent = tmp;
12326                }
12327                codeRoot = f;
12328                Slog.w(TAG, "Unrecognized code path "
12329                        + codePath + " - using " + codeRoot);
12330            } catch (IOException e) {
12331                // Can't canonicalize the code path -- shenanigans?
12332                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12333                return Environment.getRootDirectory().getPath();
12334            }
12335        }
12336        return codeRoot.getPath();
12337    }
12338
12339    /**
12340     * Derive and set the location of native libraries for the given package,
12341     * which varies depending on where and how the package was installed.
12342     */
12343    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12344        final ApplicationInfo info = pkg.applicationInfo;
12345        final String codePath = pkg.codePath;
12346        final File codeFile = new File(codePath);
12347        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12348        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12349
12350        info.nativeLibraryRootDir = null;
12351        info.nativeLibraryRootRequiresIsa = false;
12352        info.nativeLibraryDir = null;
12353        info.secondaryNativeLibraryDir = null;
12354
12355        if (isApkFile(codeFile)) {
12356            // Monolithic install
12357            if (bundledApp) {
12358                // If "/system/lib64/apkname" exists, assume that is the per-package
12359                // native library directory to use; otherwise use "/system/lib/apkname".
12360                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12361                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12362                        getPrimaryInstructionSet(info));
12363
12364                // This is a bundled system app so choose the path based on the ABI.
12365                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12366                // is just the default path.
12367                final String apkName = deriveCodePathName(codePath);
12368                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12369                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12370                        apkName).getAbsolutePath();
12371
12372                if (info.secondaryCpuAbi != null) {
12373                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12374                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12375                            secondaryLibDir, apkName).getAbsolutePath();
12376                }
12377            } else if (asecApp) {
12378                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12379                        .getAbsolutePath();
12380            } else {
12381                final String apkName = deriveCodePathName(codePath);
12382                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12383                        .getAbsolutePath();
12384            }
12385
12386            info.nativeLibraryRootRequiresIsa = false;
12387            info.nativeLibraryDir = info.nativeLibraryRootDir;
12388        } else {
12389            // Cluster install
12390            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12391            info.nativeLibraryRootRequiresIsa = true;
12392
12393            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12394                    getPrimaryInstructionSet(info)).getAbsolutePath();
12395
12396            if (info.secondaryCpuAbi != null) {
12397                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12398                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12399            }
12400        }
12401    }
12402
12403    /**
12404     * Calculate the abis and roots for a bundled app. These can uniquely
12405     * be determined from the contents of the system partition, i.e whether
12406     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12407     * of this information, and instead assume that the system was built
12408     * sensibly.
12409     */
12410    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12411                                           PackageSetting pkgSetting) {
12412        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12413
12414        // If "/system/lib64/apkname" exists, assume that is the per-package
12415        // native library directory to use; otherwise use "/system/lib/apkname".
12416        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12417        setBundledAppAbi(pkg, apkRoot, apkName);
12418        // pkgSetting might be null during rescan following uninstall of updates
12419        // to a bundled app, so accommodate that possibility.  The settings in
12420        // that case will be established later from the parsed package.
12421        //
12422        // If the settings aren't null, sync them up with what we've just derived.
12423        // note that apkRoot isn't stored in the package settings.
12424        if (pkgSetting != null) {
12425            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12426            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12427        }
12428    }
12429
12430    /**
12431     * Deduces the ABI of a bundled app and sets the relevant fields on the
12432     * parsed pkg object.
12433     *
12434     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12435     *        under which system libraries are installed.
12436     * @param apkName the name of the installed package.
12437     */
12438    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12439        final File codeFile = new File(pkg.codePath);
12440
12441        final boolean has64BitLibs;
12442        final boolean has32BitLibs;
12443        if (isApkFile(codeFile)) {
12444            // Monolithic install
12445            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12446            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12447        } else {
12448            // Cluster install
12449            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12450            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12451                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12452                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12453                has64BitLibs = (new File(rootDir, isa)).exists();
12454            } else {
12455                has64BitLibs = false;
12456            }
12457            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12458                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12459                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12460                has32BitLibs = (new File(rootDir, isa)).exists();
12461            } else {
12462                has32BitLibs = false;
12463            }
12464        }
12465
12466        if (has64BitLibs && !has32BitLibs) {
12467            // The package has 64 bit libs, but not 32 bit libs. Its primary
12468            // ABI should be 64 bit. We can safely assume here that the bundled
12469            // native libraries correspond to the most preferred ABI in the list.
12470
12471            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12472            pkg.applicationInfo.secondaryCpuAbi = null;
12473        } else if (has32BitLibs && !has64BitLibs) {
12474            // The package has 32 bit libs but not 64 bit libs. Its primary
12475            // ABI should be 32 bit.
12476
12477            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12478            pkg.applicationInfo.secondaryCpuAbi = null;
12479        } else if (has32BitLibs && has64BitLibs) {
12480            // The application has both 64 and 32 bit bundled libraries. We check
12481            // here that the app declares multiArch support, and warn if it doesn't.
12482            //
12483            // We will be lenient here and record both ABIs. The primary will be the
12484            // ABI that's higher on the list, i.e, a device that's configured to prefer
12485            // 64 bit apps will see a 64 bit primary ABI,
12486
12487            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12488                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12489            }
12490
12491            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12492                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12493                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12494            } else {
12495                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12496                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12497            }
12498        } else {
12499            pkg.applicationInfo.primaryCpuAbi = null;
12500            pkg.applicationInfo.secondaryCpuAbi = null;
12501        }
12502    }
12503
12504    private void killApplication(String pkgName, int appId, String reason) {
12505        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12506    }
12507
12508    private void killApplication(String pkgName, int appId, int userId, String reason) {
12509        // Request the ActivityManager to kill the process(only for existing packages)
12510        // so that we do not end up in a confused state while the user is still using the older
12511        // version of the application while the new one gets installed.
12512        final long token = Binder.clearCallingIdentity();
12513        try {
12514            IActivityManager am = ActivityManager.getService();
12515            if (am != null) {
12516                try {
12517                    am.killApplication(pkgName, appId, userId, reason);
12518                } catch (RemoteException e) {
12519                }
12520            }
12521        } finally {
12522            Binder.restoreCallingIdentity(token);
12523        }
12524    }
12525
12526    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12527        // Remove the parent package setting
12528        PackageSetting ps = (PackageSetting) pkg.mExtras;
12529        if (ps != null) {
12530            removePackageLI(ps, chatty);
12531        }
12532        // Remove the child package setting
12533        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12534        for (int i = 0; i < childCount; i++) {
12535            PackageParser.Package childPkg = pkg.childPackages.get(i);
12536            ps = (PackageSetting) childPkg.mExtras;
12537            if (ps != null) {
12538                removePackageLI(ps, chatty);
12539            }
12540        }
12541    }
12542
12543    void removePackageLI(PackageSetting ps, boolean chatty) {
12544        if (DEBUG_INSTALL) {
12545            if (chatty)
12546                Log.d(TAG, "Removing package " + ps.name);
12547        }
12548
12549        // writer
12550        synchronized (mPackages) {
12551            mPackages.remove(ps.name);
12552            final PackageParser.Package pkg = ps.pkg;
12553            if (pkg != null) {
12554                cleanPackageDataStructuresLILPw(pkg, chatty);
12555            }
12556        }
12557    }
12558
12559    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12560        if (DEBUG_INSTALL) {
12561            if (chatty)
12562                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12563        }
12564
12565        // writer
12566        synchronized (mPackages) {
12567            // Remove the parent package
12568            mPackages.remove(pkg.applicationInfo.packageName);
12569            cleanPackageDataStructuresLILPw(pkg, chatty);
12570
12571            // Remove the child packages
12572            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12573            for (int i = 0; i < childCount; i++) {
12574                PackageParser.Package childPkg = pkg.childPackages.get(i);
12575                mPackages.remove(childPkg.applicationInfo.packageName);
12576                cleanPackageDataStructuresLILPw(childPkg, chatty);
12577            }
12578        }
12579    }
12580
12581    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12582        int N = pkg.providers.size();
12583        StringBuilder r = null;
12584        int i;
12585        for (i=0; i<N; i++) {
12586            PackageParser.Provider p = pkg.providers.get(i);
12587            mProviders.removeProvider(p);
12588            if (p.info.authority == null) {
12589
12590                /* There was another ContentProvider with this authority when
12591                 * this app was installed so this authority is null,
12592                 * Ignore it as we don't have to unregister the provider.
12593                 */
12594                continue;
12595            }
12596            String names[] = p.info.authority.split(";");
12597            for (int j = 0; j < names.length; j++) {
12598                if (mProvidersByAuthority.get(names[j]) == p) {
12599                    mProvidersByAuthority.remove(names[j]);
12600                    if (DEBUG_REMOVE) {
12601                        if (chatty)
12602                            Log.d(TAG, "Unregistered content provider: " + names[j]
12603                                    + ", className = " + p.info.name + ", isSyncable = "
12604                                    + p.info.isSyncable);
12605                    }
12606                }
12607            }
12608            if (DEBUG_REMOVE && chatty) {
12609                if (r == null) {
12610                    r = new StringBuilder(256);
12611                } else {
12612                    r.append(' ');
12613                }
12614                r.append(p.info.name);
12615            }
12616        }
12617        if (r != null) {
12618            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12619        }
12620
12621        N = pkg.services.size();
12622        r = null;
12623        for (i=0; i<N; i++) {
12624            PackageParser.Service s = pkg.services.get(i);
12625            mServices.removeService(s);
12626            if (chatty) {
12627                if (r == null) {
12628                    r = new StringBuilder(256);
12629                } else {
12630                    r.append(' ');
12631                }
12632                r.append(s.info.name);
12633            }
12634        }
12635        if (r != null) {
12636            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12637        }
12638
12639        N = pkg.receivers.size();
12640        r = null;
12641        for (i=0; i<N; i++) {
12642            PackageParser.Activity a = pkg.receivers.get(i);
12643            mReceivers.removeActivity(a, "receiver");
12644            if (DEBUG_REMOVE && chatty) {
12645                if (r == null) {
12646                    r = new StringBuilder(256);
12647                } else {
12648                    r.append(' ');
12649                }
12650                r.append(a.info.name);
12651            }
12652        }
12653        if (r != null) {
12654            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12655        }
12656
12657        N = pkg.activities.size();
12658        r = null;
12659        for (i=0; i<N; i++) {
12660            PackageParser.Activity a = pkg.activities.get(i);
12661            mActivities.removeActivity(a, "activity");
12662            if (DEBUG_REMOVE && chatty) {
12663                if (r == null) {
12664                    r = new StringBuilder(256);
12665                } else {
12666                    r.append(' ');
12667                }
12668                r.append(a.info.name);
12669            }
12670        }
12671        if (r != null) {
12672            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12673        }
12674
12675        N = pkg.permissions.size();
12676        r = null;
12677        for (i=0; i<N; i++) {
12678            PackageParser.Permission p = pkg.permissions.get(i);
12679            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12680            if (bp == null) {
12681                bp = mSettings.mPermissionTrees.get(p.info.name);
12682            }
12683            if (bp != null && bp.perm == p) {
12684                bp.perm = null;
12685                if (DEBUG_REMOVE && chatty) {
12686                    if (r == null) {
12687                        r = new StringBuilder(256);
12688                    } else {
12689                        r.append(' ');
12690                    }
12691                    r.append(p.info.name);
12692                }
12693            }
12694            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12695                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12696                if (appOpPkgs != null) {
12697                    appOpPkgs.remove(pkg.packageName);
12698                }
12699            }
12700        }
12701        if (r != null) {
12702            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12703        }
12704
12705        N = pkg.requestedPermissions.size();
12706        r = null;
12707        for (i=0; i<N; i++) {
12708            String perm = pkg.requestedPermissions.get(i);
12709            BasePermission bp = mSettings.mPermissions.get(perm);
12710            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12711                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12712                if (appOpPkgs != null) {
12713                    appOpPkgs.remove(pkg.packageName);
12714                    if (appOpPkgs.isEmpty()) {
12715                        mAppOpPermissionPackages.remove(perm);
12716                    }
12717                }
12718            }
12719        }
12720        if (r != null) {
12721            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12722        }
12723
12724        N = pkg.instrumentation.size();
12725        r = null;
12726        for (i=0; i<N; i++) {
12727            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12728            mInstrumentation.remove(a.getComponentName());
12729            if (DEBUG_REMOVE && chatty) {
12730                if (r == null) {
12731                    r = new StringBuilder(256);
12732                } else {
12733                    r.append(' ');
12734                }
12735                r.append(a.info.name);
12736            }
12737        }
12738        if (r != null) {
12739            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12740        }
12741
12742        r = null;
12743        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12744            // Only system apps can hold shared libraries.
12745            if (pkg.libraryNames != null) {
12746                for (i = 0; i < pkg.libraryNames.size(); i++) {
12747                    String name = pkg.libraryNames.get(i);
12748                    if (removeSharedLibraryLPw(name, 0)) {
12749                        if (DEBUG_REMOVE && chatty) {
12750                            if (r == null) {
12751                                r = new StringBuilder(256);
12752                            } else {
12753                                r.append(' ');
12754                            }
12755                            r.append(name);
12756                        }
12757                    }
12758                }
12759            }
12760        }
12761
12762        r = null;
12763
12764        // Any package can hold static shared libraries.
12765        if (pkg.staticSharedLibName != null) {
12766            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12767                if (DEBUG_REMOVE && chatty) {
12768                    if (r == null) {
12769                        r = new StringBuilder(256);
12770                    } else {
12771                        r.append(' ');
12772                    }
12773                    r.append(pkg.staticSharedLibName);
12774                }
12775            }
12776        }
12777
12778        if (r != null) {
12779            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12780        }
12781    }
12782
12783    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12784        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12785            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12786                return true;
12787            }
12788        }
12789        return false;
12790    }
12791
12792    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12793    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12794    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12795
12796    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12797        // Update the parent permissions
12798        updatePermissionsLPw(pkg.packageName, pkg, flags);
12799        // Update the child permissions
12800        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12801        for (int i = 0; i < childCount; i++) {
12802            PackageParser.Package childPkg = pkg.childPackages.get(i);
12803            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12804        }
12805    }
12806
12807    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12808            int flags) {
12809        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12810        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12811    }
12812
12813    private void updatePermissionsLPw(String changingPkg,
12814            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12815        // Make sure there are no dangling permission trees.
12816        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12817        while (it.hasNext()) {
12818            final BasePermission bp = it.next();
12819            if (bp.packageSetting == null) {
12820                // We may not yet have parsed the package, so just see if
12821                // we still know about its settings.
12822                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12823            }
12824            if (bp.packageSetting == null) {
12825                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12826                        + " from package " + bp.sourcePackage);
12827                it.remove();
12828            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12829                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12830                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12831                            + " from package " + bp.sourcePackage);
12832                    flags |= UPDATE_PERMISSIONS_ALL;
12833                    it.remove();
12834                }
12835            }
12836        }
12837
12838        // Make sure all dynamic permissions have been assigned to a package,
12839        // and make sure there are no dangling permissions.
12840        it = mSettings.mPermissions.values().iterator();
12841        while (it.hasNext()) {
12842            final BasePermission bp = it.next();
12843            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12844                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12845                        + bp.name + " pkg=" + bp.sourcePackage
12846                        + " info=" + bp.pendingInfo);
12847                if (bp.packageSetting == null && bp.pendingInfo != null) {
12848                    final BasePermission tree = findPermissionTreeLP(bp.name);
12849                    if (tree != null && tree.perm != null) {
12850                        bp.packageSetting = tree.packageSetting;
12851                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12852                                new PermissionInfo(bp.pendingInfo));
12853                        bp.perm.info.packageName = tree.perm.info.packageName;
12854                        bp.perm.info.name = bp.name;
12855                        bp.uid = tree.uid;
12856                    }
12857                }
12858            }
12859            if (bp.packageSetting == null) {
12860                // We may not yet have parsed the package, so just see if
12861                // we still know about its settings.
12862                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12863            }
12864            if (bp.packageSetting == null) {
12865                Slog.w(TAG, "Removing dangling permission: " + bp.name
12866                        + " from package " + bp.sourcePackage);
12867                it.remove();
12868            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12869                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12870                    Slog.i(TAG, "Removing old permission: " + bp.name
12871                            + " from package " + bp.sourcePackage);
12872                    flags |= UPDATE_PERMISSIONS_ALL;
12873                    it.remove();
12874                }
12875            }
12876        }
12877
12878        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12879        // Now update the permissions for all packages, in particular
12880        // replace the granted permissions of the system packages.
12881        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12882            for (PackageParser.Package pkg : mPackages.values()) {
12883                if (pkg != pkgInfo) {
12884                    // Only replace for packages on requested volume
12885                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12886                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12887                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12888                    grantPermissionsLPw(pkg, replace, changingPkg);
12889                }
12890            }
12891        }
12892
12893        if (pkgInfo != null) {
12894            // Only replace for packages on requested volume
12895            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12896            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12897                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12898            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12899        }
12900        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12901    }
12902
12903    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12904            String packageOfInterest) {
12905        // IMPORTANT: There are two types of permissions: install and runtime.
12906        // Install time permissions are granted when the app is installed to
12907        // all device users and users added in the future. Runtime permissions
12908        // are granted at runtime explicitly to specific users. Normal and signature
12909        // protected permissions are install time permissions. Dangerous permissions
12910        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12911        // otherwise they are runtime permissions. This function does not manage
12912        // runtime permissions except for the case an app targeting Lollipop MR1
12913        // being upgraded to target a newer SDK, in which case dangerous permissions
12914        // are transformed from install time to runtime ones.
12915
12916        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12917        if (ps == null) {
12918            return;
12919        }
12920
12921        PermissionsState permissionsState = ps.getPermissionsState();
12922        PermissionsState origPermissions = permissionsState;
12923
12924        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12925
12926        boolean runtimePermissionsRevoked = false;
12927        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12928
12929        boolean changedInstallPermission = false;
12930
12931        if (replace) {
12932            ps.installPermissionsFixed = false;
12933            if (!ps.isSharedUser()) {
12934                origPermissions = new PermissionsState(permissionsState);
12935                permissionsState.reset();
12936            } else {
12937                // We need to know only about runtime permission changes since the
12938                // calling code always writes the install permissions state but
12939                // the runtime ones are written only if changed. The only cases of
12940                // changed runtime permissions here are promotion of an install to
12941                // runtime and revocation of a runtime from a shared user.
12942                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12943                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12944                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12945                    runtimePermissionsRevoked = true;
12946                }
12947            }
12948        }
12949
12950        permissionsState.setGlobalGids(mGlobalGids);
12951
12952        final int N = pkg.requestedPermissions.size();
12953        for (int i=0; i<N; i++) {
12954            final String name = pkg.requestedPermissions.get(i);
12955            final BasePermission bp = mSettings.mPermissions.get(name);
12956            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12957                    >= Build.VERSION_CODES.M;
12958
12959            if (DEBUG_INSTALL) {
12960                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12961            }
12962
12963            if (bp == null || bp.packageSetting == null) {
12964                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12965                    if (DEBUG_PERMISSIONS) {
12966                        Slog.i(TAG, "Unknown permission " + name
12967                                + " in package " + pkg.packageName);
12968                    }
12969                }
12970                continue;
12971            }
12972
12973
12974            // Limit ephemeral apps to ephemeral allowed permissions.
12975            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12976                if (DEBUG_PERMISSIONS) {
12977                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12978                            + pkg.packageName);
12979                }
12980                continue;
12981            }
12982
12983            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12984                if (DEBUG_PERMISSIONS) {
12985                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12986                            + pkg.packageName);
12987                }
12988                continue;
12989            }
12990
12991            final String perm = bp.name;
12992            boolean allowedSig = false;
12993            int grant = GRANT_DENIED;
12994
12995            // Keep track of app op permissions.
12996            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12997                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12998                if (pkgs == null) {
12999                    pkgs = new ArraySet<>();
13000                    mAppOpPermissionPackages.put(bp.name, pkgs);
13001                }
13002                pkgs.add(pkg.packageName);
13003            }
13004
13005            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
13006            switch (level) {
13007                case PermissionInfo.PROTECTION_NORMAL: {
13008                    // For all apps normal permissions are install time ones.
13009                    grant = GRANT_INSTALL;
13010                } break;
13011
13012                case PermissionInfo.PROTECTION_DANGEROUS: {
13013                    // If a permission review is required for legacy apps we represent
13014                    // their permissions as always granted runtime ones since we need
13015                    // to keep the review required permission flag per user while an
13016                    // install permission's state is shared across all users.
13017                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
13018                        // For legacy apps dangerous permissions are install time ones.
13019                        grant = GRANT_INSTALL;
13020                    } else if (origPermissions.hasInstallPermission(bp.name)) {
13021                        // For legacy apps that became modern, install becomes runtime.
13022                        grant = GRANT_UPGRADE;
13023                    } else if (mPromoteSystemApps
13024                            && isSystemApp(ps)
13025                            && mExistingSystemPackages.contains(ps.name)) {
13026                        // For legacy system apps, install becomes runtime.
13027                        // We cannot check hasInstallPermission() for system apps since those
13028                        // permissions were granted implicitly and not persisted pre-M.
13029                        grant = GRANT_UPGRADE;
13030                    } else {
13031                        // For modern apps keep runtime permissions unchanged.
13032                        grant = GRANT_RUNTIME;
13033                    }
13034                } break;
13035
13036                case PermissionInfo.PROTECTION_SIGNATURE: {
13037                    // For all apps signature permissions are install time ones.
13038                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
13039                    if (allowedSig) {
13040                        grant = GRANT_INSTALL;
13041                    }
13042                } break;
13043            }
13044
13045            if (DEBUG_PERMISSIONS) {
13046                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
13047            }
13048
13049            if (grant != GRANT_DENIED) {
13050                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
13051                    // If this is an existing, non-system package, then
13052                    // we can't add any new permissions to it.
13053                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
13054                        // Except...  if this is a permission that was added
13055                        // to the platform (note: need to only do this when
13056                        // updating the platform).
13057                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
13058                            grant = GRANT_DENIED;
13059                        }
13060                    }
13061                }
13062
13063                switch (grant) {
13064                    case GRANT_INSTALL: {
13065                        // Revoke this as runtime permission to handle the case of
13066                        // a runtime permission being downgraded to an install one.
13067                        // Also in permission review mode we keep dangerous permissions
13068                        // for legacy apps
13069                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13070                            if (origPermissions.getRuntimePermissionState(
13071                                    bp.name, userId) != null) {
13072                                // Revoke the runtime permission and clear the flags.
13073                                origPermissions.revokeRuntimePermission(bp, userId);
13074                                origPermissions.updatePermissionFlags(bp, userId,
13075                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
13076                                // If we revoked a permission permission, we have to write.
13077                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13078                                        changedRuntimePermissionUserIds, userId);
13079                            }
13080                        }
13081                        // Grant an install permission.
13082                        if (permissionsState.grantInstallPermission(bp) !=
13083                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
13084                            changedInstallPermission = true;
13085                        }
13086                    } break;
13087
13088                    case GRANT_RUNTIME: {
13089                        // Grant previously granted runtime permissions.
13090                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13091                            PermissionState permissionState = origPermissions
13092                                    .getRuntimePermissionState(bp.name, userId);
13093                            int flags = permissionState != null
13094                                    ? permissionState.getFlags() : 0;
13095                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
13096                                // Don't propagate the permission in a permission review mode if
13097                                // the former was revoked, i.e. marked to not propagate on upgrade.
13098                                // Note that in a permission review mode install permissions are
13099                                // represented as constantly granted runtime ones since we need to
13100                                // keep a per user state associated with the permission. Also the
13101                                // revoke on upgrade flag is no longer applicable and is reset.
13102                                final boolean revokeOnUpgrade = (flags & PackageManager
13103                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
13104                                if (revokeOnUpgrade) {
13105                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13106                                    // Since we changed the flags, we have to write.
13107                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13108                                            changedRuntimePermissionUserIds, userId);
13109                                }
13110                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
13111                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
13112                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
13113                                        // If we cannot put the permission as it was,
13114                                        // we have to write.
13115                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13116                                                changedRuntimePermissionUserIds, userId);
13117                                    }
13118                                }
13119
13120                                // If the app supports runtime permissions no need for a review.
13121                                if (mPermissionReviewRequired
13122                                        && appSupportsRuntimePermissions
13123                                        && (flags & PackageManager
13124                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
13125                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
13126                                    // Since we changed the flags, we have to write.
13127                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13128                                            changedRuntimePermissionUserIds, userId);
13129                                }
13130                            } else if (mPermissionReviewRequired
13131                                    && !appSupportsRuntimePermissions) {
13132                                // For legacy apps that need a permission review, every new
13133                                // runtime permission is granted but it is pending a review.
13134                                // We also need to review only platform defined runtime
13135                                // permissions as these are the only ones the platform knows
13136                                // how to disable the API to simulate revocation as legacy
13137                                // apps don't expect to run with revoked permissions.
13138                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
13139                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
13140                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
13141                                        // We changed the flags, hence have to write.
13142                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13143                                                changedRuntimePermissionUserIds, userId);
13144                                    }
13145                                }
13146                                if (permissionsState.grantRuntimePermission(bp, userId)
13147                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13148                                    // We changed the permission, hence have to write.
13149                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13150                                            changedRuntimePermissionUserIds, userId);
13151                                }
13152                            }
13153                            // Propagate the permission flags.
13154                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
13155                        }
13156                    } break;
13157
13158                    case GRANT_UPGRADE: {
13159                        // Grant runtime permissions for a previously held install permission.
13160                        PermissionState permissionState = origPermissions
13161                                .getInstallPermissionState(bp.name);
13162                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
13163
13164                        if (origPermissions.revokeInstallPermission(bp)
13165                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13166                            // We will be transferring the permission flags, so clear them.
13167                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
13168                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
13169                            changedInstallPermission = true;
13170                        }
13171
13172                        // If the permission is not to be promoted to runtime we ignore it and
13173                        // also its other flags as they are not applicable to install permissions.
13174                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
13175                            for (int userId : currentUserIds) {
13176                                if (permissionsState.grantRuntimePermission(bp, userId) !=
13177                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13178                                    // Transfer the permission flags.
13179                                    permissionsState.updatePermissionFlags(bp, userId,
13180                                            flags, flags);
13181                                    // If we granted the permission, we have to write.
13182                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13183                                            changedRuntimePermissionUserIds, userId);
13184                                }
13185                            }
13186                        }
13187                    } break;
13188
13189                    default: {
13190                        if (packageOfInterest == null
13191                                || packageOfInterest.equals(pkg.packageName)) {
13192                            if (DEBUG_PERMISSIONS) {
13193                                Slog.i(TAG, "Not granting permission " + perm
13194                                        + " to package " + pkg.packageName
13195                                        + " because it was previously installed without");
13196                            }
13197                        }
13198                    } break;
13199                }
13200            } else {
13201                if (permissionsState.revokeInstallPermission(bp) !=
13202                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13203                    // Also drop the permission flags.
13204                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13205                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13206                    changedInstallPermission = true;
13207                    Slog.i(TAG, "Un-granting permission " + perm
13208                            + " from package " + pkg.packageName
13209                            + " (protectionLevel=" + bp.protectionLevel
13210                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13211                            + ")");
13212                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13213                    // Don't print warning for app op permissions, since it is fine for them
13214                    // not to be granted, there is a UI for the user to decide.
13215                    if (DEBUG_PERMISSIONS
13216                            && (packageOfInterest == null
13217                                    || packageOfInterest.equals(pkg.packageName))) {
13218                        Slog.i(TAG, "Not granting permission " + perm
13219                                + " to package " + pkg.packageName
13220                                + " (protectionLevel=" + bp.protectionLevel
13221                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13222                                + ")");
13223                    }
13224                }
13225            }
13226        }
13227
13228        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13229                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13230            // This is the first that we have heard about this package, so the
13231            // permissions we have now selected are fixed until explicitly
13232            // changed.
13233            ps.installPermissionsFixed = true;
13234        }
13235
13236        // Persist the runtime permissions state for users with changes. If permissions
13237        // were revoked because no app in the shared user declares them we have to
13238        // write synchronously to avoid losing runtime permissions state.
13239        for (int userId : changedRuntimePermissionUserIds) {
13240            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13241        }
13242    }
13243
13244    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13245        boolean allowed = false;
13246        final int NP = PackageParser.NEW_PERMISSIONS.length;
13247        for (int ip=0; ip<NP; ip++) {
13248            final PackageParser.NewPermissionInfo npi
13249                    = PackageParser.NEW_PERMISSIONS[ip];
13250            if (npi.name.equals(perm)
13251                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13252                allowed = true;
13253                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13254                        + pkg.packageName);
13255                break;
13256            }
13257        }
13258        return allowed;
13259    }
13260
13261    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13262            BasePermission bp, PermissionsState origPermissions) {
13263        boolean privilegedPermission = (bp.protectionLevel
13264                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13265        boolean privappPermissionsDisable =
13266                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13267        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13268        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13269        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13270                && !platformPackage && platformPermission) {
13271            final ArraySet<String> allowedPermissions = SystemConfig.getInstance()
13272                    .getPrivAppPermissions(pkg.packageName);
13273            final boolean whitelisted =
13274                    allowedPermissions != null && allowedPermissions.contains(perm);
13275            if (!whitelisted) {
13276                Slog.w(TAG, "Privileged permission " + perm + " for package "
13277                        + pkg.packageName + " - not in privapp-permissions whitelist");
13278                // Only report violations for apps on system image
13279                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13280                    // it's only a reportable violation if the permission isn't explicitly denied
13281                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
13282                            .getPrivAppDenyPermissions(pkg.packageName);
13283                    final boolean permissionViolation =
13284                            deniedPermissions == null || !deniedPermissions.contains(perm);
13285                    if (permissionViolation) {
13286                        if (mPrivappPermissionsViolations == null) {
13287                            mPrivappPermissionsViolations = new ArraySet<>();
13288                        }
13289                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13290                    } else {
13291                        return false;
13292                    }
13293                }
13294                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13295                    return false;
13296                }
13297            }
13298        }
13299        boolean allowed = (compareSignatures(
13300                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13301                        == PackageManager.SIGNATURE_MATCH)
13302                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13303                        == PackageManager.SIGNATURE_MATCH);
13304        if (!allowed && privilegedPermission) {
13305            if (isSystemApp(pkg)) {
13306                // For updated system applications, a system permission
13307                // is granted only if it had been defined by the original application.
13308                if (pkg.isUpdatedSystemApp()) {
13309                    final PackageSetting sysPs = mSettings
13310                            .getDisabledSystemPkgLPr(pkg.packageName);
13311                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13312                        // If the original was granted this permission, we take
13313                        // that grant decision as read and propagate it to the
13314                        // update.
13315                        if (sysPs.isPrivileged()) {
13316                            allowed = true;
13317                        }
13318                    } else {
13319                        // The system apk may have been updated with an older
13320                        // version of the one on the data partition, but which
13321                        // granted a new system permission that it didn't have
13322                        // before.  In this case we do want to allow the app to
13323                        // now get the new permission if the ancestral apk is
13324                        // privileged to get it.
13325                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13326                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13327                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13328                                    allowed = true;
13329                                    break;
13330                                }
13331                            }
13332                        }
13333                        // Also if a privileged parent package on the system image or any of
13334                        // its children requested a privileged permission, the updated child
13335                        // packages can also get the permission.
13336                        if (pkg.parentPackage != null) {
13337                            final PackageSetting disabledSysParentPs = mSettings
13338                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13339                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13340                                    && disabledSysParentPs.isPrivileged()) {
13341                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13342                                    allowed = true;
13343                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13344                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13345                                    for (int i = 0; i < count; i++) {
13346                                        PackageParser.Package disabledSysChildPkg =
13347                                                disabledSysParentPs.pkg.childPackages.get(i);
13348                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13349                                                perm)) {
13350                                            allowed = true;
13351                                            break;
13352                                        }
13353                                    }
13354                                }
13355                            }
13356                        }
13357                    }
13358                } else {
13359                    allowed = isPrivilegedApp(pkg);
13360                }
13361            }
13362        }
13363        if (!allowed) {
13364            if (!allowed && (bp.protectionLevel
13365                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13366                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13367                // If this was a previously normal/dangerous permission that got moved
13368                // to a system permission as part of the runtime permission redesign, then
13369                // we still want to blindly grant it to old apps.
13370                allowed = true;
13371            }
13372            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13373                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13374                // If this permission is to be granted to the system installer and
13375                // this app is an installer, then it gets the permission.
13376                allowed = true;
13377            }
13378            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13379                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13380                // If this permission is to be granted to the system verifier and
13381                // this app is a verifier, then it gets the permission.
13382                allowed = true;
13383            }
13384            if (!allowed && (bp.protectionLevel
13385                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13386                    && isSystemApp(pkg)) {
13387                // Any pre-installed system app is allowed to get this permission.
13388                allowed = true;
13389            }
13390            if (!allowed && (bp.protectionLevel
13391                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13392                // For development permissions, a development permission
13393                // is granted only if it was already granted.
13394                allowed = origPermissions.hasInstallPermission(perm);
13395            }
13396            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13397                    && pkg.packageName.equals(mSetupWizardPackage)) {
13398                // If this permission is to be granted to the system setup wizard and
13399                // this app is a setup wizard, then it gets the permission.
13400                allowed = true;
13401            }
13402        }
13403        return allowed;
13404    }
13405
13406    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13407        final int permCount = pkg.requestedPermissions.size();
13408        for (int j = 0; j < permCount; j++) {
13409            String requestedPermission = pkg.requestedPermissions.get(j);
13410            if (permission.equals(requestedPermission)) {
13411                return true;
13412            }
13413        }
13414        return false;
13415    }
13416
13417    final class ActivityIntentResolver
13418            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13419        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13420                boolean defaultOnly, int userId) {
13421            if (!sUserManager.exists(userId)) return null;
13422            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13423            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13424        }
13425
13426        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13427                int userId) {
13428            if (!sUserManager.exists(userId)) return null;
13429            mFlags = flags;
13430            return super.queryIntent(intent, resolvedType,
13431                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13432                    userId);
13433        }
13434
13435        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13436                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13437            if (!sUserManager.exists(userId)) return null;
13438            if (packageActivities == null) {
13439                return null;
13440            }
13441            mFlags = flags;
13442            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13443            final int N = packageActivities.size();
13444            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13445                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13446
13447            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13448            for (int i = 0; i < N; ++i) {
13449                intentFilters = packageActivities.get(i).intents;
13450                if (intentFilters != null && intentFilters.size() > 0) {
13451                    PackageParser.ActivityIntentInfo[] array =
13452                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13453                    intentFilters.toArray(array);
13454                    listCut.add(array);
13455                }
13456            }
13457            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13458        }
13459
13460        /**
13461         * Finds a privileged activity that matches the specified activity names.
13462         */
13463        private PackageParser.Activity findMatchingActivity(
13464                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13465            for (PackageParser.Activity sysActivity : activityList) {
13466                if (sysActivity.info.name.equals(activityInfo.name)) {
13467                    return sysActivity;
13468                }
13469                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13470                    return sysActivity;
13471                }
13472                if (sysActivity.info.targetActivity != null) {
13473                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13474                        return sysActivity;
13475                    }
13476                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13477                        return sysActivity;
13478                    }
13479                }
13480            }
13481            return null;
13482        }
13483
13484        public class IterGenerator<E> {
13485            public Iterator<E> generate(ActivityIntentInfo info) {
13486                return null;
13487            }
13488        }
13489
13490        public class ActionIterGenerator extends IterGenerator<String> {
13491            @Override
13492            public Iterator<String> generate(ActivityIntentInfo info) {
13493                return info.actionsIterator();
13494            }
13495        }
13496
13497        public class CategoriesIterGenerator extends IterGenerator<String> {
13498            @Override
13499            public Iterator<String> generate(ActivityIntentInfo info) {
13500                return info.categoriesIterator();
13501            }
13502        }
13503
13504        public class SchemesIterGenerator extends IterGenerator<String> {
13505            @Override
13506            public Iterator<String> generate(ActivityIntentInfo info) {
13507                return info.schemesIterator();
13508            }
13509        }
13510
13511        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13512            @Override
13513            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13514                return info.authoritiesIterator();
13515            }
13516        }
13517
13518        /**
13519         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13520         * MODIFIED. Do not pass in a list that should not be changed.
13521         */
13522        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13523                IterGenerator<T> generator, Iterator<T> searchIterator) {
13524            // loop through the set of actions; every one must be found in the intent filter
13525            while (searchIterator.hasNext()) {
13526                // we must have at least one filter in the list to consider a match
13527                if (intentList.size() == 0) {
13528                    break;
13529                }
13530
13531                final T searchAction = searchIterator.next();
13532
13533                // loop through the set of intent filters
13534                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13535                while (intentIter.hasNext()) {
13536                    final ActivityIntentInfo intentInfo = intentIter.next();
13537                    boolean selectionFound = false;
13538
13539                    // loop through the intent filter's selection criteria; at least one
13540                    // of them must match the searched criteria
13541                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13542                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13543                        final T intentSelection = intentSelectionIter.next();
13544                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13545                            selectionFound = true;
13546                            break;
13547                        }
13548                    }
13549
13550                    // the selection criteria wasn't found in this filter's set; this filter
13551                    // is not a potential match
13552                    if (!selectionFound) {
13553                        intentIter.remove();
13554                    }
13555                }
13556            }
13557        }
13558
13559        private boolean isProtectedAction(ActivityIntentInfo filter) {
13560            final Iterator<String> actionsIter = filter.actionsIterator();
13561            while (actionsIter != null && actionsIter.hasNext()) {
13562                final String filterAction = actionsIter.next();
13563                if (PROTECTED_ACTIONS.contains(filterAction)) {
13564                    return true;
13565                }
13566            }
13567            return false;
13568        }
13569
13570        /**
13571         * Adjusts the priority of the given intent filter according to policy.
13572         * <p>
13573         * <ul>
13574         * <li>The priority for non privileged applications is capped to '0'</li>
13575         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13576         * <li>The priority for unbundled updates to privileged applications is capped to the
13577         *      priority defined on the system partition</li>
13578         * </ul>
13579         * <p>
13580         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13581         * allowed to obtain any priority on any action.
13582         */
13583        private void adjustPriority(
13584                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13585            // nothing to do; priority is fine as-is
13586            if (intent.getPriority() <= 0) {
13587                return;
13588            }
13589
13590            final ActivityInfo activityInfo = intent.activity.info;
13591            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13592
13593            final boolean privilegedApp =
13594                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13595            if (!privilegedApp) {
13596                // non-privileged applications can never define a priority >0
13597                if (DEBUG_FILTERS) {
13598                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13599                            + " package: " + applicationInfo.packageName
13600                            + " activity: " + intent.activity.className
13601                            + " origPrio: " + intent.getPriority());
13602                }
13603                intent.setPriority(0);
13604                return;
13605            }
13606
13607            if (systemActivities == null) {
13608                // the system package is not disabled; we're parsing the system partition
13609                if (isProtectedAction(intent)) {
13610                    if (mDeferProtectedFilters) {
13611                        // We can't deal with these just yet. No component should ever obtain a
13612                        // >0 priority for a protected actions, with ONE exception -- the setup
13613                        // wizard. The setup wizard, however, cannot be known until we're able to
13614                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13615                        // until all intent filters have been processed. Chicken, meet egg.
13616                        // Let the filter temporarily have a high priority and rectify the
13617                        // priorities after all system packages have been scanned.
13618                        mProtectedFilters.add(intent);
13619                        if (DEBUG_FILTERS) {
13620                            Slog.i(TAG, "Protected action; save for later;"
13621                                    + " package: " + applicationInfo.packageName
13622                                    + " activity: " + intent.activity.className
13623                                    + " origPrio: " + intent.getPriority());
13624                        }
13625                        return;
13626                    } else {
13627                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13628                            Slog.i(TAG, "No setup wizard;"
13629                                + " All protected intents capped to priority 0");
13630                        }
13631                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13632                            if (DEBUG_FILTERS) {
13633                                Slog.i(TAG, "Found setup wizard;"
13634                                    + " allow priority " + intent.getPriority() + ";"
13635                                    + " package: " + intent.activity.info.packageName
13636                                    + " activity: " + intent.activity.className
13637                                    + " priority: " + intent.getPriority());
13638                            }
13639                            // setup wizard gets whatever it wants
13640                            return;
13641                        }
13642                        if (DEBUG_FILTERS) {
13643                            Slog.i(TAG, "Protected action; cap priority to 0;"
13644                                    + " package: " + intent.activity.info.packageName
13645                                    + " activity: " + intent.activity.className
13646                                    + " origPrio: " + intent.getPriority());
13647                        }
13648                        intent.setPriority(0);
13649                        return;
13650                    }
13651                }
13652                // privileged apps on the system image get whatever priority they request
13653                return;
13654            }
13655
13656            // privileged app unbundled update ... try to find the same activity
13657            final PackageParser.Activity foundActivity =
13658                    findMatchingActivity(systemActivities, activityInfo);
13659            if (foundActivity == null) {
13660                // this is a new activity; it cannot obtain >0 priority
13661                if (DEBUG_FILTERS) {
13662                    Slog.i(TAG, "New activity; cap priority to 0;"
13663                            + " package: " + applicationInfo.packageName
13664                            + " activity: " + intent.activity.className
13665                            + " origPrio: " + intent.getPriority());
13666                }
13667                intent.setPriority(0);
13668                return;
13669            }
13670
13671            // found activity, now check for filter equivalence
13672
13673            // a shallow copy is enough; we modify the list, not its contents
13674            final List<ActivityIntentInfo> intentListCopy =
13675                    new ArrayList<>(foundActivity.intents);
13676            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13677
13678            // find matching action subsets
13679            final Iterator<String> actionsIterator = intent.actionsIterator();
13680            if (actionsIterator != null) {
13681                getIntentListSubset(
13682                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13683                if (intentListCopy.size() == 0) {
13684                    // no more intents to match; we're not equivalent
13685                    if (DEBUG_FILTERS) {
13686                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13687                                + " package: " + applicationInfo.packageName
13688                                + " activity: " + intent.activity.className
13689                                + " origPrio: " + intent.getPriority());
13690                    }
13691                    intent.setPriority(0);
13692                    return;
13693                }
13694            }
13695
13696            // find matching category subsets
13697            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13698            if (categoriesIterator != null) {
13699                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13700                        categoriesIterator);
13701                if (intentListCopy.size() == 0) {
13702                    // no more intents to match; we're not equivalent
13703                    if (DEBUG_FILTERS) {
13704                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13705                                + " package: " + applicationInfo.packageName
13706                                + " activity: " + intent.activity.className
13707                                + " origPrio: " + intent.getPriority());
13708                    }
13709                    intent.setPriority(0);
13710                    return;
13711                }
13712            }
13713
13714            // find matching schemes subsets
13715            final Iterator<String> schemesIterator = intent.schemesIterator();
13716            if (schemesIterator != null) {
13717                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13718                        schemesIterator);
13719                if (intentListCopy.size() == 0) {
13720                    // no more intents to match; we're not equivalent
13721                    if (DEBUG_FILTERS) {
13722                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13723                                + " package: " + applicationInfo.packageName
13724                                + " activity: " + intent.activity.className
13725                                + " origPrio: " + intent.getPriority());
13726                    }
13727                    intent.setPriority(0);
13728                    return;
13729                }
13730            }
13731
13732            // find matching authorities subsets
13733            final Iterator<IntentFilter.AuthorityEntry>
13734                    authoritiesIterator = intent.authoritiesIterator();
13735            if (authoritiesIterator != null) {
13736                getIntentListSubset(intentListCopy,
13737                        new AuthoritiesIterGenerator(),
13738                        authoritiesIterator);
13739                if (intentListCopy.size() == 0) {
13740                    // no more intents to match; we're not equivalent
13741                    if (DEBUG_FILTERS) {
13742                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13743                                + " package: " + applicationInfo.packageName
13744                                + " activity: " + intent.activity.className
13745                                + " origPrio: " + intent.getPriority());
13746                    }
13747                    intent.setPriority(0);
13748                    return;
13749                }
13750            }
13751
13752            // we found matching filter(s); app gets the max priority of all intents
13753            int cappedPriority = 0;
13754            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13755                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13756            }
13757            if (intent.getPriority() > cappedPriority) {
13758                if (DEBUG_FILTERS) {
13759                    Slog.i(TAG, "Found matching filter(s);"
13760                            + " cap priority to " + cappedPriority + ";"
13761                            + " package: " + applicationInfo.packageName
13762                            + " activity: " + intent.activity.className
13763                            + " origPrio: " + intent.getPriority());
13764                }
13765                intent.setPriority(cappedPriority);
13766                return;
13767            }
13768            // all this for nothing; the requested priority was <= what was on the system
13769        }
13770
13771        public final void addActivity(PackageParser.Activity a, String type) {
13772            mActivities.put(a.getComponentName(), a);
13773            if (DEBUG_SHOW_INFO)
13774                Log.v(
13775                TAG, "  " + type + " " +
13776                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13777            if (DEBUG_SHOW_INFO)
13778                Log.v(TAG, "    Class=" + a.info.name);
13779            final int NI = a.intents.size();
13780            for (int j=0; j<NI; j++) {
13781                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13782                if ("activity".equals(type)) {
13783                    final PackageSetting ps =
13784                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13785                    final List<PackageParser.Activity> systemActivities =
13786                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13787                    adjustPriority(systemActivities, intent);
13788                }
13789                if (DEBUG_SHOW_INFO) {
13790                    Log.v(TAG, "    IntentFilter:");
13791                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13792                }
13793                if (!intent.debugCheck()) {
13794                    Log.w(TAG, "==> For Activity " + a.info.name);
13795                }
13796                addFilter(intent);
13797            }
13798        }
13799
13800        public final void removeActivity(PackageParser.Activity a, String type) {
13801            mActivities.remove(a.getComponentName());
13802            if (DEBUG_SHOW_INFO) {
13803                Log.v(TAG, "  " + type + " "
13804                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13805                                : a.info.name) + ":");
13806                Log.v(TAG, "    Class=" + a.info.name);
13807            }
13808            final int NI = a.intents.size();
13809            for (int j=0; j<NI; j++) {
13810                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13811                if (DEBUG_SHOW_INFO) {
13812                    Log.v(TAG, "    IntentFilter:");
13813                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13814                }
13815                removeFilter(intent);
13816            }
13817        }
13818
13819        @Override
13820        protected boolean allowFilterResult(
13821                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13822            ActivityInfo filterAi = filter.activity.info;
13823            for (int i=dest.size()-1; i>=0; i--) {
13824                ActivityInfo destAi = dest.get(i).activityInfo;
13825                if (destAi.name == filterAi.name
13826                        && destAi.packageName == filterAi.packageName) {
13827                    return false;
13828                }
13829            }
13830            return true;
13831        }
13832
13833        @Override
13834        protected ActivityIntentInfo[] newArray(int size) {
13835            return new ActivityIntentInfo[size];
13836        }
13837
13838        @Override
13839        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13840            if (!sUserManager.exists(userId)) return true;
13841            PackageParser.Package p = filter.activity.owner;
13842            if (p != null) {
13843                PackageSetting ps = (PackageSetting)p.mExtras;
13844                if (ps != null) {
13845                    // System apps are never considered stopped for purposes of
13846                    // filtering, because there may be no way for the user to
13847                    // actually re-launch them.
13848                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13849                            && ps.getStopped(userId);
13850                }
13851            }
13852            return false;
13853        }
13854
13855        @Override
13856        protected boolean isPackageForFilter(String packageName,
13857                PackageParser.ActivityIntentInfo info) {
13858            return packageName.equals(info.activity.owner.packageName);
13859        }
13860
13861        @Override
13862        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13863                int match, int userId) {
13864            if (!sUserManager.exists(userId)) return null;
13865            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13866                return null;
13867            }
13868            final PackageParser.Activity activity = info.activity;
13869            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13870            if (ps == null) {
13871                return null;
13872            }
13873            final PackageUserState userState = ps.readUserState(userId);
13874            ActivityInfo ai =
13875                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13876            if (ai == null) {
13877                return null;
13878            }
13879            final boolean matchExplicitlyVisibleOnly =
13880                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13881            final boolean matchVisibleToInstantApp =
13882                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13883            final boolean componentVisible =
13884                    matchVisibleToInstantApp
13885                    && info.isVisibleToInstantApp()
13886                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13887            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13888            // throw out filters that aren't visible to ephemeral apps
13889            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13890                return null;
13891            }
13892            // throw out instant app filters if we're not explicitly requesting them
13893            if (!matchInstantApp && userState.instantApp) {
13894                return null;
13895            }
13896            // throw out instant app filters if updates are available; will trigger
13897            // instant app resolution
13898            if (userState.instantApp && ps.isUpdateAvailable()) {
13899                return null;
13900            }
13901            final ResolveInfo res = new ResolveInfo();
13902            res.activityInfo = ai;
13903            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13904                res.filter = info;
13905            }
13906            if (info != null) {
13907                res.handleAllWebDataURI = info.handleAllWebDataURI();
13908            }
13909            res.priority = info.getPriority();
13910            res.preferredOrder = activity.owner.mPreferredOrder;
13911            //System.out.println("Result: " + res.activityInfo.className +
13912            //                   " = " + res.priority);
13913            res.match = match;
13914            res.isDefault = info.hasDefault;
13915            res.labelRes = info.labelRes;
13916            res.nonLocalizedLabel = info.nonLocalizedLabel;
13917            if (userNeedsBadging(userId)) {
13918                res.noResourceId = true;
13919            } else {
13920                res.icon = info.icon;
13921            }
13922            res.iconResourceId = info.icon;
13923            res.system = res.activityInfo.applicationInfo.isSystemApp();
13924            res.isInstantAppAvailable = userState.instantApp;
13925            return res;
13926        }
13927
13928        @Override
13929        protected void sortResults(List<ResolveInfo> results) {
13930            Collections.sort(results, mResolvePrioritySorter);
13931        }
13932
13933        @Override
13934        protected void dumpFilter(PrintWriter out, String prefix,
13935                PackageParser.ActivityIntentInfo filter) {
13936            out.print(prefix); out.print(
13937                    Integer.toHexString(System.identityHashCode(filter.activity)));
13938                    out.print(' ');
13939                    filter.activity.printComponentShortName(out);
13940                    out.print(" filter ");
13941                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13942        }
13943
13944        @Override
13945        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13946            return filter.activity;
13947        }
13948
13949        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13950            PackageParser.Activity activity = (PackageParser.Activity)label;
13951            out.print(prefix); out.print(
13952                    Integer.toHexString(System.identityHashCode(activity)));
13953                    out.print(' ');
13954                    activity.printComponentShortName(out);
13955            if (count > 1) {
13956                out.print(" ("); out.print(count); out.print(" filters)");
13957            }
13958            out.println();
13959        }
13960
13961        // Keys are String (activity class name), values are Activity.
13962        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13963                = new ArrayMap<ComponentName, PackageParser.Activity>();
13964        private int mFlags;
13965    }
13966
13967    private final class ServiceIntentResolver
13968            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13969        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13970                boolean defaultOnly, int userId) {
13971            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13972            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13973        }
13974
13975        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13976                int userId) {
13977            if (!sUserManager.exists(userId)) return null;
13978            mFlags = flags;
13979            return super.queryIntent(intent, resolvedType,
13980                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13981                    userId);
13982        }
13983
13984        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13985                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13986            if (!sUserManager.exists(userId)) return null;
13987            if (packageServices == null) {
13988                return null;
13989            }
13990            mFlags = flags;
13991            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13992            final int N = packageServices.size();
13993            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13994                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13995
13996            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13997            for (int i = 0; i < N; ++i) {
13998                intentFilters = packageServices.get(i).intents;
13999                if (intentFilters != null && intentFilters.size() > 0) {
14000                    PackageParser.ServiceIntentInfo[] array =
14001                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
14002                    intentFilters.toArray(array);
14003                    listCut.add(array);
14004                }
14005            }
14006            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14007        }
14008
14009        public final void addService(PackageParser.Service s) {
14010            mServices.put(s.getComponentName(), s);
14011            if (DEBUG_SHOW_INFO) {
14012                Log.v(TAG, "  "
14013                        + (s.info.nonLocalizedLabel != null
14014                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14015                Log.v(TAG, "    Class=" + s.info.name);
14016            }
14017            final int NI = s.intents.size();
14018            int j;
14019            for (j=0; j<NI; j++) {
14020                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14021                if (DEBUG_SHOW_INFO) {
14022                    Log.v(TAG, "    IntentFilter:");
14023                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14024                }
14025                if (!intent.debugCheck()) {
14026                    Log.w(TAG, "==> For Service " + s.info.name);
14027                }
14028                addFilter(intent);
14029            }
14030        }
14031
14032        public final void removeService(PackageParser.Service s) {
14033            mServices.remove(s.getComponentName());
14034            if (DEBUG_SHOW_INFO) {
14035                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
14036                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14037                Log.v(TAG, "    Class=" + s.info.name);
14038            }
14039            final int NI = s.intents.size();
14040            int j;
14041            for (j=0; j<NI; j++) {
14042                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14043                if (DEBUG_SHOW_INFO) {
14044                    Log.v(TAG, "    IntentFilter:");
14045                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14046                }
14047                removeFilter(intent);
14048            }
14049        }
14050
14051        @Override
14052        protected boolean allowFilterResult(
14053                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
14054            ServiceInfo filterSi = filter.service.info;
14055            for (int i=dest.size()-1; i>=0; i--) {
14056                ServiceInfo destAi = dest.get(i).serviceInfo;
14057                if (destAi.name == filterSi.name
14058                        && destAi.packageName == filterSi.packageName) {
14059                    return false;
14060                }
14061            }
14062            return true;
14063        }
14064
14065        @Override
14066        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
14067            return new PackageParser.ServiceIntentInfo[size];
14068        }
14069
14070        @Override
14071        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
14072            if (!sUserManager.exists(userId)) return true;
14073            PackageParser.Package p = filter.service.owner;
14074            if (p != null) {
14075                PackageSetting ps = (PackageSetting)p.mExtras;
14076                if (ps != null) {
14077                    // System apps are never considered stopped for purposes of
14078                    // filtering, because there may be no way for the user to
14079                    // actually re-launch them.
14080                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14081                            && ps.getStopped(userId);
14082                }
14083            }
14084            return false;
14085        }
14086
14087        @Override
14088        protected boolean isPackageForFilter(String packageName,
14089                PackageParser.ServiceIntentInfo info) {
14090            return packageName.equals(info.service.owner.packageName);
14091        }
14092
14093        @Override
14094        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
14095                int match, int userId) {
14096            if (!sUserManager.exists(userId)) return null;
14097            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
14098            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
14099                return null;
14100            }
14101            final PackageParser.Service service = info.service;
14102            PackageSetting ps = (PackageSetting) service.owner.mExtras;
14103            if (ps == null) {
14104                return null;
14105            }
14106            final PackageUserState userState = ps.readUserState(userId);
14107            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
14108                    userState, userId);
14109            if (si == null) {
14110                return null;
14111            }
14112            final boolean matchVisibleToInstantApp =
14113                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14114            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14115            // throw out filters that aren't visible to ephemeral apps
14116            if (matchVisibleToInstantApp
14117                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14118                return null;
14119            }
14120            // throw out ephemeral filters if we're not explicitly requesting them
14121            if (!isInstantApp && userState.instantApp) {
14122                return null;
14123            }
14124            // throw out instant app filters if updates are available; will trigger
14125            // instant app resolution
14126            if (userState.instantApp && ps.isUpdateAvailable()) {
14127                return null;
14128            }
14129            final ResolveInfo res = new ResolveInfo();
14130            res.serviceInfo = si;
14131            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
14132                res.filter = filter;
14133            }
14134            res.priority = info.getPriority();
14135            res.preferredOrder = service.owner.mPreferredOrder;
14136            res.match = match;
14137            res.isDefault = info.hasDefault;
14138            res.labelRes = info.labelRes;
14139            res.nonLocalizedLabel = info.nonLocalizedLabel;
14140            res.icon = info.icon;
14141            res.system = res.serviceInfo.applicationInfo.isSystemApp();
14142            return res;
14143        }
14144
14145        @Override
14146        protected void sortResults(List<ResolveInfo> results) {
14147            Collections.sort(results, mResolvePrioritySorter);
14148        }
14149
14150        @Override
14151        protected void dumpFilter(PrintWriter out, String prefix,
14152                PackageParser.ServiceIntentInfo filter) {
14153            out.print(prefix); out.print(
14154                    Integer.toHexString(System.identityHashCode(filter.service)));
14155                    out.print(' ');
14156                    filter.service.printComponentShortName(out);
14157                    out.print(" filter ");
14158                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14159        }
14160
14161        @Override
14162        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14163            return filter.service;
14164        }
14165
14166        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14167            PackageParser.Service service = (PackageParser.Service)label;
14168            out.print(prefix); out.print(
14169                    Integer.toHexString(System.identityHashCode(service)));
14170                    out.print(' ');
14171                    service.printComponentShortName(out);
14172            if (count > 1) {
14173                out.print(" ("); out.print(count); out.print(" filters)");
14174            }
14175            out.println();
14176        }
14177
14178//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14179//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14180//            final List<ResolveInfo> retList = Lists.newArrayList();
14181//            while (i.hasNext()) {
14182//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14183//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14184//                    retList.add(resolveInfo);
14185//                }
14186//            }
14187//            return retList;
14188//        }
14189
14190        // Keys are String (activity class name), values are Activity.
14191        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14192                = new ArrayMap<ComponentName, PackageParser.Service>();
14193        private int mFlags;
14194    }
14195
14196    private final class ProviderIntentResolver
14197            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14198        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14199                boolean defaultOnly, int userId) {
14200            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14201            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14202        }
14203
14204        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14205                int userId) {
14206            if (!sUserManager.exists(userId))
14207                return null;
14208            mFlags = flags;
14209            return super.queryIntent(intent, resolvedType,
14210                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14211                    userId);
14212        }
14213
14214        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14215                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14216            if (!sUserManager.exists(userId))
14217                return null;
14218            if (packageProviders == null) {
14219                return null;
14220            }
14221            mFlags = flags;
14222            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14223            final int N = packageProviders.size();
14224            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14225                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14226
14227            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14228            for (int i = 0; i < N; ++i) {
14229                intentFilters = packageProviders.get(i).intents;
14230                if (intentFilters != null && intentFilters.size() > 0) {
14231                    PackageParser.ProviderIntentInfo[] array =
14232                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14233                    intentFilters.toArray(array);
14234                    listCut.add(array);
14235                }
14236            }
14237            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14238        }
14239
14240        public final void addProvider(PackageParser.Provider p) {
14241            if (mProviders.containsKey(p.getComponentName())) {
14242                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14243                return;
14244            }
14245
14246            mProviders.put(p.getComponentName(), p);
14247            if (DEBUG_SHOW_INFO) {
14248                Log.v(TAG, "  "
14249                        + (p.info.nonLocalizedLabel != null
14250                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14251                Log.v(TAG, "    Class=" + p.info.name);
14252            }
14253            final int NI = p.intents.size();
14254            int j;
14255            for (j = 0; j < NI; j++) {
14256                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14257                if (DEBUG_SHOW_INFO) {
14258                    Log.v(TAG, "    IntentFilter:");
14259                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14260                }
14261                if (!intent.debugCheck()) {
14262                    Log.w(TAG, "==> For Provider " + p.info.name);
14263                }
14264                addFilter(intent);
14265            }
14266        }
14267
14268        public final void removeProvider(PackageParser.Provider p) {
14269            mProviders.remove(p.getComponentName());
14270            if (DEBUG_SHOW_INFO) {
14271                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14272                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14273                Log.v(TAG, "    Class=" + p.info.name);
14274            }
14275            final int NI = p.intents.size();
14276            int j;
14277            for (j = 0; j < NI; j++) {
14278                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14279                if (DEBUG_SHOW_INFO) {
14280                    Log.v(TAG, "    IntentFilter:");
14281                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14282                }
14283                removeFilter(intent);
14284            }
14285        }
14286
14287        @Override
14288        protected boolean allowFilterResult(
14289                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14290            ProviderInfo filterPi = filter.provider.info;
14291            for (int i = dest.size() - 1; i >= 0; i--) {
14292                ProviderInfo destPi = dest.get(i).providerInfo;
14293                if (destPi.name == filterPi.name
14294                        && destPi.packageName == filterPi.packageName) {
14295                    return false;
14296                }
14297            }
14298            return true;
14299        }
14300
14301        @Override
14302        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14303            return new PackageParser.ProviderIntentInfo[size];
14304        }
14305
14306        @Override
14307        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14308            if (!sUserManager.exists(userId))
14309                return true;
14310            PackageParser.Package p = filter.provider.owner;
14311            if (p != null) {
14312                PackageSetting ps = (PackageSetting) p.mExtras;
14313                if (ps != null) {
14314                    // System apps are never considered stopped for purposes of
14315                    // filtering, because there may be no way for the user to
14316                    // actually re-launch them.
14317                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14318                            && ps.getStopped(userId);
14319                }
14320            }
14321            return false;
14322        }
14323
14324        @Override
14325        protected boolean isPackageForFilter(String packageName,
14326                PackageParser.ProviderIntentInfo info) {
14327            return packageName.equals(info.provider.owner.packageName);
14328        }
14329
14330        @Override
14331        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14332                int match, int userId) {
14333            if (!sUserManager.exists(userId))
14334                return null;
14335            final PackageParser.ProviderIntentInfo info = filter;
14336            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14337                return null;
14338            }
14339            final PackageParser.Provider provider = info.provider;
14340            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14341            if (ps == null) {
14342                return null;
14343            }
14344            final PackageUserState userState = ps.readUserState(userId);
14345            final boolean matchVisibleToInstantApp =
14346                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14347            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14348            // throw out filters that aren't visible to instant applications
14349            if (matchVisibleToInstantApp
14350                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14351                return null;
14352            }
14353            // throw out instant application filters if we're not explicitly requesting them
14354            if (!isInstantApp && userState.instantApp) {
14355                return null;
14356            }
14357            // throw out instant application filters if updates are available; will trigger
14358            // instant application resolution
14359            if (userState.instantApp && ps.isUpdateAvailable()) {
14360                return null;
14361            }
14362            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14363                    userState, userId);
14364            if (pi == null) {
14365                return null;
14366            }
14367            final ResolveInfo res = new ResolveInfo();
14368            res.providerInfo = pi;
14369            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14370                res.filter = filter;
14371            }
14372            res.priority = info.getPriority();
14373            res.preferredOrder = provider.owner.mPreferredOrder;
14374            res.match = match;
14375            res.isDefault = info.hasDefault;
14376            res.labelRes = info.labelRes;
14377            res.nonLocalizedLabel = info.nonLocalizedLabel;
14378            res.icon = info.icon;
14379            res.system = res.providerInfo.applicationInfo.isSystemApp();
14380            return res;
14381        }
14382
14383        @Override
14384        protected void sortResults(List<ResolveInfo> results) {
14385            Collections.sort(results, mResolvePrioritySorter);
14386        }
14387
14388        @Override
14389        protected void dumpFilter(PrintWriter out, String prefix,
14390                PackageParser.ProviderIntentInfo filter) {
14391            out.print(prefix);
14392            out.print(
14393                    Integer.toHexString(System.identityHashCode(filter.provider)));
14394            out.print(' ');
14395            filter.provider.printComponentShortName(out);
14396            out.print(" filter ");
14397            out.println(Integer.toHexString(System.identityHashCode(filter)));
14398        }
14399
14400        @Override
14401        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14402            return filter.provider;
14403        }
14404
14405        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14406            PackageParser.Provider provider = (PackageParser.Provider)label;
14407            out.print(prefix); out.print(
14408                    Integer.toHexString(System.identityHashCode(provider)));
14409                    out.print(' ');
14410                    provider.printComponentShortName(out);
14411            if (count > 1) {
14412                out.print(" ("); out.print(count); out.print(" filters)");
14413            }
14414            out.println();
14415        }
14416
14417        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14418                = new ArrayMap<ComponentName, PackageParser.Provider>();
14419        private int mFlags;
14420    }
14421
14422    static final class EphemeralIntentResolver
14423            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14424        /**
14425         * The result that has the highest defined order. Ordering applies on a
14426         * per-package basis. Mapping is from package name to Pair of order and
14427         * EphemeralResolveInfo.
14428         * <p>
14429         * NOTE: This is implemented as a field variable for convenience and efficiency.
14430         * By having a field variable, we're able to track filter ordering as soon as
14431         * a non-zero order is defined. Otherwise, multiple loops across the result set
14432         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14433         * this needs to be contained entirely within {@link #filterResults}.
14434         */
14435        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14436
14437        @Override
14438        protected AuxiliaryResolveInfo[] newArray(int size) {
14439            return new AuxiliaryResolveInfo[size];
14440        }
14441
14442        @Override
14443        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14444            return true;
14445        }
14446
14447        @Override
14448        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14449                int userId) {
14450            if (!sUserManager.exists(userId)) {
14451                return null;
14452            }
14453            final String packageName = responseObj.resolveInfo.getPackageName();
14454            final Integer order = responseObj.getOrder();
14455            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14456                    mOrderResult.get(packageName);
14457            // ordering is enabled and this item's order isn't high enough
14458            if (lastOrderResult != null && lastOrderResult.first >= order) {
14459                return null;
14460            }
14461            final InstantAppResolveInfo res = responseObj.resolveInfo;
14462            if (order > 0) {
14463                // non-zero order, enable ordering
14464                mOrderResult.put(packageName, new Pair<>(order, res));
14465            }
14466            return responseObj;
14467        }
14468
14469        @Override
14470        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14471            // only do work if ordering is enabled [most of the time it won't be]
14472            if (mOrderResult.size() == 0) {
14473                return;
14474            }
14475            int resultSize = results.size();
14476            for (int i = 0; i < resultSize; i++) {
14477                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14478                final String packageName = info.getPackageName();
14479                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14480                if (savedInfo == null) {
14481                    // package doesn't having ordering
14482                    continue;
14483                }
14484                if (savedInfo.second == info) {
14485                    // circled back to the highest ordered item; remove from order list
14486                    mOrderResult.remove(packageName);
14487                    if (mOrderResult.size() == 0) {
14488                        // no more ordered items
14489                        break;
14490                    }
14491                    continue;
14492                }
14493                // item has a worse order, remove it from the result list
14494                results.remove(i);
14495                resultSize--;
14496                i--;
14497            }
14498        }
14499    }
14500
14501    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14502            new Comparator<ResolveInfo>() {
14503        public int compare(ResolveInfo r1, ResolveInfo r2) {
14504            int v1 = r1.priority;
14505            int v2 = r2.priority;
14506            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14507            if (v1 != v2) {
14508                return (v1 > v2) ? -1 : 1;
14509            }
14510            v1 = r1.preferredOrder;
14511            v2 = r2.preferredOrder;
14512            if (v1 != v2) {
14513                return (v1 > v2) ? -1 : 1;
14514            }
14515            if (r1.isDefault != r2.isDefault) {
14516                return r1.isDefault ? -1 : 1;
14517            }
14518            v1 = r1.match;
14519            v2 = r2.match;
14520            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14521            if (v1 != v2) {
14522                return (v1 > v2) ? -1 : 1;
14523            }
14524            if (r1.system != r2.system) {
14525                return r1.system ? -1 : 1;
14526            }
14527            if (r1.activityInfo != null) {
14528                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14529            }
14530            if (r1.serviceInfo != null) {
14531                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14532            }
14533            if (r1.providerInfo != null) {
14534                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14535            }
14536            return 0;
14537        }
14538    };
14539
14540    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14541            new Comparator<ProviderInfo>() {
14542        public int compare(ProviderInfo p1, ProviderInfo p2) {
14543            final int v1 = p1.initOrder;
14544            final int v2 = p2.initOrder;
14545            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14546        }
14547    };
14548
14549    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14550            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14551            final int[] userIds) {
14552        mHandler.post(new Runnable() {
14553            @Override
14554            public void run() {
14555                try {
14556                    final IActivityManager am = ActivityManager.getService();
14557                    if (am == null) return;
14558                    final int[] resolvedUserIds;
14559                    if (userIds == null) {
14560                        resolvedUserIds = am.getRunningUserIds();
14561                    } else {
14562                        resolvedUserIds = userIds;
14563                    }
14564                    for (int id : resolvedUserIds) {
14565                        final Intent intent = new Intent(action,
14566                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14567                        if (extras != null) {
14568                            intent.putExtras(extras);
14569                        }
14570                        if (targetPkg != null) {
14571                            intent.setPackage(targetPkg);
14572                        }
14573                        // Modify the UID when posting to other users
14574                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14575                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14576                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14577                            intent.putExtra(Intent.EXTRA_UID, uid);
14578                        }
14579                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14580                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14581                        if (DEBUG_BROADCASTS) {
14582                            RuntimeException here = new RuntimeException("here");
14583                            here.fillInStackTrace();
14584                            Slog.d(TAG, "Sending to user " + id + ": "
14585                                    + intent.toShortString(false, true, false, false)
14586                                    + " " + intent.getExtras(), here);
14587                        }
14588                        am.broadcastIntent(null, intent, null, finishedReceiver,
14589                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14590                                null, finishedReceiver != null, false, id);
14591                    }
14592                } catch (RemoteException ex) {
14593                }
14594            }
14595        });
14596    }
14597
14598    /**
14599     * Check if the external storage media is available. This is true if there
14600     * is a mounted external storage medium or if the external storage is
14601     * emulated.
14602     */
14603    private boolean isExternalMediaAvailable() {
14604        return mMediaMounted || Environment.isExternalStorageEmulated();
14605    }
14606
14607    @Override
14608    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14609        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14610            return null;
14611        }
14612        // writer
14613        synchronized (mPackages) {
14614            if (!isExternalMediaAvailable()) {
14615                // If the external storage is no longer mounted at this point,
14616                // the caller may not have been able to delete all of this
14617                // packages files and can not delete any more.  Bail.
14618                return null;
14619            }
14620            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14621            if (lastPackage != null) {
14622                pkgs.remove(lastPackage);
14623            }
14624            if (pkgs.size() > 0) {
14625                return pkgs.get(0);
14626            }
14627        }
14628        return null;
14629    }
14630
14631    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14632        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14633                userId, andCode ? 1 : 0, packageName);
14634        if (mSystemReady) {
14635            msg.sendToTarget();
14636        } else {
14637            if (mPostSystemReadyMessages == null) {
14638                mPostSystemReadyMessages = new ArrayList<>();
14639            }
14640            mPostSystemReadyMessages.add(msg);
14641        }
14642    }
14643
14644    void startCleaningPackages() {
14645        // reader
14646        if (!isExternalMediaAvailable()) {
14647            return;
14648        }
14649        synchronized (mPackages) {
14650            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14651                return;
14652            }
14653        }
14654        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14655        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14656        IActivityManager am = ActivityManager.getService();
14657        if (am != null) {
14658            int dcsUid = -1;
14659            synchronized (mPackages) {
14660                if (!mDefaultContainerWhitelisted) {
14661                    mDefaultContainerWhitelisted = true;
14662                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14663                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14664                }
14665            }
14666            try {
14667                if (dcsUid > 0) {
14668                    am.backgroundWhitelistUid(dcsUid);
14669                }
14670                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14671                        UserHandle.USER_SYSTEM);
14672            } catch (RemoteException e) {
14673            }
14674        }
14675    }
14676
14677    @Override
14678    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14679            int installFlags, String installerPackageName, int userId) {
14680        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14681
14682        final int callingUid = Binder.getCallingUid();
14683        enforceCrossUserPermission(callingUid, userId,
14684                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14685
14686        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14687            try {
14688                if (observer != null) {
14689                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14690                }
14691            } catch (RemoteException re) {
14692            }
14693            return;
14694        }
14695
14696        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14697            installFlags |= PackageManager.INSTALL_FROM_ADB;
14698
14699        } else {
14700            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14701            // about installerPackageName.
14702
14703            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14704            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14705        }
14706
14707        UserHandle user;
14708        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14709            user = UserHandle.ALL;
14710        } else {
14711            user = new UserHandle(userId);
14712        }
14713
14714        // Only system components can circumvent runtime permissions when installing.
14715        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14716                && mContext.checkCallingOrSelfPermission(Manifest.permission
14717                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14718            throw new SecurityException("You need the "
14719                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14720                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14721        }
14722
14723        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14724                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14725            throw new IllegalArgumentException(
14726                    "New installs into ASEC containers no longer supported");
14727        }
14728
14729        final File originFile = new File(originPath);
14730        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14731
14732        final Message msg = mHandler.obtainMessage(INIT_COPY);
14733        final VerificationInfo verificationInfo = new VerificationInfo(
14734                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14735        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14736                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14737                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14738                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14739        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14740        msg.obj = params;
14741
14742        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14743                System.identityHashCode(msg.obj));
14744        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14745                System.identityHashCode(msg.obj));
14746
14747        mHandler.sendMessage(msg);
14748    }
14749
14750
14751    /**
14752     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14753     * it is acting on behalf on an enterprise or the user).
14754     *
14755     * Note that the ordering of the conditionals in this method is important. The checks we perform
14756     * are as follows, in this order:
14757     *
14758     * 1) If the install is being performed by a system app, we can trust the app to have set the
14759     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14760     *    what it is.
14761     * 2) If the install is being performed by a device or profile owner app, the install reason
14762     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14763     *    set the install reason correctly. If the app targets an older SDK version where install
14764     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14765     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14766     * 3) In all other cases, the install is being performed by a regular app that is neither part
14767     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14768     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14769     *    set to enterprise policy and if so, change it to unknown instead.
14770     */
14771    private int fixUpInstallReason(String installerPackageName, int installerUid,
14772            int installReason) {
14773        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14774                == PERMISSION_GRANTED) {
14775            // If the install is being performed by a system app, we trust that app to have set the
14776            // install reason correctly.
14777            return installReason;
14778        }
14779
14780        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14781            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14782        if (dpm != null) {
14783            ComponentName owner = null;
14784            try {
14785                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14786                if (owner == null) {
14787                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14788                }
14789            } catch (RemoteException e) {
14790            }
14791            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14792                // If the install is being performed by a device or profile owner, the install
14793                // reason should be enterprise policy.
14794                return PackageManager.INSTALL_REASON_POLICY;
14795            }
14796        }
14797
14798        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14799            // If the install is being performed by a regular app (i.e. neither system app nor
14800            // device or profile owner), we have no reason to believe that the app is acting on
14801            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14802            // change it to unknown instead.
14803            return PackageManager.INSTALL_REASON_UNKNOWN;
14804        }
14805
14806        // If the install is being performed by a regular app and the install reason was set to any
14807        // value but enterprise policy, leave the install reason unchanged.
14808        return installReason;
14809    }
14810
14811    void installStage(String packageName, File stagedDir, String stagedCid,
14812            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14813            String installerPackageName, int installerUid, UserHandle user,
14814            Certificate[][] certificates) {
14815        if (DEBUG_EPHEMERAL) {
14816            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14817                Slog.d(TAG, "Ephemeral install of " + packageName);
14818            }
14819        }
14820        final VerificationInfo verificationInfo = new VerificationInfo(
14821                sessionParams.originatingUri, sessionParams.referrerUri,
14822                sessionParams.originatingUid, installerUid);
14823
14824        final OriginInfo origin;
14825        if (stagedDir != null) {
14826            origin = OriginInfo.fromStagedFile(stagedDir);
14827        } else {
14828            origin = OriginInfo.fromStagedContainer(stagedCid);
14829        }
14830
14831        final Message msg = mHandler.obtainMessage(INIT_COPY);
14832        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14833                sessionParams.installReason);
14834        final InstallParams params = new InstallParams(origin, null, observer,
14835                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14836                verificationInfo, user, sessionParams.abiOverride,
14837                sessionParams.grantedRuntimePermissions, certificates, installReason);
14838        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14839        msg.obj = params;
14840
14841        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14842                System.identityHashCode(msg.obj));
14843        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14844                System.identityHashCode(msg.obj));
14845
14846        mHandler.sendMessage(msg);
14847    }
14848
14849    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14850            int userId) {
14851        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14852        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14853                false /*startReceiver*/, pkgSetting.appId, userId);
14854
14855        // Send a session commit broadcast
14856        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14857        info.installReason = pkgSetting.getInstallReason(userId);
14858        info.appPackageName = packageName;
14859        sendSessionCommitBroadcast(info, userId);
14860    }
14861
14862    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14863            boolean includeStopped, int appId, int... userIds) {
14864        if (ArrayUtils.isEmpty(userIds)) {
14865            return;
14866        }
14867        Bundle extras = new Bundle(1);
14868        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14869        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14870
14871        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14872                packageName, extras, 0, null, null, userIds);
14873        if (sendBootCompleted) {
14874            mHandler.post(() -> {
14875                        for (int userId : userIds) {
14876                            sendBootCompletedBroadcastToSystemApp(
14877                                    packageName, includeStopped, userId);
14878                        }
14879                    }
14880            );
14881        }
14882    }
14883
14884    /**
14885     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14886     * automatically without needing an explicit launch.
14887     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14888     */
14889    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14890            int userId) {
14891        // If user is not running, the app didn't miss any broadcast
14892        if (!mUserManagerInternal.isUserRunning(userId)) {
14893            return;
14894        }
14895        final IActivityManager am = ActivityManager.getService();
14896        try {
14897            // Deliver LOCKED_BOOT_COMPLETED first
14898            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14899                    .setPackage(packageName);
14900            if (includeStopped) {
14901                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14902            }
14903            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14904            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14905                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14906
14907            // Deliver BOOT_COMPLETED only if user is unlocked
14908            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14909                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14910                if (includeStopped) {
14911                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14912                }
14913                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14914                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14915            }
14916        } catch (RemoteException e) {
14917            throw e.rethrowFromSystemServer();
14918        }
14919    }
14920
14921    @Override
14922    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14923            int userId) {
14924        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14925        PackageSetting pkgSetting;
14926        final int callingUid = Binder.getCallingUid();
14927        enforceCrossUserPermission(callingUid, userId,
14928                true /* requireFullPermission */, true /* checkShell */,
14929                "setApplicationHiddenSetting for user " + userId);
14930
14931        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14932            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14933            return false;
14934        }
14935
14936        long callingId = Binder.clearCallingIdentity();
14937        try {
14938            boolean sendAdded = false;
14939            boolean sendRemoved = false;
14940            // writer
14941            synchronized (mPackages) {
14942                pkgSetting = mSettings.mPackages.get(packageName);
14943                if (pkgSetting == null) {
14944                    return false;
14945                }
14946                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14947                    return false;
14948                }
14949                // Do not allow "android" is being disabled
14950                if ("android".equals(packageName)) {
14951                    Slog.w(TAG, "Cannot hide package: android");
14952                    return false;
14953                }
14954                // Cannot hide static shared libs as they are considered
14955                // a part of the using app (emulating static linking). Also
14956                // static libs are installed always on internal storage.
14957                PackageParser.Package pkg = mPackages.get(packageName);
14958                if (pkg != null && pkg.staticSharedLibName != null) {
14959                    Slog.w(TAG, "Cannot hide package: " + packageName
14960                            + " providing static shared library: "
14961                            + pkg.staticSharedLibName);
14962                    return false;
14963                }
14964                // Only allow protected packages to hide themselves.
14965                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14966                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14967                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14968                    return false;
14969                }
14970
14971                if (pkgSetting.getHidden(userId) != hidden) {
14972                    pkgSetting.setHidden(hidden, userId);
14973                    mSettings.writePackageRestrictionsLPr(userId);
14974                    if (hidden) {
14975                        sendRemoved = true;
14976                    } else {
14977                        sendAdded = true;
14978                    }
14979                }
14980            }
14981            if (sendAdded) {
14982                sendPackageAddedForUser(packageName, pkgSetting, userId);
14983                return true;
14984            }
14985            if (sendRemoved) {
14986                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14987                        "hiding pkg");
14988                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14989                return true;
14990            }
14991        } finally {
14992            Binder.restoreCallingIdentity(callingId);
14993        }
14994        return false;
14995    }
14996
14997    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14998            int userId) {
14999        final PackageRemovedInfo info = new PackageRemovedInfo(this);
15000        info.removedPackage = packageName;
15001        info.installerPackageName = pkgSetting.installerPackageName;
15002        info.removedUsers = new int[] {userId};
15003        info.broadcastUsers = new int[] {userId};
15004        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
15005        info.sendPackageRemovedBroadcasts(true /*killApp*/);
15006    }
15007
15008    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
15009        if (pkgList.length > 0) {
15010            Bundle extras = new Bundle(1);
15011            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15012
15013            sendPackageBroadcast(
15014                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
15015                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
15016                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
15017                    new int[] {userId});
15018        }
15019    }
15020
15021    /**
15022     * Returns true if application is not found or there was an error. Otherwise it returns
15023     * the hidden state of the package for the given user.
15024     */
15025    @Override
15026    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
15027        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15028        final int callingUid = Binder.getCallingUid();
15029        enforceCrossUserPermission(callingUid, userId,
15030                true /* requireFullPermission */, false /* checkShell */,
15031                "getApplicationHidden for user " + userId);
15032        PackageSetting ps;
15033        long callingId = Binder.clearCallingIdentity();
15034        try {
15035            // writer
15036            synchronized (mPackages) {
15037                ps = mSettings.mPackages.get(packageName);
15038                if (ps == null) {
15039                    return true;
15040                }
15041                if (filterAppAccessLPr(ps, callingUid, userId)) {
15042                    return true;
15043                }
15044                return ps.getHidden(userId);
15045            }
15046        } finally {
15047            Binder.restoreCallingIdentity(callingId);
15048        }
15049    }
15050
15051    /**
15052     * @hide
15053     */
15054    @Override
15055    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
15056            int installReason) {
15057        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
15058                null);
15059        PackageSetting pkgSetting;
15060        final int callingUid = Binder.getCallingUid();
15061        enforceCrossUserPermission(callingUid, userId,
15062                true /* requireFullPermission */, true /* checkShell */,
15063                "installExistingPackage for user " + userId);
15064        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
15065            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
15066        }
15067
15068        long callingId = Binder.clearCallingIdentity();
15069        try {
15070            boolean installed = false;
15071            final boolean instantApp =
15072                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15073            final boolean fullApp =
15074                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
15075
15076            // writer
15077            synchronized (mPackages) {
15078                pkgSetting = mSettings.mPackages.get(packageName);
15079                if (pkgSetting == null) {
15080                    return PackageManager.INSTALL_FAILED_INVALID_URI;
15081                }
15082                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
15083                    // only allow the existing package to be used if it's installed as a full
15084                    // application for at least one user
15085                    boolean installAllowed = false;
15086                    for (int checkUserId : sUserManager.getUserIds()) {
15087                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
15088                        if (installAllowed) {
15089                            break;
15090                        }
15091                    }
15092                    if (!installAllowed) {
15093                        return PackageManager.INSTALL_FAILED_INVALID_URI;
15094                    }
15095                }
15096                if (!pkgSetting.getInstalled(userId)) {
15097                    pkgSetting.setInstalled(true, userId);
15098                    pkgSetting.setHidden(false, userId);
15099                    pkgSetting.setInstallReason(installReason, userId);
15100                    mSettings.writePackageRestrictionsLPr(userId);
15101                    mSettings.writeKernelMappingLPr(pkgSetting);
15102                    installed = true;
15103                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15104                    // upgrade app from instant to full; we don't allow app downgrade
15105                    installed = true;
15106                }
15107                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
15108            }
15109
15110            if (installed) {
15111                if (pkgSetting.pkg != null) {
15112                    synchronized (mInstallLock) {
15113                        // We don't need to freeze for a brand new install
15114                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
15115                    }
15116                }
15117                sendPackageAddedForUser(packageName, pkgSetting, userId);
15118                synchronized (mPackages) {
15119                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
15120                }
15121            }
15122        } finally {
15123            Binder.restoreCallingIdentity(callingId);
15124        }
15125
15126        return PackageManager.INSTALL_SUCCEEDED;
15127    }
15128
15129    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
15130            boolean instantApp, boolean fullApp) {
15131        // no state specified; do nothing
15132        if (!instantApp && !fullApp) {
15133            return;
15134        }
15135        if (userId != UserHandle.USER_ALL) {
15136            if (instantApp && !pkgSetting.getInstantApp(userId)) {
15137                pkgSetting.setInstantApp(true /*instantApp*/, userId);
15138            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15139                pkgSetting.setInstantApp(false /*instantApp*/, userId);
15140            }
15141        } else {
15142            for (int currentUserId : sUserManager.getUserIds()) {
15143                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
15144                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
15145                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
15146                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
15147                }
15148            }
15149        }
15150    }
15151
15152    boolean isUserRestricted(int userId, String restrictionKey) {
15153        Bundle restrictions = sUserManager.getUserRestrictions(userId);
15154        if (restrictions.getBoolean(restrictionKey, false)) {
15155            Log.w(TAG, "User is restricted: " + restrictionKey);
15156            return true;
15157        }
15158        return false;
15159    }
15160
15161    @Override
15162    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15163            int userId) {
15164        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15165        final int callingUid = Binder.getCallingUid();
15166        enforceCrossUserPermission(callingUid, userId,
15167                true /* requireFullPermission */, true /* checkShell */,
15168                "setPackagesSuspended for user " + userId);
15169
15170        if (ArrayUtils.isEmpty(packageNames)) {
15171            return packageNames;
15172        }
15173
15174        // List of package names for whom the suspended state has changed.
15175        List<String> changedPackages = new ArrayList<>(packageNames.length);
15176        // List of package names for whom the suspended state is not set as requested in this
15177        // method.
15178        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15179        long callingId = Binder.clearCallingIdentity();
15180        try {
15181            for (int i = 0; i < packageNames.length; i++) {
15182                String packageName = packageNames[i];
15183                boolean changed = false;
15184                final int appId;
15185                synchronized (mPackages) {
15186                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15187                    if (pkgSetting == null
15188                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15189                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15190                                + "\". Skipping suspending/un-suspending.");
15191                        unactionedPackages.add(packageName);
15192                        continue;
15193                    }
15194                    appId = pkgSetting.appId;
15195                    if (pkgSetting.getSuspended(userId) != suspended) {
15196                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15197                            unactionedPackages.add(packageName);
15198                            continue;
15199                        }
15200                        pkgSetting.setSuspended(suspended, userId);
15201                        mSettings.writePackageRestrictionsLPr(userId);
15202                        changed = true;
15203                        changedPackages.add(packageName);
15204                    }
15205                }
15206
15207                if (changed && suspended) {
15208                    killApplication(packageName, UserHandle.getUid(userId, appId),
15209                            "suspending package");
15210                }
15211            }
15212        } finally {
15213            Binder.restoreCallingIdentity(callingId);
15214        }
15215
15216        if (!changedPackages.isEmpty()) {
15217            sendPackagesSuspendedForUser(changedPackages.toArray(
15218                    new String[changedPackages.size()]), userId, suspended);
15219        }
15220
15221        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15222    }
15223
15224    @Override
15225    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15226        final int callingUid = Binder.getCallingUid();
15227        enforceCrossUserPermission(callingUid, userId,
15228                true /* requireFullPermission */, false /* checkShell */,
15229                "isPackageSuspendedForUser for user " + userId);
15230        synchronized (mPackages) {
15231            final PackageSetting ps = mSettings.mPackages.get(packageName);
15232            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15233                throw new IllegalArgumentException("Unknown target package: " + packageName);
15234            }
15235            return ps.getSuspended(userId);
15236        }
15237    }
15238
15239    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15240        if (isPackageDeviceAdmin(packageName, userId)) {
15241            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15242                    + "\": has an active device admin");
15243            return false;
15244        }
15245
15246        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15247        if (packageName.equals(activeLauncherPackageName)) {
15248            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15249                    + "\": contains the active launcher");
15250            return false;
15251        }
15252
15253        if (packageName.equals(mRequiredInstallerPackage)) {
15254            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15255                    + "\": required for package installation");
15256            return false;
15257        }
15258
15259        if (packageName.equals(mRequiredUninstallerPackage)) {
15260            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15261                    + "\": required for package uninstallation");
15262            return false;
15263        }
15264
15265        if (packageName.equals(mRequiredVerifierPackage)) {
15266            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15267                    + "\": required for package verification");
15268            return false;
15269        }
15270
15271        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15272            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15273                    + "\": is the default dialer");
15274            return false;
15275        }
15276
15277        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15278            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15279                    + "\": protected package");
15280            return false;
15281        }
15282
15283        // Cannot suspend static shared libs as they are considered
15284        // a part of the using app (emulating static linking). Also
15285        // static libs are installed always on internal storage.
15286        PackageParser.Package pkg = mPackages.get(packageName);
15287        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15288            Slog.w(TAG, "Cannot suspend package: " + packageName
15289                    + " providing static shared library: "
15290                    + pkg.staticSharedLibName);
15291            return false;
15292        }
15293
15294        return true;
15295    }
15296
15297    private String getActiveLauncherPackageName(int userId) {
15298        Intent intent = new Intent(Intent.ACTION_MAIN);
15299        intent.addCategory(Intent.CATEGORY_HOME);
15300        ResolveInfo resolveInfo = resolveIntent(
15301                intent,
15302                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15303                PackageManager.MATCH_DEFAULT_ONLY,
15304                userId);
15305
15306        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15307    }
15308
15309    private String getDefaultDialerPackageName(int userId) {
15310        synchronized (mPackages) {
15311            return mSettings.getDefaultDialerPackageNameLPw(userId);
15312        }
15313    }
15314
15315    @Override
15316    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15317        mContext.enforceCallingOrSelfPermission(
15318                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15319                "Only package verification agents can verify applications");
15320
15321        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15322        final PackageVerificationResponse response = new PackageVerificationResponse(
15323                verificationCode, Binder.getCallingUid());
15324        msg.arg1 = id;
15325        msg.obj = response;
15326        mHandler.sendMessage(msg);
15327    }
15328
15329    @Override
15330    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15331            long millisecondsToDelay) {
15332        mContext.enforceCallingOrSelfPermission(
15333                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15334                "Only package verification agents can extend verification timeouts");
15335
15336        final PackageVerificationState state = mPendingVerification.get(id);
15337        final PackageVerificationResponse response = new PackageVerificationResponse(
15338                verificationCodeAtTimeout, Binder.getCallingUid());
15339
15340        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15341            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15342        }
15343        if (millisecondsToDelay < 0) {
15344            millisecondsToDelay = 0;
15345        }
15346        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15347                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15348            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15349        }
15350
15351        if ((state != null) && !state.timeoutExtended()) {
15352            state.extendTimeout();
15353
15354            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15355            msg.arg1 = id;
15356            msg.obj = response;
15357            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15358        }
15359    }
15360
15361    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15362            int verificationCode, UserHandle user) {
15363        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15364        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15365        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15366        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15367        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15368
15369        mContext.sendBroadcastAsUser(intent, user,
15370                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15371    }
15372
15373    private ComponentName matchComponentForVerifier(String packageName,
15374            List<ResolveInfo> receivers) {
15375        ActivityInfo targetReceiver = null;
15376
15377        final int NR = receivers.size();
15378        for (int i = 0; i < NR; i++) {
15379            final ResolveInfo info = receivers.get(i);
15380            if (info.activityInfo == null) {
15381                continue;
15382            }
15383
15384            if (packageName.equals(info.activityInfo.packageName)) {
15385                targetReceiver = info.activityInfo;
15386                break;
15387            }
15388        }
15389
15390        if (targetReceiver == null) {
15391            return null;
15392        }
15393
15394        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15395    }
15396
15397    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15398            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15399        if (pkgInfo.verifiers.length == 0) {
15400            return null;
15401        }
15402
15403        final int N = pkgInfo.verifiers.length;
15404        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15405        for (int i = 0; i < N; i++) {
15406            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15407
15408            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15409                    receivers);
15410            if (comp == null) {
15411                continue;
15412            }
15413
15414            final int verifierUid = getUidForVerifier(verifierInfo);
15415            if (verifierUid == -1) {
15416                continue;
15417            }
15418
15419            if (DEBUG_VERIFY) {
15420                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15421                        + " with the correct signature");
15422            }
15423            sufficientVerifiers.add(comp);
15424            verificationState.addSufficientVerifier(verifierUid);
15425        }
15426
15427        return sufficientVerifiers;
15428    }
15429
15430    private int getUidForVerifier(VerifierInfo verifierInfo) {
15431        synchronized (mPackages) {
15432            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15433            if (pkg == null) {
15434                return -1;
15435            } else if (pkg.mSignatures.length != 1) {
15436                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15437                        + " has more than one signature; ignoring");
15438                return -1;
15439            }
15440
15441            /*
15442             * If the public key of the package's signature does not match
15443             * our expected public key, then this is a different package and
15444             * we should skip.
15445             */
15446
15447            final byte[] expectedPublicKey;
15448            try {
15449                final Signature verifierSig = pkg.mSignatures[0];
15450                final PublicKey publicKey = verifierSig.getPublicKey();
15451                expectedPublicKey = publicKey.getEncoded();
15452            } catch (CertificateException e) {
15453                return -1;
15454            }
15455
15456            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15457
15458            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15459                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15460                        + " does not have the expected public key; ignoring");
15461                return -1;
15462            }
15463
15464            return pkg.applicationInfo.uid;
15465        }
15466    }
15467
15468    @Override
15469    public void finishPackageInstall(int token, boolean didLaunch) {
15470        enforceSystemOrRoot("Only the system is allowed to finish installs");
15471
15472        if (DEBUG_INSTALL) {
15473            Slog.v(TAG, "BM finishing package install for " + token);
15474        }
15475        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15476
15477        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15478        mHandler.sendMessage(msg);
15479    }
15480
15481    /**
15482     * Get the verification agent timeout.  Used for both the APK verifier and the
15483     * intent filter verifier.
15484     *
15485     * @return verification timeout in milliseconds
15486     */
15487    private long getVerificationTimeout() {
15488        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15489                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15490                DEFAULT_VERIFICATION_TIMEOUT);
15491    }
15492
15493    /**
15494     * Get the default verification agent response code.
15495     *
15496     * @return default verification response code
15497     */
15498    private int getDefaultVerificationResponse(UserHandle user) {
15499        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15500            return PackageManager.VERIFICATION_REJECT;
15501        }
15502        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15503                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15504                DEFAULT_VERIFICATION_RESPONSE);
15505    }
15506
15507    /**
15508     * Check whether or not package verification has been enabled.
15509     *
15510     * @return true if verification should be performed
15511     */
15512    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15513        if (!DEFAULT_VERIFY_ENABLE) {
15514            return false;
15515        }
15516
15517        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15518
15519        // Check if installing from ADB
15520        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15521            // Do not run verification in a test harness environment
15522            if (ActivityManager.isRunningInTestHarness()) {
15523                return false;
15524            }
15525            if (ensureVerifyAppsEnabled) {
15526                return true;
15527            }
15528            // Check if the developer does not want package verification for ADB installs
15529            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15530                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15531                return false;
15532            }
15533        } else {
15534            // only when not installed from ADB, skip verification for instant apps when
15535            // the installer and verifier are the same.
15536            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15537                if (mInstantAppInstallerActivity != null
15538                        && mInstantAppInstallerActivity.packageName.equals(
15539                                mRequiredVerifierPackage)) {
15540                    try {
15541                        mContext.getSystemService(AppOpsManager.class)
15542                                .checkPackage(installerUid, mRequiredVerifierPackage);
15543                        if (DEBUG_VERIFY) {
15544                            Slog.i(TAG, "disable verification for instant app");
15545                        }
15546                        return false;
15547                    } catch (SecurityException ignore) { }
15548                }
15549            }
15550        }
15551
15552        if (ensureVerifyAppsEnabled) {
15553            return true;
15554        }
15555
15556        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15557                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15558    }
15559
15560    @Override
15561    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15562            throws RemoteException {
15563        mContext.enforceCallingOrSelfPermission(
15564                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15565                "Only intentfilter verification agents can verify applications");
15566
15567        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15568        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15569                Binder.getCallingUid(), verificationCode, failedDomains);
15570        msg.arg1 = id;
15571        msg.obj = response;
15572        mHandler.sendMessage(msg);
15573    }
15574
15575    @Override
15576    public int getIntentVerificationStatus(String packageName, int userId) {
15577        final int callingUid = Binder.getCallingUid();
15578        if (UserHandle.getUserId(callingUid) != userId) {
15579            mContext.enforceCallingOrSelfPermission(
15580                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15581                    "getIntentVerificationStatus" + userId);
15582        }
15583        if (getInstantAppPackageName(callingUid) != null) {
15584            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15585        }
15586        synchronized (mPackages) {
15587            final PackageSetting ps = mSettings.mPackages.get(packageName);
15588            if (ps == null
15589                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15590                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15591            }
15592            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15593        }
15594    }
15595
15596    @Override
15597    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15598        mContext.enforceCallingOrSelfPermission(
15599                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15600
15601        boolean result = false;
15602        synchronized (mPackages) {
15603            final PackageSetting ps = mSettings.mPackages.get(packageName);
15604            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15605                return false;
15606            }
15607            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15608        }
15609        if (result) {
15610            scheduleWritePackageRestrictionsLocked(userId);
15611        }
15612        return result;
15613    }
15614
15615    @Override
15616    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15617            String packageName) {
15618        final int callingUid = Binder.getCallingUid();
15619        if (getInstantAppPackageName(callingUid) != null) {
15620            return ParceledListSlice.emptyList();
15621        }
15622        synchronized (mPackages) {
15623            final PackageSetting ps = mSettings.mPackages.get(packageName);
15624            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15625                return ParceledListSlice.emptyList();
15626            }
15627            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15628        }
15629    }
15630
15631    @Override
15632    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15633        if (TextUtils.isEmpty(packageName)) {
15634            return ParceledListSlice.emptyList();
15635        }
15636        final int callingUid = Binder.getCallingUid();
15637        final int callingUserId = UserHandle.getUserId(callingUid);
15638        synchronized (mPackages) {
15639            PackageParser.Package pkg = mPackages.get(packageName);
15640            if (pkg == null || pkg.activities == null) {
15641                return ParceledListSlice.emptyList();
15642            }
15643            if (pkg.mExtras == null) {
15644                return ParceledListSlice.emptyList();
15645            }
15646            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15647            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15648                return ParceledListSlice.emptyList();
15649            }
15650            final int count = pkg.activities.size();
15651            ArrayList<IntentFilter> result = new ArrayList<>();
15652            for (int n=0; n<count; n++) {
15653                PackageParser.Activity activity = pkg.activities.get(n);
15654                if (activity.intents != null && activity.intents.size() > 0) {
15655                    result.addAll(activity.intents);
15656                }
15657            }
15658            return new ParceledListSlice<>(result);
15659        }
15660    }
15661
15662    @Override
15663    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15664        mContext.enforceCallingOrSelfPermission(
15665                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15666        if (UserHandle.getCallingUserId() != userId) {
15667            mContext.enforceCallingOrSelfPermission(
15668                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15669        }
15670
15671        synchronized (mPackages) {
15672            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15673            if (packageName != null) {
15674                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15675                        packageName, userId);
15676            }
15677            return result;
15678        }
15679    }
15680
15681    @Override
15682    public String getDefaultBrowserPackageName(int userId) {
15683        if (UserHandle.getCallingUserId() != userId) {
15684            mContext.enforceCallingOrSelfPermission(
15685                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15686        }
15687        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15688            return null;
15689        }
15690        synchronized (mPackages) {
15691            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15692        }
15693    }
15694
15695    /**
15696     * Get the "allow unknown sources" setting.
15697     *
15698     * @return the current "allow unknown sources" setting
15699     */
15700    private int getUnknownSourcesSettings() {
15701        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15702                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15703                -1);
15704    }
15705
15706    @Override
15707    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15708        final int callingUid = Binder.getCallingUid();
15709        if (getInstantAppPackageName(callingUid) != null) {
15710            return;
15711        }
15712        // writer
15713        synchronized (mPackages) {
15714            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15715            if (targetPackageSetting == null
15716                    || filterAppAccessLPr(
15717                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15718                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15719            }
15720
15721            PackageSetting installerPackageSetting;
15722            if (installerPackageName != null) {
15723                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15724                if (installerPackageSetting == null) {
15725                    throw new IllegalArgumentException("Unknown installer package: "
15726                            + installerPackageName);
15727                }
15728            } else {
15729                installerPackageSetting = null;
15730            }
15731
15732            Signature[] callerSignature;
15733            Object obj = mSettings.getUserIdLPr(callingUid);
15734            if (obj != null) {
15735                if (obj instanceof SharedUserSetting) {
15736                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15737                } else if (obj instanceof PackageSetting) {
15738                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15739                } else {
15740                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15741                }
15742            } else {
15743                throw new SecurityException("Unknown calling UID: " + callingUid);
15744            }
15745
15746            // Verify: can't set installerPackageName to a package that is
15747            // not signed with the same cert as the caller.
15748            if (installerPackageSetting != null) {
15749                if (compareSignatures(callerSignature,
15750                        installerPackageSetting.signatures.mSignatures)
15751                        != PackageManager.SIGNATURE_MATCH) {
15752                    throw new SecurityException(
15753                            "Caller does not have same cert as new installer package "
15754                            + installerPackageName);
15755                }
15756            }
15757
15758            // Verify: if target already has an installer package, it must
15759            // be signed with the same cert as the caller.
15760            if (targetPackageSetting.installerPackageName != null) {
15761                PackageSetting setting = mSettings.mPackages.get(
15762                        targetPackageSetting.installerPackageName);
15763                // If the currently set package isn't valid, then it's always
15764                // okay to change it.
15765                if (setting != null) {
15766                    if (compareSignatures(callerSignature,
15767                            setting.signatures.mSignatures)
15768                            != PackageManager.SIGNATURE_MATCH) {
15769                        throw new SecurityException(
15770                                "Caller does not have same cert as old installer package "
15771                                + targetPackageSetting.installerPackageName);
15772                    }
15773                }
15774            }
15775
15776            // Okay!
15777            targetPackageSetting.installerPackageName = installerPackageName;
15778            if (installerPackageName != null) {
15779                mSettings.mInstallerPackages.add(installerPackageName);
15780            }
15781            scheduleWriteSettingsLocked();
15782        }
15783    }
15784
15785    @Override
15786    public void setApplicationCategoryHint(String packageName, int categoryHint,
15787            String callerPackageName) {
15788        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15789            throw new SecurityException("Instant applications don't have access to this method");
15790        }
15791        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15792                callerPackageName);
15793        synchronized (mPackages) {
15794            PackageSetting ps = mSettings.mPackages.get(packageName);
15795            if (ps == null) {
15796                throw new IllegalArgumentException("Unknown target package " + packageName);
15797            }
15798            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15799                throw new IllegalArgumentException("Unknown target package " + packageName);
15800            }
15801            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15802                throw new IllegalArgumentException("Calling package " + callerPackageName
15803                        + " is not installer for " + packageName);
15804            }
15805
15806            if (ps.categoryHint != categoryHint) {
15807                ps.categoryHint = categoryHint;
15808                scheduleWriteSettingsLocked();
15809            }
15810        }
15811    }
15812
15813    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15814        // Queue up an async operation since the package installation may take a little while.
15815        mHandler.post(new Runnable() {
15816            public void run() {
15817                mHandler.removeCallbacks(this);
15818                 // Result object to be returned
15819                PackageInstalledInfo res = new PackageInstalledInfo();
15820                res.setReturnCode(currentStatus);
15821                res.uid = -1;
15822                res.pkg = null;
15823                res.removedInfo = null;
15824                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15825                    args.doPreInstall(res.returnCode);
15826                    synchronized (mInstallLock) {
15827                        installPackageTracedLI(args, res);
15828                    }
15829                    args.doPostInstall(res.returnCode, res.uid);
15830                }
15831
15832                // A restore should be performed at this point if (a) the install
15833                // succeeded, (b) the operation is not an update, and (c) the new
15834                // package has not opted out of backup participation.
15835                final boolean update = res.removedInfo != null
15836                        && res.removedInfo.removedPackage != null;
15837                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15838                boolean doRestore = !update
15839                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15840
15841                // Set up the post-install work request bookkeeping.  This will be used
15842                // and cleaned up by the post-install event handling regardless of whether
15843                // there's a restore pass performed.  Token values are >= 1.
15844                int token;
15845                if (mNextInstallToken < 0) mNextInstallToken = 1;
15846                token = mNextInstallToken++;
15847
15848                PostInstallData data = new PostInstallData(args, res);
15849                mRunningInstalls.put(token, data);
15850                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15851
15852                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15853                    // Pass responsibility to the Backup Manager.  It will perform a
15854                    // restore if appropriate, then pass responsibility back to the
15855                    // Package Manager to run the post-install observer callbacks
15856                    // and broadcasts.
15857                    IBackupManager bm = IBackupManager.Stub.asInterface(
15858                            ServiceManager.getService(Context.BACKUP_SERVICE));
15859                    if (bm != null) {
15860                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15861                                + " to BM for possible restore");
15862                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15863                        try {
15864                            // TODO: http://b/22388012
15865                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15866                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15867                            } else {
15868                                doRestore = false;
15869                            }
15870                        } catch (RemoteException e) {
15871                            // can't happen; the backup manager is local
15872                        } catch (Exception e) {
15873                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15874                            doRestore = false;
15875                        }
15876                    } else {
15877                        Slog.e(TAG, "Backup Manager not found!");
15878                        doRestore = false;
15879                    }
15880                }
15881
15882                if (!doRestore) {
15883                    // No restore possible, or the Backup Manager was mysteriously not
15884                    // available -- just fire the post-install work request directly.
15885                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15886
15887                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15888
15889                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15890                    mHandler.sendMessage(msg);
15891                }
15892            }
15893        });
15894    }
15895
15896    /**
15897     * Callback from PackageSettings whenever an app is first transitioned out of the
15898     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15899     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15900     * here whether the app is the target of an ongoing install, and only send the
15901     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15902     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15903     * handling.
15904     */
15905    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15906        // Serialize this with the rest of the install-process message chain.  In the
15907        // restore-at-install case, this Runnable will necessarily run before the
15908        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15909        // are coherent.  In the non-restore case, the app has already completed install
15910        // and been launched through some other means, so it is not in a problematic
15911        // state for observers to see the FIRST_LAUNCH signal.
15912        mHandler.post(new Runnable() {
15913            @Override
15914            public void run() {
15915                for (int i = 0; i < mRunningInstalls.size(); i++) {
15916                    final PostInstallData data = mRunningInstalls.valueAt(i);
15917                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15918                        continue;
15919                    }
15920                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15921                        // right package; but is it for the right user?
15922                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15923                            if (userId == data.res.newUsers[uIndex]) {
15924                                if (DEBUG_BACKUP) {
15925                                    Slog.i(TAG, "Package " + pkgName
15926                                            + " being restored so deferring FIRST_LAUNCH");
15927                                }
15928                                return;
15929                            }
15930                        }
15931                    }
15932                }
15933                // didn't find it, so not being restored
15934                if (DEBUG_BACKUP) {
15935                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15936                }
15937                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15938            }
15939        });
15940    }
15941
15942    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15943        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15944                installerPkg, null, userIds);
15945    }
15946
15947    private abstract class HandlerParams {
15948        private static final int MAX_RETRIES = 4;
15949
15950        /**
15951         * Number of times startCopy() has been attempted and had a non-fatal
15952         * error.
15953         */
15954        private int mRetries = 0;
15955
15956        /** User handle for the user requesting the information or installation. */
15957        private final UserHandle mUser;
15958        String traceMethod;
15959        int traceCookie;
15960
15961        HandlerParams(UserHandle user) {
15962            mUser = user;
15963        }
15964
15965        UserHandle getUser() {
15966            return mUser;
15967        }
15968
15969        HandlerParams setTraceMethod(String traceMethod) {
15970            this.traceMethod = traceMethod;
15971            return this;
15972        }
15973
15974        HandlerParams setTraceCookie(int traceCookie) {
15975            this.traceCookie = traceCookie;
15976            return this;
15977        }
15978
15979        final boolean startCopy() {
15980            boolean res;
15981            try {
15982                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15983
15984                if (++mRetries > MAX_RETRIES) {
15985                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15986                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15987                    handleServiceError();
15988                    return false;
15989                } else {
15990                    handleStartCopy();
15991                    res = true;
15992                }
15993            } catch (RemoteException e) {
15994                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15995                mHandler.sendEmptyMessage(MCS_RECONNECT);
15996                res = false;
15997            }
15998            handleReturnCode();
15999            return res;
16000        }
16001
16002        final void serviceError() {
16003            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
16004            handleServiceError();
16005            handleReturnCode();
16006        }
16007
16008        abstract void handleStartCopy() throws RemoteException;
16009        abstract void handleServiceError();
16010        abstract void handleReturnCode();
16011    }
16012
16013    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
16014        for (File path : paths) {
16015            try {
16016                mcs.clearDirectory(path.getAbsolutePath());
16017            } catch (RemoteException e) {
16018            }
16019        }
16020    }
16021
16022    static class OriginInfo {
16023        /**
16024         * Location where install is coming from, before it has been
16025         * copied/renamed into place. This could be a single monolithic APK
16026         * file, or a cluster directory. This location may be untrusted.
16027         */
16028        final File file;
16029        final String cid;
16030
16031        /**
16032         * Flag indicating that {@link #file} or {@link #cid} has already been
16033         * staged, meaning downstream users don't need to defensively copy the
16034         * contents.
16035         */
16036        final boolean staged;
16037
16038        /**
16039         * Flag indicating that {@link #file} or {@link #cid} is an already
16040         * installed app that is being moved.
16041         */
16042        final boolean existing;
16043
16044        final String resolvedPath;
16045        final File resolvedFile;
16046
16047        static OriginInfo fromNothing() {
16048            return new OriginInfo(null, null, false, false);
16049        }
16050
16051        static OriginInfo fromUntrustedFile(File file) {
16052            return new OriginInfo(file, null, false, false);
16053        }
16054
16055        static OriginInfo fromExistingFile(File file) {
16056            return new OriginInfo(file, null, false, true);
16057        }
16058
16059        static OriginInfo fromStagedFile(File file) {
16060            return new OriginInfo(file, null, true, false);
16061        }
16062
16063        static OriginInfo fromStagedContainer(String cid) {
16064            return new OriginInfo(null, cid, true, false);
16065        }
16066
16067        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
16068            this.file = file;
16069            this.cid = cid;
16070            this.staged = staged;
16071            this.existing = existing;
16072
16073            if (cid != null) {
16074                resolvedPath = PackageHelper.getSdDir(cid);
16075                resolvedFile = new File(resolvedPath);
16076            } else if (file != null) {
16077                resolvedPath = file.getAbsolutePath();
16078                resolvedFile = file;
16079            } else {
16080                resolvedPath = null;
16081                resolvedFile = null;
16082            }
16083        }
16084    }
16085
16086    static class MoveInfo {
16087        final int moveId;
16088        final String fromUuid;
16089        final String toUuid;
16090        final String packageName;
16091        final String dataAppName;
16092        final int appId;
16093        final String seinfo;
16094        final int targetSdkVersion;
16095
16096        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
16097                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
16098            this.moveId = moveId;
16099            this.fromUuid = fromUuid;
16100            this.toUuid = toUuid;
16101            this.packageName = packageName;
16102            this.dataAppName = dataAppName;
16103            this.appId = appId;
16104            this.seinfo = seinfo;
16105            this.targetSdkVersion = targetSdkVersion;
16106        }
16107    }
16108
16109    static class VerificationInfo {
16110        /** A constant used to indicate that a uid value is not present. */
16111        public static final int NO_UID = -1;
16112
16113        /** URI referencing where the package was downloaded from. */
16114        final Uri originatingUri;
16115
16116        /** HTTP referrer URI associated with the originatingURI. */
16117        final Uri referrer;
16118
16119        /** UID of the application that the install request originated from. */
16120        final int originatingUid;
16121
16122        /** UID of application requesting the install */
16123        final int installerUid;
16124
16125        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
16126            this.originatingUri = originatingUri;
16127            this.referrer = referrer;
16128            this.originatingUid = originatingUid;
16129            this.installerUid = installerUid;
16130        }
16131    }
16132
16133    class InstallParams extends HandlerParams {
16134        final OriginInfo origin;
16135        final MoveInfo move;
16136        final IPackageInstallObserver2 observer;
16137        int installFlags;
16138        final String installerPackageName;
16139        final String volumeUuid;
16140        private InstallArgs mArgs;
16141        private int mRet;
16142        final String packageAbiOverride;
16143        final String[] grantedRuntimePermissions;
16144        final VerificationInfo verificationInfo;
16145        final Certificate[][] certificates;
16146        final int installReason;
16147
16148        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16149                int installFlags, String installerPackageName, String volumeUuid,
16150                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16151                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16152            super(user);
16153            this.origin = origin;
16154            this.move = move;
16155            this.observer = observer;
16156            this.installFlags = installFlags;
16157            this.installerPackageName = installerPackageName;
16158            this.volumeUuid = volumeUuid;
16159            this.verificationInfo = verificationInfo;
16160            this.packageAbiOverride = packageAbiOverride;
16161            this.grantedRuntimePermissions = grantedPermissions;
16162            this.certificates = certificates;
16163            this.installReason = installReason;
16164        }
16165
16166        @Override
16167        public String toString() {
16168            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16169                    + " file=" + origin.file + " cid=" + origin.cid + "}";
16170        }
16171
16172        private int installLocationPolicy(PackageInfoLite pkgLite) {
16173            String packageName = pkgLite.packageName;
16174            int installLocation = pkgLite.installLocation;
16175            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16176            // reader
16177            synchronized (mPackages) {
16178                // Currently installed package which the new package is attempting to replace or
16179                // null if no such package is installed.
16180                PackageParser.Package installedPkg = mPackages.get(packageName);
16181                // Package which currently owns the data which the new package will own if installed.
16182                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16183                // will be null whereas dataOwnerPkg will contain information about the package
16184                // which was uninstalled while keeping its data.
16185                PackageParser.Package dataOwnerPkg = installedPkg;
16186                if (dataOwnerPkg  == null) {
16187                    PackageSetting ps = mSettings.mPackages.get(packageName);
16188                    if (ps != null) {
16189                        dataOwnerPkg = ps.pkg;
16190                    }
16191                }
16192
16193                if (dataOwnerPkg != null) {
16194                    // If installed, the package will get access to data left on the device by its
16195                    // predecessor. As a security measure, this is permited only if this is not a
16196                    // version downgrade or if the predecessor package is marked as debuggable and
16197                    // a downgrade is explicitly requested.
16198                    //
16199                    // On debuggable platform builds, downgrades are permitted even for
16200                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16201                    // not offer security guarantees and thus it's OK to disable some security
16202                    // mechanisms to make debugging/testing easier on those builds. However, even on
16203                    // debuggable builds downgrades of packages are permitted only if requested via
16204                    // installFlags. This is because we aim to keep the behavior of debuggable
16205                    // platform builds as close as possible to the behavior of non-debuggable
16206                    // platform builds.
16207                    final boolean downgradeRequested =
16208                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16209                    final boolean packageDebuggable =
16210                                (dataOwnerPkg.applicationInfo.flags
16211                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16212                    final boolean downgradePermitted =
16213                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16214                    if (!downgradePermitted) {
16215                        try {
16216                            checkDowngrade(dataOwnerPkg, pkgLite);
16217                        } catch (PackageManagerException e) {
16218                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16219                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16220                        }
16221                    }
16222                }
16223
16224                if (installedPkg != null) {
16225                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16226                        // Check for updated system application.
16227                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16228                            if (onSd) {
16229                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16230                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16231                            }
16232                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16233                        } else {
16234                            if (onSd) {
16235                                // Install flag overrides everything.
16236                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16237                            }
16238                            // If current upgrade specifies particular preference
16239                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16240                                // Application explicitly specified internal.
16241                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16242                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16243                                // App explictly prefers external. Let policy decide
16244                            } else {
16245                                // Prefer previous location
16246                                if (isExternal(installedPkg)) {
16247                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16248                                }
16249                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16250                            }
16251                        }
16252                    } else {
16253                        // Invalid install. Return error code
16254                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16255                    }
16256                }
16257            }
16258            // All the special cases have been taken care of.
16259            // Return result based on recommended install location.
16260            if (onSd) {
16261                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16262            }
16263            return pkgLite.recommendedInstallLocation;
16264        }
16265
16266        /*
16267         * Invoke remote method to get package information and install
16268         * location values. Override install location based on default
16269         * policy if needed and then create install arguments based
16270         * on the install location.
16271         */
16272        public void handleStartCopy() throws RemoteException {
16273            int ret = PackageManager.INSTALL_SUCCEEDED;
16274
16275            // If we're already staged, we've firmly committed to an install location
16276            if (origin.staged) {
16277                if (origin.file != null) {
16278                    installFlags |= PackageManager.INSTALL_INTERNAL;
16279                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16280                } else if (origin.cid != null) {
16281                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16282                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16283                } else {
16284                    throw new IllegalStateException("Invalid stage location");
16285                }
16286            }
16287
16288            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16289            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16290            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16291            PackageInfoLite pkgLite = null;
16292
16293            if (onInt && onSd) {
16294                // Check if both bits are set.
16295                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16296                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16297            } else if (onSd && ephemeral) {
16298                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16299                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16300            } else {
16301                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16302                        packageAbiOverride);
16303
16304                if (DEBUG_EPHEMERAL && ephemeral) {
16305                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16306                }
16307
16308                /*
16309                 * If we have too little free space, try to free cache
16310                 * before giving up.
16311                 */
16312                if (!origin.staged && pkgLite.recommendedInstallLocation
16313                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16314                    // TODO: focus freeing disk space on the target device
16315                    final StorageManager storage = StorageManager.from(mContext);
16316                    final long lowThreshold = storage.getStorageLowBytes(
16317                            Environment.getDataDirectory());
16318
16319                    final long sizeBytes = mContainerService.calculateInstalledSize(
16320                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16321
16322                    try {
16323                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16324                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16325                                installFlags, packageAbiOverride);
16326                    } catch (InstallerException e) {
16327                        Slog.w(TAG, "Failed to free cache", e);
16328                    }
16329
16330                    /*
16331                     * The cache free must have deleted the file we
16332                     * downloaded to install.
16333                     *
16334                     * TODO: fix the "freeCache" call to not delete
16335                     *       the file we care about.
16336                     */
16337                    if (pkgLite.recommendedInstallLocation
16338                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16339                        pkgLite.recommendedInstallLocation
16340                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16341                    }
16342                }
16343            }
16344
16345            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16346                int loc = pkgLite.recommendedInstallLocation;
16347                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16348                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16349                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16350                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16351                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16352                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16353                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16354                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16355                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16356                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16357                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16358                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16359                } else {
16360                    // Override with defaults if needed.
16361                    loc = installLocationPolicy(pkgLite);
16362                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16363                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16364                    } else if (!onSd && !onInt) {
16365                        // Override install location with flags
16366                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16367                            // Set the flag to install on external media.
16368                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16369                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16370                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16371                            if (DEBUG_EPHEMERAL) {
16372                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16373                            }
16374                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16375                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16376                                    |PackageManager.INSTALL_INTERNAL);
16377                        } else {
16378                            // Make sure the flag for installing on external
16379                            // media is unset
16380                            installFlags |= PackageManager.INSTALL_INTERNAL;
16381                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16382                        }
16383                    }
16384                }
16385            }
16386
16387            final InstallArgs args = createInstallArgs(this);
16388            mArgs = args;
16389
16390            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16391                // TODO: http://b/22976637
16392                // Apps installed for "all" users use the device owner to verify the app
16393                UserHandle verifierUser = getUser();
16394                if (verifierUser == UserHandle.ALL) {
16395                    verifierUser = UserHandle.SYSTEM;
16396                }
16397
16398                /*
16399                 * Determine if we have any installed package verifiers. If we
16400                 * do, then we'll defer to them to verify the packages.
16401                 */
16402                final int requiredUid = mRequiredVerifierPackage == null ? -1
16403                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16404                                verifierUser.getIdentifier());
16405                final int installerUid =
16406                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16407                if (!origin.existing && requiredUid != -1
16408                        && isVerificationEnabled(
16409                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16410                    final Intent verification = new Intent(
16411                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16412                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16413                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16414                            PACKAGE_MIME_TYPE);
16415                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16416
16417                    // Query all live verifiers based on current user state
16418                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16419                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16420                            false /*allowDynamicSplits*/);
16421
16422                    if (DEBUG_VERIFY) {
16423                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16424                                + verification.toString() + " with " + pkgLite.verifiers.length
16425                                + " optional verifiers");
16426                    }
16427
16428                    final int verificationId = mPendingVerificationToken++;
16429
16430                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16431
16432                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16433                            installerPackageName);
16434
16435                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16436                            installFlags);
16437
16438                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16439                            pkgLite.packageName);
16440
16441                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16442                            pkgLite.versionCode);
16443
16444                    if (verificationInfo != null) {
16445                        if (verificationInfo.originatingUri != null) {
16446                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16447                                    verificationInfo.originatingUri);
16448                        }
16449                        if (verificationInfo.referrer != null) {
16450                            verification.putExtra(Intent.EXTRA_REFERRER,
16451                                    verificationInfo.referrer);
16452                        }
16453                        if (verificationInfo.originatingUid >= 0) {
16454                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16455                                    verificationInfo.originatingUid);
16456                        }
16457                        if (verificationInfo.installerUid >= 0) {
16458                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16459                                    verificationInfo.installerUid);
16460                        }
16461                    }
16462
16463                    final PackageVerificationState verificationState = new PackageVerificationState(
16464                            requiredUid, args);
16465
16466                    mPendingVerification.append(verificationId, verificationState);
16467
16468                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16469                            receivers, verificationState);
16470
16471                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16472                    final long idleDuration = getVerificationTimeout();
16473
16474                    /*
16475                     * If any sufficient verifiers were listed in the package
16476                     * manifest, attempt to ask them.
16477                     */
16478                    if (sufficientVerifiers != null) {
16479                        final int N = sufficientVerifiers.size();
16480                        if (N == 0) {
16481                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16482                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16483                        } else {
16484                            for (int i = 0; i < N; i++) {
16485                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16486                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16487                                        verifierComponent.getPackageName(), idleDuration,
16488                                        verifierUser.getIdentifier(), false, "package verifier");
16489
16490                                final Intent sufficientIntent = new Intent(verification);
16491                                sufficientIntent.setComponent(verifierComponent);
16492                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16493                            }
16494                        }
16495                    }
16496
16497                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16498                            mRequiredVerifierPackage, receivers);
16499                    if (ret == PackageManager.INSTALL_SUCCEEDED
16500                            && mRequiredVerifierPackage != null) {
16501                        Trace.asyncTraceBegin(
16502                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16503                        /*
16504                         * Send the intent to the required verification agent,
16505                         * but only start the verification timeout after the
16506                         * target BroadcastReceivers have run.
16507                         */
16508                        verification.setComponent(requiredVerifierComponent);
16509                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16510                                mRequiredVerifierPackage, idleDuration,
16511                                verifierUser.getIdentifier(), false, "package verifier");
16512                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16513                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16514                                new BroadcastReceiver() {
16515                                    @Override
16516                                    public void onReceive(Context context, Intent intent) {
16517                                        final Message msg = mHandler
16518                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16519                                        msg.arg1 = verificationId;
16520                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16521                                    }
16522                                }, null, 0, null, null);
16523
16524                        /*
16525                         * We don't want the copy to proceed until verification
16526                         * succeeds, so null out this field.
16527                         */
16528                        mArgs = null;
16529                    }
16530                } else {
16531                    /*
16532                     * No package verification is enabled, so immediately start
16533                     * the remote call to initiate copy using temporary file.
16534                     */
16535                    ret = args.copyApk(mContainerService, true);
16536                }
16537            }
16538
16539            mRet = ret;
16540        }
16541
16542        @Override
16543        void handleReturnCode() {
16544            // If mArgs is null, then MCS couldn't be reached. When it
16545            // reconnects, it will try again to install. At that point, this
16546            // will succeed.
16547            if (mArgs != null) {
16548                processPendingInstall(mArgs, mRet);
16549            }
16550        }
16551
16552        @Override
16553        void handleServiceError() {
16554            mArgs = createInstallArgs(this);
16555            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16556        }
16557
16558        public boolean isForwardLocked() {
16559            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16560        }
16561    }
16562
16563    /**
16564     * Used during creation of InstallArgs
16565     *
16566     * @param installFlags package installation flags
16567     * @return true if should be installed on external storage
16568     */
16569    private static boolean installOnExternalAsec(int installFlags) {
16570        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16571            return false;
16572        }
16573        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16574            return true;
16575        }
16576        return false;
16577    }
16578
16579    /**
16580     * Used during creation of InstallArgs
16581     *
16582     * @param installFlags package installation flags
16583     * @return true if should be installed as forward locked
16584     */
16585    private static boolean installForwardLocked(int installFlags) {
16586        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16587    }
16588
16589    private InstallArgs createInstallArgs(InstallParams params) {
16590        if (params.move != null) {
16591            return new MoveInstallArgs(params);
16592        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16593            return new AsecInstallArgs(params);
16594        } else {
16595            return new FileInstallArgs(params);
16596        }
16597    }
16598
16599    /**
16600     * Create args that describe an existing installed package. Typically used
16601     * when cleaning up old installs, or used as a move source.
16602     */
16603    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16604            String resourcePath, String[] instructionSets) {
16605        final boolean isInAsec;
16606        if (installOnExternalAsec(installFlags)) {
16607            /* Apps on SD card are always in ASEC containers. */
16608            isInAsec = true;
16609        } else if (installForwardLocked(installFlags)
16610                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16611            /*
16612             * Forward-locked apps are only in ASEC containers if they're the
16613             * new style
16614             */
16615            isInAsec = true;
16616        } else {
16617            isInAsec = false;
16618        }
16619
16620        if (isInAsec) {
16621            return new AsecInstallArgs(codePath, instructionSets,
16622                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16623        } else {
16624            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16625        }
16626    }
16627
16628    static abstract class InstallArgs {
16629        /** @see InstallParams#origin */
16630        final OriginInfo origin;
16631        /** @see InstallParams#move */
16632        final MoveInfo move;
16633
16634        final IPackageInstallObserver2 observer;
16635        // Always refers to PackageManager flags only
16636        final int installFlags;
16637        final String installerPackageName;
16638        final String volumeUuid;
16639        final UserHandle user;
16640        final String abiOverride;
16641        final String[] installGrantPermissions;
16642        /** If non-null, drop an async trace when the install completes */
16643        final String traceMethod;
16644        final int traceCookie;
16645        final Certificate[][] certificates;
16646        final int installReason;
16647
16648        // The list of instruction sets supported by this app. This is currently
16649        // only used during the rmdex() phase to clean up resources. We can get rid of this
16650        // if we move dex files under the common app path.
16651        /* nullable */ String[] instructionSets;
16652
16653        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16654                int installFlags, String installerPackageName, String volumeUuid,
16655                UserHandle user, String[] instructionSets,
16656                String abiOverride, String[] installGrantPermissions,
16657                String traceMethod, int traceCookie, Certificate[][] certificates,
16658                int installReason) {
16659            this.origin = origin;
16660            this.move = move;
16661            this.installFlags = installFlags;
16662            this.observer = observer;
16663            this.installerPackageName = installerPackageName;
16664            this.volumeUuid = volumeUuid;
16665            this.user = user;
16666            this.instructionSets = instructionSets;
16667            this.abiOverride = abiOverride;
16668            this.installGrantPermissions = installGrantPermissions;
16669            this.traceMethod = traceMethod;
16670            this.traceCookie = traceCookie;
16671            this.certificates = certificates;
16672            this.installReason = installReason;
16673        }
16674
16675        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16676        abstract int doPreInstall(int status);
16677
16678        /**
16679         * Rename package into final resting place. All paths on the given
16680         * scanned package should be updated to reflect the rename.
16681         */
16682        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16683        abstract int doPostInstall(int status, int uid);
16684
16685        /** @see PackageSettingBase#codePathString */
16686        abstract String getCodePath();
16687        /** @see PackageSettingBase#resourcePathString */
16688        abstract String getResourcePath();
16689
16690        // Need installer lock especially for dex file removal.
16691        abstract void cleanUpResourcesLI();
16692        abstract boolean doPostDeleteLI(boolean delete);
16693
16694        /**
16695         * Called before the source arguments are copied. This is used mostly
16696         * for MoveParams when it needs to read the source file to put it in the
16697         * destination.
16698         */
16699        int doPreCopy() {
16700            return PackageManager.INSTALL_SUCCEEDED;
16701        }
16702
16703        /**
16704         * Called after the source arguments are copied. This is used mostly for
16705         * MoveParams when it needs to read the source file to put it in the
16706         * destination.
16707         */
16708        int doPostCopy(int uid) {
16709            return PackageManager.INSTALL_SUCCEEDED;
16710        }
16711
16712        protected boolean isFwdLocked() {
16713            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16714        }
16715
16716        protected boolean isExternalAsec() {
16717            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16718        }
16719
16720        protected boolean isEphemeral() {
16721            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16722        }
16723
16724        UserHandle getUser() {
16725            return user;
16726        }
16727    }
16728
16729    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16730        if (!allCodePaths.isEmpty()) {
16731            if (instructionSets == null) {
16732                throw new IllegalStateException("instructionSet == null");
16733            }
16734            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16735            for (String codePath : allCodePaths) {
16736                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16737                    try {
16738                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16739                    } catch (InstallerException ignored) {
16740                    }
16741                }
16742            }
16743        }
16744    }
16745
16746    /**
16747     * Logic to handle installation of non-ASEC applications, including copying
16748     * and renaming logic.
16749     */
16750    class FileInstallArgs extends InstallArgs {
16751        private File codeFile;
16752        private File resourceFile;
16753
16754        // Example topology:
16755        // /data/app/com.example/base.apk
16756        // /data/app/com.example/split_foo.apk
16757        // /data/app/com.example/lib/arm/libfoo.so
16758        // /data/app/com.example/lib/arm64/libfoo.so
16759        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16760
16761        /** New install */
16762        FileInstallArgs(InstallParams params) {
16763            super(params.origin, params.move, params.observer, params.installFlags,
16764                    params.installerPackageName, params.volumeUuid,
16765                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16766                    params.grantedRuntimePermissions,
16767                    params.traceMethod, params.traceCookie, params.certificates,
16768                    params.installReason);
16769            if (isFwdLocked()) {
16770                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16771            }
16772        }
16773
16774        /** Existing install */
16775        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16776            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16777                    null, null, null, 0, null /*certificates*/,
16778                    PackageManager.INSTALL_REASON_UNKNOWN);
16779            this.codeFile = (codePath != null) ? new File(codePath) : null;
16780            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16781        }
16782
16783        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16784            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16785            try {
16786                return doCopyApk(imcs, temp);
16787            } finally {
16788                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16789            }
16790        }
16791
16792        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16793            if (origin.staged) {
16794                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16795                codeFile = origin.file;
16796                resourceFile = origin.file;
16797                return PackageManager.INSTALL_SUCCEEDED;
16798            }
16799
16800            try {
16801                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16802                final File tempDir =
16803                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16804                codeFile = tempDir;
16805                resourceFile = tempDir;
16806            } catch (IOException e) {
16807                Slog.w(TAG, "Failed to create copy file: " + e);
16808                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16809            }
16810
16811            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16812                @Override
16813                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16814                    if (!FileUtils.isValidExtFilename(name)) {
16815                        throw new IllegalArgumentException("Invalid filename: " + name);
16816                    }
16817                    try {
16818                        final File file = new File(codeFile, name);
16819                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16820                                O_RDWR | O_CREAT, 0644);
16821                        Os.chmod(file.getAbsolutePath(), 0644);
16822                        return new ParcelFileDescriptor(fd);
16823                    } catch (ErrnoException e) {
16824                        throw new RemoteException("Failed to open: " + e.getMessage());
16825                    }
16826                }
16827            };
16828
16829            int ret = PackageManager.INSTALL_SUCCEEDED;
16830            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16831            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16832                Slog.e(TAG, "Failed to copy package");
16833                return ret;
16834            }
16835
16836            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16837            NativeLibraryHelper.Handle handle = null;
16838            try {
16839                handle = NativeLibraryHelper.Handle.create(codeFile);
16840                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16841                        abiOverride);
16842            } catch (IOException e) {
16843                Slog.e(TAG, "Copying native libraries failed", e);
16844                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16845            } finally {
16846                IoUtils.closeQuietly(handle);
16847            }
16848
16849            return ret;
16850        }
16851
16852        int doPreInstall(int status) {
16853            if (status != PackageManager.INSTALL_SUCCEEDED) {
16854                cleanUp();
16855            }
16856            return status;
16857        }
16858
16859        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16860            if (status != PackageManager.INSTALL_SUCCEEDED) {
16861                cleanUp();
16862                return false;
16863            }
16864
16865            final File targetDir = codeFile.getParentFile();
16866            final File beforeCodeFile = codeFile;
16867            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16868
16869            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16870            try {
16871                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16872            } catch (ErrnoException e) {
16873                Slog.w(TAG, "Failed to rename", e);
16874                return false;
16875            }
16876
16877            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16878                Slog.w(TAG, "Failed to restorecon");
16879                return false;
16880            }
16881
16882            // Reflect the rename internally
16883            codeFile = afterCodeFile;
16884            resourceFile = afterCodeFile;
16885
16886            // Reflect the rename in scanned details
16887            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16888            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16889                    afterCodeFile, pkg.baseCodePath));
16890            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16891                    afterCodeFile, pkg.splitCodePaths));
16892
16893            // Reflect the rename in app info
16894            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16895            pkg.setApplicationInfoCodePath(pkg.codePath);
16896            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16897            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16898            pkg.setApplicationInfoResourcePath(pkg.codePath);
16899            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16900            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16901
16902            return true;
16903        }
16904
16905        int doPostInstall(int status, int uid) {
16906            if (status != PackageManager.INSTALL_SUCCEEDED) {
16907                cleanUp();
16908            }
16909            return status;
16910        }
16911
16912        @Override
16913        String getCodePath() {
16914            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16915        }
16916
16917        @Override
16918        String getResourcePath() {
16919            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16920        }
16921
16922        private boolean cleanUp() {
16923            if (codeFile == null || !codeFile.exists()) {
16924                return false;
16925            }
16926
16927            removeCodePathLI(codeFile);
16928
16929            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16930                resourceFile.delete();
16931            }
16932
16933            return true;
16934        }
16935
16936        void cleanUpResourcesLI() {
16937            // Try enumerating all code paths before deleting
16938            List<String> allCodePaths = Collections.EMPTY_LIST;
16939            if (codeFile != null && codeFile.exists()) {
16940                try {
16941                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16942                    allCodePaths = pkg.getAllCodePaths();
16943                } catch (PackageParserException e) {
16944                    // Ignored; we tried our best
16945                }
16946            }
16947
16948            cleanUp();
16949            removeDexFiles(allCodePaths, instructionSets);
16950        }
16951
16952        boolean doPostDeleteLI(boolean delete) {
16953            // XXX err, shouldn't we respect the delete flag?
16954            cleanUpResourcesLI();
16955            return true;
16956        }
16957    }
16958
16959    private boolean isAsecExternal(String cid) {
16960        final String asecPath = PackageHelper.getSdFilesystem(cid);
16961        return !asecPath.startsWith(mAsecInternalPath);
16962    }
16963
16964    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16965            PackageManagerException {
16966        if (copyRet < 0) {
16967            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16968                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16969                throw new PackageManagerException(copyRet, message);
16970            }
16971        }
16972    }
16973
16974    /**
16975     * Extract the StorageManagerService "container ID" from the full code path of an
16976     * .apk.
16977     */
16978    static String cidFromCodePath(String fullCodePath) {
16979        int eidx = fullCodePath.lastIndexOf("/");
16980        String subStr1 = fullCodePath.substring(0, eidx);
16981        int sidx = subStr1.lastIndexOf("/");
16982        return subStr1.substring(sidx+1, eidx);
16983    }
16984
16985    /**
16986     * Logic to handle installation of ASEC applications, including copying and
16987     * renaming logic.
16988     */
16989    class AsecInstallArgs extends InstallArgs {
16990        static final String RES_FILE_NAME = "pkg.apk";
16991        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16992
16993        String cid;
16994        String packagePath;
16995        String resourcePath;
16996
16997        /** New install */
16998        AsecInstallArgs(InstallParams params) {
16999            super(params.origin, params.move, params.observer, params.installFlags,
17000                    params.installerPackageName, params.volumeUuid,
17001                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17002                    params.grantedRuntimePermissions,
17003                    params.traceMethod, params.traceCookie, params.certificates,
17004                    params.installReason);
17005        }
17006
17007        /** Existing install */
17008        AsecInstallArgs(String fullCodePath, String[] instructionSets,
17009                        boolean isExternal, boolean isForwardLocked) {
17010            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
17011                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
17012                    instructionSets, null, null, null, 0, null /*certificates*/,
17013                    PackageManager.INSTALL_REASON_UNKNOWN);
17014            // Hackily pretend we're still looking at a full code path
17015            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
17016                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
17017            }
17018
17019            // Extract cid from fullCodePath
17020            int eidx = fullCodePath.lastIndexOf("/");
17021            String subStr1 = fullCodePath.substring(0, eidx);
17022            int sidx = subStr1.lastIndexOf("/");
17023            cid = subStr1.substring(sidx+1, eidx);
17024            setMountPath(subStr1);
17025        }
17026
17027        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
17028            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
17029                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
17030                    instructionSets, null, null, null, 0, null /*certificates*/,
17031                    PackageManager.INSTALL_REASON_UNKNOWN);
17032            this.cid = cid;
17033            setMountPath(PackageHelper.getSdDir(cid));
17034        }
17035
17036        void createCopyFile() {
17037            cid = mInstallerService.allocateExternalStageCidLegacy();
17038        }
17039
17040        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
17041            if (origin.staged && origin.cid != null) {
17042                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
17043                cid = origin.cid;
17044                setMountPath(PackageHelper.getSdDir(cid));
17045                return PackageManager.INSTALL_SUCCEEDED;
17046            }
17047
17048            if (temp) {
17049                createCopyFile();
17050            } else {
17051                /*
17052                 * Pre-emptively destroy the container since it's destroyed if
17053                 * copying fails due to it existing anyway.
17054                 */
17055                PackageHelper.destroySdDir(cid);
17056            }
17057
17058            final String newMountPath = imcs.copyPackageToContainer(
17059                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
17060                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
17061
17062            if (newMountPath != null) {
17063                setMountPath(newMountPath);
17064                return PackageManager.INSTALL_SUCCEEDED;
17065            } else {
17066                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17067            }
17068        }
17069
17070        @Override
17071        String getCodePath() {
17072            return packagePath;
17073        }
17074
17075        @Override
17076        String getResourcePath() {
17077            return resourcePath;
17078        }
17079
17080        int doPreInstall(int status) {
17081            if (status != PackageManager.INSTALL_SUCCEEDED) {
17082                // Destroy container
17083                PackageHelper.destroySdDir(cid);
17084            } else {
17085                boolean mounted = PackageHelper.isContainerMounted(cid);
17086                if (!mounted) {
17087                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
17088                            Process.SYSTEM_UID);
17089                    if (newMountPath != null) {
17090                        setMountPath(newMountPath);
17091                    } else {
17092                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17093                    }
17094                }
17095            }
17096            return status;
17097        }
17098
17099        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17100            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
17101            String newMountPath = null;
17102            if (PackageHelper.isContainerMounted(cid)) {
17103                // Unmount the container
17104                if (!PackageHelper.unMountSdDir(cid)) {
17105                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
17106                    return false;
17107                }
17108            }
17109            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17110                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
17111                        " which might be stale. Will try to clean up.");
17112                // Clean up the stale container and proceed to recreate.
17113                if (!PackageHelper.destroySdDir(newCacheId)) {
17114                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
17115                    return false;
17116                }
17117                // Successfully cleaned up stale container. Try to rename again.
17118                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17119                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
17120                            + " inspite of cleaning it up.");
17121                    return false;
17122                }
17123            }
17124            if (!PackageHelper.isContainerMounted(newCacheId)) {
17125                Slog.w(TAG, "Mounting container " + newCacheId);
17126                newMountPath = PackageHelper.mountSdDir(newCacheId,
17127                        getEncryptKey(), Process.SYSTEM_UID);
17128            } else {
17129                newMountPath = PackageHelper.getSdDir(newCacheId);
17130            }
17131            if (newMountPath == null) {
17132                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
17133                return false;
17134            }
17135            Log.i(TAG, "Succesfully renamed " + cid +
17136                    " to " + newCacheId +
17137                    " at new path: " + newMountPath);
17138            cid = newCacheId;
17139
17140            final File beforeCodeFile = new File(packagePath);
17141            setMountPath(newMountPath);
17142            final File afterCodeFile = new File(packagePath);
17143
17144            // Reflect the rename in scanned details
17145            pkg.setCodePath(afterCodeFile.getAbsolutePath());
17146            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
17147                    afterCodeFile, pkg.baseCodePath));
17148            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
17149                    afterCodeFile, pkg.splitCodePaths));
17150
17151            // Reflect the rename in app info
17152            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17153            pkg.setApplicationInfoCodePath(pkg.codePath);
17154            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17155            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17156            pkg.setApplicationInfoResourcePath(pkg.codePath);
17157            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17158            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17159
17160            return true;
17161        }
17162
17163        private void setMountPath(String mountPath) {
17164            final File mountFile = new File(mountPath);
17165
17166            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
17167            if (monolithicFile.exists()) {
17168                packagePath = monolithicFile.getAbsolutePath();
17169                if (isFwdLocked()) {
17170                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
17171                } else {
17172                    resourcePath = packagePath;
17173                }
17174            } else {
17175                packagePath = mountFile.getAbsolutePath();
17176                resourcePath = packagePath;
17177            }
17178        }
17179
17180        int doPostInstall(int status, int uid) {
17181            if (status != PackageManager.INSTALL_SUCCEEDED) {
17182                cleanUp();
17183            } else {
17184                final int groupOwner;
17185                final String protectedFile;
17186                if (isFwdLocked()) {
17187                    groupOwner = UserHandle.getSharedAppGid(uid);
17188                    protectedFile = RES_FILE_NAME;
17189                } else {
17190                    groupOwner = -1;
17191                    protectedFile = null;
17192                }
17193
17194                if (uid < Process.FIRST_APPLICATION_UID
17195                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
17196                    Slog.e(TAG, "Failed to finalize " + cid);
17197                    PackageHelper.destroySdDir(cid);
17198                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17199                }
17200
17201                boolean mounted = PackageHelper.isContainerMounted(cid);
17202                if (!mounted) {
17203                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17204                }
17205            }
17206            return status;
17207        }
17208
17209        private void cleanUp() {
17210            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17211
17212            // Destroy secure container
17213            PackageHelper.destroySdDir(cid);
17214        }
17215
17216        private List<String> getAllCodePaths() {
17217            final File codeFile = new File(getCodePath());
17218            if (codeFile != null && codeFile.exists()) {
17219                try {
17220                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17221                    return pkg.getAllCodePaths();
17222                } catch (PackageParserException e) {
17223                    // Ignored; we tried our best
17224                }
17225            }
17226            return Collections.EMPTY_LIST;
17227        }
17228
17229        void cleanUpResourcesLI() {
17230            // Enumerate all code paths before deleting
17231            cleanUpResourcesLI(getAllCodePaths());
17232        }
17233
17234        private void cleanUpResourcesLI(List<String> allCodePaths) {
17235            cleanUp();
17236            removeDexFiles(allCodePaths, instructionSets);
17237        }
17238
17239        String getPackageName() {
17240            return getAsecPackageName(cid);
17241        }
17242
17243        boolean doPostDeleteLI(boolean delete) {
17244            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17245            final List<String> allCodePaths = getAllCodePaths();
17246            boolean mounted = PackageHelper.isContainerMounted(cid);
17247            if (mounted) {
17248                // Unmount first
17249                if (PackageHelper.unMountSdDir(cid)) {
17250                    mounted = false;
17251                }
17252            }
17253            if (!mounted && delete) {
17254                cleanUpResourcesLI(allCodePaths);
17255            }
17256            return !mounted;
17257        }
17258
17259        @Override
17260        int doPreCopy() {
17261            if (isFwdLocked()) {
17262                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17263                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17264                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17265                }
17266            }
17267
17268            return PackageManager.INSTALL_SUCCEEDED;
17269        }
17270
17271        @Override
17272        int doPostCopy(int uid) {
17273            if (isFwdLocked()) {
17274                if (uid < Process.FIRST_APPLICATION_UID
17275                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17276                                RES_FILE_NAME)) {
17277                    Slog.e(TAG, "Failed to finalize " + cid);
17278                    PackageHelper.destroySdDir(cid);
17279                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17280                }
17281            }
17282
17283            return PackageManager.INSTALL_SUCCEEDED;
17284        }
17285    }
17286
17287    /**
17288     * Logic to handle movement of existing installed applications.
17289     */
17290    class MoveInstallArgs extends InstallArgs {
17291        private File codeFile;
17292        private File resourceFile;
17293
17294        /** New install */
17295        MoveInstallArgs(InstallParams params) {
17296            super(params.origin, params.move, params.observer, params.installFlags,
17297                    params.installerPackageName, params.volumeUuid,
17298                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17299                    params.grantedRuntimePermissions,
17300                    params.traceMethod, params.traceCookie, params.certificates,
17301                    params.installReason);
17302        }
17303
17304        int copyApk(IMediaContainerService imcs, boolean temp) {
17305            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17306                    + move.fromUuid + " to " + move.toUuid);
17307            synchronized (mInstaller) {
17308                try {
17309                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17310                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17311                } catch (InstallerException e) {
17312                    Slog.w(TAG, "Failed to move app", e);
17313                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17314                }
17315            }
17316
17317            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17318            resourceFile = codeFile;
17319            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17320
17321            return PackageManager.INSTALL_SUCCEEDED;
17322        }
17323
17324        int doPreInstall(int status) {
17325            if (status != PackageManager.INSTALL_SUCCEEDED) {
17326                cleanUp(move.toUuid);
17327            }
17328            return status;
17329        }
17330
17331        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17332            if (status != PackageManager.INSTALL_SUCCEEDED) {
17333                cleanUp(move.toUuid);
17334                return false;
17335            }
17336
17337            // Reflect the move in app info
17338            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17339            pkg.setApplicationInfoCodePath(pkg.codePath);
17340            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17341            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17342            pkg.setApplicationInfoResourcePath(pkg.codePath);
17343            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17344            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17345
17346            return true;
17347        }
17348
17349        int doPostInstall(int status, int uid) {
17350            if (status == PackageManager.INSTALL_SUCCEEDED) {
17351                cleanUp(move.fromUuid);
17352            } else {
17353                cleanUp(move.toUuid);
17354            }
17355            return status;
17356        }
17357
17358        @Override
17359        String getCodePath() {
17360            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17361        }
17362
17363        @Override
17364        String getResourcePath() {
17365            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17366        }
17367
17368        private boolean cleanUp(String volumeUuid) {
17369            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17370                    move.dataAppName);
17371            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17372            final int[] userIds = sUserManager.getUserIds();
17373            synchronized (mInstallLock) {
17374                // Clean up both app data and code
17375                // All package moves are frozen until finished
17376                for (int userId : userIds) {
17377                    try {
17378                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17379                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17380                    } catch (InstallerException e) {
17381                        Slog.w(TAG, String.valueOf(e));
17382                    }
17383                }
17384                removeCodePathLI(codeFile);
17385            }
17386            return true;
17387        }
17388
17389        void cleanUpResourcesLI() {
17390            throw new UnsupportedOperationException();
17391        }
17392
17393        boolean doPostDeleteLI(boolean delete) {
17394            throw new UnsupportedOperationException();
17395        }
17396    }
17397
17398    static String getAsecPackageName(String packageCid) {
17399        int idx = packageCid.lastIndexOf("-");
17400        if (idx == -1) {
17401            return packageCid;
17402        }
17403        return packageCid.substring(0, idx);
17404    }
17405
17406    // Utility method used to create code paths based on package name and available index.
17407    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17408        String idxStr = "";
17409        int idx = 1;
17410        // Fall back to default value of idx=1 if prefix is not
17411        // part of oldCodePath
17412        if (oldCodePath != null) {
17413            String subStr = oldCodePath;
17414            // Drop the suffix right away
17415            if (suffix != null && subStr.endsWith(suffix)) {
17416                subStr = subStr.substring(0, subStr.length() - suffix.length());
17417            }
17418            // If oldCodePath already contains prefix find out the
17419            // ending index to either increment or decrement.
17420            int sidx = subStr.lastIndexOf(prefix);
17421            if (sidx != -1) {
17422                subStr = subStr.substring(sidx + prefix.length());
17423                if (subStr != null) {
17424                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17425                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17426                    }
17427                    try {
17428                        idx = Integer.parseInt(subStr);
17429                        if (idx <= 1) {
17430                            idx++;
17431                        } else {
17432                            idx--;
17433                        }
17434                    } catch(NumberFormatException e) {
17435                    }
17436                }
17437            }
17438        }
17439        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17440        return prefix + idxStr;
17441    }
17442
17443    private File getNextCodePath(File targetDir, String packageName) {
17444        File result;
17445        SecureRandom random = new SecureRandom();
17446        byte[] bytes = new byte[16];
17447        do {
17448            random.nextBytes(bytes);
17449            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17450            result = new File(targetDir, packageName + "-" + suffix);
17451        } while (result.exists());
17452        return result;
17453    }
17454
17455    // Utility method that returns the relative package path with respect
17456    // to the installation directory. Like say for /data/data/com.test-1.apk
17457    // string com.test-1 is returned.
17458    static String deriveCodePathName(String codePath) {
17459        if (codePath == null) {
17460            return null;
17461        }
17462        final File codeFile = new File(codePath);
17463        final String name = codeFile.getName();
17464        if (codeFile.isDirectory()) {
17465            return name;
17466        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17467            final int lastDot = name.lastIndexOf('.');
17468            return name.substring(0, lastDot);
17469        } else {
17470            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17471            return null;
17472        }
17473    }
17474
17475    static class PackageInstalledInfo {
17476        String name;
17477        int uid;
17478        // The set of users that originally had this package installed.
17479        int[] origUsers;
17480        // The set of users that now have this package installed.
17481        int[] newUsers;
17482        PackageParser.Package pkg;
17483        int returnCode;
17484        String returnMsg;
17485        String installerPackageName;
17486        PackageRemovedInfo removedInfo;
17487        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17488
17489        public void setError(int code, String msg) {
17490            setReturnCode(code);
17491            setReturnMessage(msg);
17492            Slog.w(TAG, msg);
17493        }
17494
17495        public void setError(String msg, PackageParserException e) {
17496            setReturnCode(e.error);
17497            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17498            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17499            for (int i = 0; i < childCount; i++) {
17500                addedChildPackages.valueAt(i).setError(msg, e);
17501            }
17502            Slog.w(TAG, msg, e);
17503        }
17504
17505        public void setError(String msg, PackageManagerException e) {
17506            returnCode = e.error;
17507            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17508            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17509            for (int i = 0; i < childCount; i++) {
17510                addedChildPackages.valueAt(i).setError(msg, e);
17511            }
17512            Slog.w(TAG, msg, e);
17513        }
17514
17515        public void setReturnCode(int returnCode) {
17516            this.returnCode = returnCode;
17517            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17518            for (int i = 0; i < childCount; i++) {
17519                addedChildPackages.valueAt(i).returnCode = returnCode;
17520            }
17521        }
17522
17523        private void setReturnMessage(String returnMsg) {
17524            this.returnMsg = returnMsg;
17525            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17526            for (int i = 0; i < childCount; i++) {
17527                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17528            }
17529        }
17530
17531        // In some error cases we want to convey more info back to the observer
17532        String origPackage;
17533        String origPermission;
17534    }
17535
17536    /*
17537     * Install a non-existing package.
17538     */
17539    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17540            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17541            PackageInstalledInfo res, int installReason) {
17542        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17543
17544        // Remember this for later, in case we need to rollback this install
17545        String pkgName = pkg.packageName;
17546
17547        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17548
17549        synchronized(mPackages) {
17550            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17551            if (renamedPackage != null) {
17552                // A package with the same name is already installed, though
17553                // it has been renamed to an older name.  The package we
17554                // are trying to install should be installed as an update to
17555                // the existing one, but that has not been requested, so bail.
17556                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17557                        + " without first uninstalling package running as "
17558                        + renamedPackage);
17559                return;
17560            }
17561            if (mPackages.containsKey(pkgName)) {
17562                // Don't allow installation over an existing package with the same name.
17563                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17564                        + " without first uninstalling.");
17565                return;
17566            }
17567        }
17568
17569        try {
17570            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17571                    System.currentTimeMillis(), user);
17572
17573            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17574
17575            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17576                prepareAppDataAfterInstallLIF(newPackage);
17577
17578            } else {
17579                // Remove package from internal structures, but keep around any
17580                // data that might have already existed
17581                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17582                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17583            }
17584        } catch (PackageManagerException e) {
17585            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17586        }
17587
17588        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17589    }
17590
17591    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17592        // Can't rotate keys during boot or if sharedUser.
17593        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17594                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17595            return false;
17596        }
17597        // app is using upgradeKeySets; make sure all are valid
17598        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17599        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17600        for (int i = 0; i < upgradeKeySets.length; i++) {
17601            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17602                Slog.wtf(TAG, "Package "
17603                         + (oldPs.name != null ? oldPs.name : "<null>")
17604                         + " contains upgrade-key-set reference to unknown key-set: "
17605                         + upgradeKeySets[i]
17606                         + " reverting to signatures check.");
17607                return false;
17608            }
17609        }
17610        return true;
17611    }
17612
17613    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17614        // Upgrade keysets are being used.  Determine if new package has a superset of the
17615        // required keys.
17616        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17617        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17618        for (int i = 0; i < upgradeKeySets.length; i++) {
17619            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17620            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17621                return true;
17622            }
17623        }
17624        return false;
17625    }
17626
17627    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17628        try (DigestInputStream digestStream =
17629                new DigestInputStream(new FileInputStream(file), digest)) {
17630            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17631        }
17632    }
17633
17634    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17635            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17636            int installReason) {
17637        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17638
17639        final PackageParser.Package oldPackage;
17640        final PackageSetting ps;
17641        final String pkgName = pkg.packageName;
17642        final int[] allUsers;
17643        final int[] installedUsers;
17644
17645        synchronized(mPackages) {
17646            oldPackage = mPackages.get(pkgName);
17647            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17648
17649            // don't allow upgrade to target a release SDK from a pre-release SDK
17650            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17651                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17652            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17653                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17654            if (oldTargetsPreRelease
17655                    && !newTargetsPreRelease
17656                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17657                Slog.w(TAG, "Can't install package targeting released sdk");
17658                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17659                return;
17660            }
17661
17662            ps = mSettings.mPackages.get(pkgName);
17663
17664            // verify signatures are valid
17665            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17666                if (!checkUpgradeKeySetLP(ps, pkg)) {
17667                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17668                            "New package not signed by keys specified by upgrade-keysets: "
17669                                    + pkgName);
17670                    return;
17671                }
17672            } else {
17673                // default to original signature matching
17674                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17675                        != PackageManager.SIGNATURE_MATCH) {
17676                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17677                            "New package has a different signature: " + pkgName);
17678                    return;
17679                }
17680            }
17681
17682            // don't allow a system upgrade unless the upgrade hash matches
17683            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17684                byte[] digestBytes = null;
17685                try {
17686                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17687                    updateDigest(digest, new File(pkg.baseCodePath));
17688                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17689                        for (String path : pkg.splitCodePaths) {
17690                            updateDigest(digest, new File(path));
17691                        }
17692                    }
17693                    digestBytes = digest.digest();
17694                } catch (NoSuchAlgorithmException | IOException e) {
17695                    res.setError(INSTALL_FAILED_INVALID_APK,
17696                            "Could not compute hash: " + pkgName);
17697                    return;
17698                }
17699                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17700                    res.setError(INSTALL_FAILED_INVALID_APK,
17701                            "New package fails restrict-update check: " + pkgName);
17702                    return;
17703                }
17704                // retain upgrade restriction
17705                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17706            }
17707
17708            // Check for shared user id changes
17709            String invalidPackageName =
17710                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17711            if (invalidPackageName != null) {
17712                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17713                        "Package " + invalidPackageName + " tried to change user "
17714                                + oldPackage.mSharedUserId);
17715                return;
17716            }
17717
17718            // In case of rollback, remember per-user/profile install state
17719            allUsers = sUserManager.getUserIds();
17720            installedUsers = ps.queryInstalledUsers(allUsers, true);
17721
17722            // don't allow an upgrade from full to ephemeral
17723            if (isInstantApp) {
17724                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17725                    for (int currentUser : allUsers) {
17726                        if (!ps.getInstantApp(currentUser)) {
17727                            // can't downgrade from full to instant
17728                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17729                                    + " for user: " + currentUser);
17730                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17731                            return;
17732                        }
17733                    }
17734                } else if (!ps.getInstantApp(user.getIdentifier())) {
17735                    // can't downgrade from full to instant
17736                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17737                            + " for user: " + user.getIdentifier());
17738                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17739                    return;
17740                }
17741            }
17742        }
17743
17744        // Update what is removed
17745        res.removedInfo = new PackageRemovedInfo(this);
17746        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17747        res.removedInfo.removedPackage = oldPackage.packageName;
17748        res.removedInfo.installerPackageName = ps.installerPackageName;
17749        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17750        res.removedInfo.isUpdate = true;
17751        res.removedInfo.origUsers = installedUsers;
17752        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17753        for (int i = 0; i < installedUsers.length; i++) {
17754            final int userId = installedUsers[i];
17755            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17756        }
17757
17758        final int childCount = (oldPackage.childPackages != null)
17759                ? oldPackage.childPackages.size() : 0;
17760        for (int i = 0; i < childCount; i++) {
17761            boolean childPackageUpdated = false;
17762            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17763            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17764            if (res.addedChildPackages != null) {
17765                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17766                if (childRes != null) {
17767                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17768                    childRes.removedInfo.removedPackage = childPkg.packageName;
17769                    if (childPs != null) {
17770                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17771                    }
17772                    childRes.removedInfo.isUpdate = true;
17773                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17774                    childPackageUpdated = true;
17775                }
17776            }
17777            if (!childPackageUpdated) {
17778                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17779                childRemovedRes.removedPackage = childPkg.packageName;
17780                if (childPs != null) {
17781                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17782                }
17783                childRemovedRes.isUpdate = false;
17784                childRemovedRes.dataRemoved = true;
17785                synchronized (mPackages) {
17786                    if (childPs != null) {
17787                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17788                    }
17789                }
17790                if (res.removedInfo.removedChildPackages == null) {
17791                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17792                }
17793                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17794            }
17795        }
17796
17797        boolean sysPkg = (isSystemApp(oldPackage));
17798        if (sysPkg) {
17799            // Set the system/privileged flags as needed
17800            final boolean privileged =
17801                    (oldPackage.applicationInfo.privateFlags
17802                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17803            final int systemPolicyFlags = policyFlags
17804                    | PackageParser.PARSE_IS_SYSTEM
17805                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17806
17807            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17808                    user, allUsers, installerPackageName, res, installReason);
17809        } else {
17810            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17811                    user, allUsers, installerPackageName, res, installReason);
17812        }
17813    }
17814
17815    @Override
17816    public List<String> getPreviousCodePaths(String packageName) {
17817        final int callingUid = Binder.getCallingUid();
17818        final List<String> result = new ArrayList<>();
17819        if (getInstantAppPackageName(callingUid) != null) {
17820            return result;
17821        }
17822        final PackageSetting ps = mSettings.mPackages.get(packageName);
17823        if (ps != null
17824                && ps.oldCodePaths != null
17825                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17826            result.addAll(ps.oldCodePaths);
17827        }
17828        return result;
17829    }
17830
17831    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17832            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17833            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17834            int installReason) {
17835        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17836                + deletedPackage);
17837
17838        String pkgName = deletedPackage.packageName;
17839        boolean deletedPkg = true;
17840        boolean addedPkg = false;
17841        boolean updatedSettings = false;
17842        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17843        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17844                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17845
17846        final long origUpdateTime = (pkg.mExtras != null)
17847                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17848
17849        // First delete the existing package while retaining the data directory
17850        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17851                res.removedInfo, true, pkg)) {
17852            // If the existing package wasn't successfully deleted
17853            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17854            deletedPkg = false;
17855        } else {
17856            // Successfully deleted the old package; proceed with replace.
17857
17858            // If deleted package lived in a container, give users a chance to
17859            // relinquish resources before killing.
17860            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17861                if (DEBUG_INSTALL) {
17862                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17863                }
17864                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17865                final ArrayList<String> pkgList = new ArrayList<String>(1);
17866                pkgList.add(deletedPackage.applicationInfo.packageName);
17867                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17868            }
17869
17870            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17871                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17872            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17873
17874            try {
17875                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17876                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17877                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17878                        installReason);
17879
17880                // Update the in-memory copy of the previous code paths.
17881                PackageSetting ps = mSettings.mPackages.get(pkgName);
17882                if (!killApp) {
17883                    if (ps.oldCodePaths == null) {
17884                        ps.oldCodePaths = new ArraySet<>();
17885                    }
17886                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17887                    if (deletedPackage.splitCodePaths != null) {
17888                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17889                    }
17890                } else {
17891                    ps.oldCodePaths = null;
17892                }
17893                if (ps.childPackageNames != null) {
17894                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17895                        final String childPkgName = ps.childPackageNames.get(i);
17896                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17897                        childPs.oldCodePaths = ps.oldCodePaths;
17898                    }
17899                }
17900                // set instant app status, but, only if it's explicitly specified
17901                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17902                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17903                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17904                prepareAppDataAfterInstallLIF(newPackage);
17905                addedPkg = true;
17906                mDexManager.notifyPackageUpdated(newPackage.packageName,
17907                        newPackage.baseCodePath, newPackage.splitCodePaths);
17908            } catch (PackageManagerException e) {
17909                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17910            }
17911        }
17912
17913        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17914            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17915
17916            // Revert all internal state mutations and added folders for the failed install
17917            if (addedPkg) {
17918                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17919                        res.removedInfo, true, null);
17920            }
17921
17922            // Restore the old package
17923            if (deletedPkg) {
17924                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17925                File restoreFile = new File(deletedPackage.codePath);
17926                // Parse old package
17927                boolean oldExternal = isExternal(deletedPackage);
17928                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17929                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17930                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17931                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17932                try {
17933                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17934                            null);
17935                } catch (PackageManagerException e) {
17936                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17937                            + e.getMessage());
17938                    return;
17939                }
17940
17941                synchronized (mPackages) {
17942                    // Ensure the installer package name up to date
17943                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17944
17945                    // Update permissions for restored package
17946                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17947
17948                    mSettings.writeLPr();
17949                }
17950
17951                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17952            }
17953        } else {
17954            synchronized (mPackages) {
17955                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17956                if (ps != null) {
17957                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17958                    if (res.removedInfo.removedChildPackages != null) {
17959                        final int childCount = res.removedInfo.removedChildPackages.size();
17960                        // Iterate in reverse as we may modify the collection
17961                        for (int i = childCount - 1; i >= 0; i--) {
17962                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17963                            if (res.addedChildPackages.containsKey(childPackageName)) {
17964                                res.removedInfo.removedChildPackages.removeAt(i);
17965                            } else {
17966                                PackageRemovedInfo childInfo = res.removedInfo
17967                                        .removedChildPackages.valueAt(i);
17968                                childInfo.removedForAllUsers = mPackages.get(
17969                                        childInfo.removedPackage) == null;
17970                            }
17971                        }
17972                    }
17973                }
17974            }
17975        }
17976    }
17977
17978    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17979            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17980            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17981            int installReason) {
17982        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17983                + ", old=" + deletedPackage);
17984
17985        final boolean disabledSystem;
17986
17987        // Remove existing system package
17988        removePackageLI(deletedPackage, true);
17989
17990        synchronized (mPackages) {
17991            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17992        }
17993        if (!disabledSystem) {
17994            // We didn't need to disable the .apk as a current system package,
17995            // which means we are replacing another update that is already
17996            // installed.  We need to make sure to delete the older one's .apk.
17997            res.removedInfo.args = createInstallArgsForExisting(0,
17998                    deletedPackage.applicationInfo.getCodePath(),
17999                    deletedPackage.applicationInfo.getResourcePath(),
18000                    getAppDexInstructionSets(deletedPackage.applicationInfo));
18001        } else {
18002            res.removedInfo.args = null;
18003        }
18004
18005        // Successfully disabled the old package. Now proceed with re-installation
18006        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
18007                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18008        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
18009
18010        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18011        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
18012                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
18013
18014        PackageParser.Package newPackage = null;
18015        try {
18016            // Add the package to the internal data structures
18017            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
18018
18019            // Set the update and install times
18020            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
18021            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
18022                    System.currentTimeMillis());
18023
18024            // Update the package dynamic state if succeeded
18025            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18026                // Now that the install succeeded make sure we remove data
18027                // directories for any child package the update removed.
18028                final int deletedChildCount = (deletedPackage.childPackages != null)
18029                        ? deletedPackage.childPackages.size() : 0;
18030                final int newChildCount = (newPackage.childPackages != null)
18031                        ? newPackage.childPackages.size() : 0;
18032                for (int i = 0; i < deletedChildCount; i++) {
18033                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
18034                    boolean childPackageDeleted = true;
18035                    for (int j = 0; j < newChildCount; j++) {
18036                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
18037                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
18038                            childPackageDeleted = false;
18039                            break;
18040                        }
18041                    }
18042                    if (childPackageDeleted) {
18043                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
18044                                deletedChildPkg.packageName);
18045                        if (ps != null && res.removedInfo.removedChildPackages != null) {
18046                            PackageRemovedInfo removedChildRes = res.removedInfo
18047                                    .removedChildPackages.get(deletedChildPkg.packageName);
18048                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
18049                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
18050                        }
18051                    }
18052                }
18053
18054                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
18055                        installReason);
18056                prepareAppDataAfterInstallLIF(newPackage);
18057
18058                mDexManager.notifyPackageUpdated(newPackage.packageName,
18059                            newPackage.baseCodePath, newPackage.splitCodePaths);
18060            }
18061        } catch (PackageManagerException e) {
18062            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
18063            res.setError("Package couldn't be installed in " + pkg.codePath, e);
18064        }
18065
18066        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
18067            // Re installation failed. Restore old information
18068            // Remove new pkg information
18069            if (newPackage != null) {
18070                removeInstalledPackageLI(newPackage, true);
18071            }
18072            // Add back the old system package
18073            try {
18074                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
18075            } catch (PackageManagerException e) {
18076                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
18077            }
18078
18079            synchronized (mPackages) {
18080                if (disabledSystem) {
18081                    enableSystemPackageLPw(deletedPackage);
18082                }
18083
18084                // Ensure the installer package name up to date
18085                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
18086
18087                // Update permissions for restored package
18088                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
18089
18090                mSettings.writeLPr();
18091            }
18092
18093            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
18094                    + " after failed upgrade");
18095        }
18096    }
18097
18098    /**
18099     * Checks whether the parent or any of the child packages have a change shared
18100     * user. For a package to be a valid update the shred users of the parent and
18101     * the children should match. We may later support changing child shared users.
18102     * @param oldPkg The updated package.
18103     * @param newPkg The update package.
18104     * @return The shared user that change between the versions.
18105     */
18106    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
18107            PackageParser.Package newPkg) {
18108        // Check parent shared user
18109        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
18110            return newPkg.packageName;
18111        }
18112        // Check child shared users
18113        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18114        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
18115        for (int i = 0; i < newChildCount; i++) {
18116            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
18117            // If this child was present, did it have the same shared user?
18118            for (int j = 0; j < oldChildCount; j++) {
18119                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
18120                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
18121                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
18122                    return newChildPkg.packageName;
18123                }
18124            }
18125        }
18126        return null;
18127    }
18128
18129    private void removeNativeBinariesLI(PackageSetting ps) {
18130        // Remove the lib path for the parent package
18131        if (ps != null) {
18132            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
18133            // Remove the lib path for the child packages
18134            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18135            for (int i = 0; i < childCount; i++) {
18136                PackageSetting childPs = null;
18137                synchronized (mPackages) {
18138                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18139                }
18140                if (childPs != null) {
18141                    NativeLibraryHelper.removeNativeBinariesLI(childPs
18142                            .legacyNativeLibraryPathString);
18143                }
18144            }
18145        }
18146    }
18147
18148    private void enableSystemPackageLPw(PackageParser.Package pkg) {
18149        // Enable the parent package
18150        mSettings.enableSystemPackageLPw(pkg.packageName);
18151        // Enable the child packages
18152        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18153        for (int i = 0; i < childCount; i++) {
18154            PackageParser.Package childPkg = pkg.childPackages.get(i);
18155            mSettings.enableSystemPackageLPw(childPkg.packageName);
18156        }
18157    }
18158
18159    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
18160            PackageParser.Package newPkg) {
18161        // Disable the parent package (parent always replaced)
18162        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
18163        // Disable the child packages
18164        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18165        for (int i = 0; i < childCount; i++) {
18166            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
18167            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
18168            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
18169        }
18170        return disabled;
18171    }
18172
18173    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
18174            String installerPackageName) {
18175        // Enable the parent package
18176        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
18177        // Enable the child packages
18178        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18179        for (int i = 0; i < childCount; i++) {
18180            PackageParser.Package childPkg = pkg.childPackages.get(i);
18181            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
18182        }
18183    }
18184
18185    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
18186        // Collect all used permissions in the UID
18187        ArraySet<String> usedPermissions = new ArraySet<>();
18188        final int packageCount = su.packages.size();
18189        for (int i = 0; i < packageCount; i++) {
18190            PackageSetting ps = su.packages.valueAt(i);
18191            if (ps.pkg == null) {
18192                continue;
18193            }
18194            final int requestedPermCount = ps.pkg.requestedPermissions.size();
18195            for (int j = 0; j < requestedPermCount; j++) {
18196                String permission = ps.pkg.requestedPermissions.get(j);
18197                BasePermission bp = mSettings.mPermissions.get(permission);
18198                if (bp != null) {
18199                    usedPermissions.add(permission);
18200                }
18201            }
18202        }
18203
18204        PermissionsState permissionsState = su.getPermissionsState();
18205        // Prune install permissions
18206        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18207        final int installPermCount = installPermStates.size();
18208        for (int i = installPermCount - 1; i >= 0;  i--) {
18209            PermissionState permissionState = installPermStates.get(i);
18210            if (!usedPermissions.contains(permissionState.getName())) {
18211                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18212                if (bp != null) {
18213                    permissionsState.revokeInstallPermission(bp);
18214                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18215                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18216                }
18217            }
18218        }
18219
18220        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18221
18222        // Prune runtime permissions
18223        for (int userId : allUserIds) {
18224            List<PermissionState> runtimePermStates = permissionsState
18225                    .getRuntimePermissionStates(userId);
18226            final int runtimePermCount = runtimePermStates.size();
18227            for (int i = runtimePermCount - 1; i >= 0; i--) {
18228                PermissionState permissionState = runtimePermStates.get(i);
18229                if (!usedPermissions.contains(permissionState.getName())) {
18230                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18231                    if (bp != null) {
18232                        permissionsState.revokeRuntimePermission(bp, userId);
18233                        permissionsState.updatePermissionFlags(bp, userId,
18234                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18235                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18236                                runtimePermissionChangedUserIds, userId);
18237                    }
18238                }
18239            }
18240        }
18241
18242        return runtimePermissionChangedUserIds;
18243    }
18244
18245    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18246            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18247        // Update the parent package setting
18248        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18249                res, user, installReason);
18250        // Update the child packages setting
18251        final int childCount = (newPackage.childPackages != null)
18252                ? newPackage.childPackages.size() : 0;
18253        for (int i = 0; i < childCount; i++) {
18254            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18255            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18256            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18257                    childRes.origUsers, childRes, user, installReason);
18258        }
18259    }
18260
18261    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18262            String installerPackageName, int[] allUsers, int[] installedForUsers,
18263            PackageInstalledInfo res, UserHandle user, int installReason) {
18264        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18265
18266        String pkgName = newPackage.packageName;
18267        synchronized (mPackages) {
18268            //write settings. the installStatus will be incomplete at this stage.
18269            //note that the new package setting would have already been
18270            //added to mPackages. It hasn't been persisted yet.
18271            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18272            // TODO: Remove this write? It's also written at the end of this method
18273            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18274            mSettings.writeLPr();
18275            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18276        }
18277
18278        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18279        synchronized (mPackages) {
18280            updatePermissionsLPw(newPackage.packageName, newPackage,
18281                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18282                            ? UPDATE_PERMISSIONS_ALL : 0));
18283            // For system-bundled packages, we assume that installing an upgraded version
18284            // of the package implies that the user actually wants to run that new code,
18285            // so we enable the package.
18286            PackageSetting ps = mSettings.mPackages.get(pkgName);
18287            final int userId = user.getIdentifier();
18288            if (ps != null) {
18289                if (isSystemApp(newPackage)) {
18290                    if (DEBUG_INSTALL) {
18291                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18292                    }
18293                    // Enable system package for requested users
18294                    if (res.origUsers != null) {
18295                        for (int origUserId : res.origUsers) {
18296                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18297                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18298                                        origUserId, installerPackageName);
18299                            }
18300                        }
18301                    }
18302                    // Also convey the prior install/uninstall state
18303                    if (allUsers != null && installedForUsers != null) {
18304                        for (int currentUserId : allUsers) {
18305                            final boolean installed = ArrayUtils.contains(
18306                                    installedForUsers, currentUserId);
18307                            if (DEBUG_INSTALL) {
18308                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18309                            }
18310                            ps.setInstalled(installed, currentUserId);
18311                        }
18312                        // these install state changes will be persisted in the
18313                        // upcoming call to mSettings.writeLPr().
18314                    }
18315                }
18316                // It's implied that when a user requests installation, they want the app to be
18317                // installed and enabled.
18318                if (userId != UserHandle.USER_ALL) {
18319                    ps.setInstalled(true, userId);
18320                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18321                }
18322
18323                // When replacing an existing package, preserve the original install reason for all
18324                // users that had the package installed before.
18325                final Set<Integer> previousUserIds = new ArraySet<>();
18326                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18327                    final int installReasonCount = res.removedInfo.installReasons.size();
18328                    for (int i = 0; i < installReasonCount; i++) {
18329                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18330                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18331                        ps.setInstallReason(previousInstallReason, previousUserId);
18332                        previousUserIds.add(previousUserId);
18333                    }
18334                }
18335
18336                // Set install reason for users that are having the package newly installed.
18337                if (userId == UserHandle.USER_ALL) {
18338                    for (int currentUserId : sUserManager.getUserIds()) {
18339                        if (!previousUserIds.contains(currentUserId)) {
18340                            ps.setInstallReason(installReason, currentUserId);
18341                        }
18342                    }
18343                } else if (!previousUserIds.contains(userId)) {
18344                    ps.setInstallReason(installReason, userId);
18345                }
18346                mSettings.writeKernelMappingLPr(ps);
18347            }
18348            res.name = pkgName;
18349            res.uid = newPackage.applicationInfo.uid;
18350            res.pkg = newPackage;
18351            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18352            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18353            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18354            //to update install status
18355            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18356            mSettings.writeLPr();
18357            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18358        }
18359
18360        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18361    }
18362
18363    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18364        try {
18365            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18366            installPackageLI(args, res);
18367        } finally {
18368            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18369        }
18370    }
18371
18372    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18373        final int installFlags = args.installFlags;
18374        final String installerPackageName = args.installerPackageName;
18375        final String volumeUuid = args.volumeUuid;
18376        final File tmpPackageFile = new File(args.getCodePath());
18377        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18378        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18379                || (args.volumeUuid != null));
18380        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18381        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18382        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18383        final boolean virtualPreload =
18384                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18385        boolean replace = false;
18386        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18387        if (args.move != null) {
18388            // moving a complete application; perform an initial scan on the new install location
18389            scanFlags |= SCAN_INITIAL;
18390        }
18391        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18392            scanFlags |= SCAN_DONT_KILL_APP;
18393        }
18394        if (instantApp) {
18395            scanFlags |= SCAN_AS_INSTANT_APP;
18396        }
18397        if (fullApp) {
18398            scanFlags |= SCAN_AS_FULL_APP;
18399        }
18400        if (virtualPreload) {
18401            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18402        }
18403
18404        // Result object to be returned
18405        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18406        res.installerPackageName = installerPackageName;
18407
18408        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18409
18410        // Sanity check
18411        if (instantApp && (forwardLocked || onExternal)) {
18412            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18413                    + " external=" + onExternal);
18414            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18415            return;
18416        }
18417
18418        // Retrieve PackageSettings and parse package
18419        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18420                | PackageParser.PARSE_ENFORCE_CODE
18421                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18422                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18423                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18424                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18425        PackageParser pp = new PackageParser();
18426        pp.setSeparateProcesses(mSeparateProcesses);
18427        pp.setDisplayMetrics(mMetrics);
18428        pp.setCallback(mPackageParserCallback);
18429
18430        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18431        final PackageParser.Package pkg;
18432        try {
18433            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18434        } catch (PackageParserException e) {
18435            res.setError("Failed parse during installPackageLI", e);
18436            return;
18437        } finally {
18438            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18439        }
18440
18441        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18442        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18443            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18444            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18445                    "Instant app package must target O");
18446            return;
18447        }
18448        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18449            Slog.w(TAG, "Instant app package " + pkg.packageName
18450                    + " does not target targetSandboxVersion 2");
18451            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18452                    "Instant app package must use targetSanboxVersion 2");
18453            return;
18454        }
18455
18456        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18457            // Static shared libraries have synthetic package names
18458            renameStaticSharedLibraryPackage(pkg);
18459
18460            // No static shared libs on external storage
18461            if (onExternal) {
18462                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18463                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18464                        "Packages declaring static-shared libs cannot be updated");
18465                return;
18466            }
18467        }
18468
18469        // If we are installing a clustered package add results for the children
18470        if (pkg.childPackages != null) {
18471            synchronized (mPackages) {
18472                final int childCount = pkg.childPackages.size();
18473                for (int i = 0; i < childCount; i++) {
18474                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18475                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18476                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18477                    childRes.pkg = childPkg;
18478                    childRes.name = childPkg.packageName;
18479                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18480                    if (childPs != null) {
18481                        childRes.origUsers = childPs.queryInstalledUsers(
18482                                sUserManager.getUserIds(), true);
18483                    }
18484                    if ((mPackages.containsKey(childPkg.packageName))) {
18485                        childRes.removedInfo = new PackageRemovedInfo(this);
18486                        childRes.removedInfo.removedPackage = childPkg.packageName;
18487                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18488                    }
18489                    if (res.addedChildPackages == null) {
18490                        res.addedChildPackages = new ArrayMap<>();
18491                    }
18492                    res.addedChildPackages.put(childPkg.packageName, childRes);
18493                }
18494            }
18495        }
18496
18497        // If package doesn't declare API override, mark that we have an install
18498        // time CPU ABI override.
18499        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18500            pkg.cpuAbiOverride = args.abiOverride;
18501        }
18502
18503        String pkgName = res.name = pkg.packageName;
18504        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18505            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18506                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18507                return;
18508            }
18509        }
18510
18511        try {
18512            // either use what we've been given or parse directly from the APK
18513            if (args.certificates != null) {
18514                try {
18515                    PackageParser.populateCertificates(pkg, args.certificates);
18516                } catch (PackageParserException e) {
18517                    // there was something wrong with the certificates we were given;
18518                    // try to pull them from the APK
18519                    PackageParser.collectCertificates(pkg, parseFlags);
18520                }
18521            } else {
18522                PackageParser.collectCertificates(pkg, parseFlags);
18523            }
18524        } catch (PackageParserException e) {
18525            res.setError("Failed collect during installPackageLI", e);
18526            return;
18527        }
18528
18529        // Get rid of all references to package scan path via parser.
18530        pp = null;
18531        String oldCodePath = null;
18532        boolean systemApp = false;
18533        synchronized (mPackages) {
18534            // Check if installing already existing package
18535            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18536                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18537                if (pkg.mOriginalPackages != null
18538                        && pkg.mOriginalPackages.contains(oldName)
18539                        && mPackages.containsKey(oldName)) {
18540                    // This package is derived from an original package,
18541                    // and this device has been updating from that original
18542                    // name.  We must continue using the original name, so
18543                    // rename the new package here.
18544                    pkg.setPackageName(oldName);
18545                    pkgName = pkg.packageName;
18546                    replace = true;
18547                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18548                            + oldName + " pkgName=" + pkgName);
18549                } else if (mPackages.containsKey(pkgName)) {
18550                    // This package, under its official name, already exists
18551                    // on the device; we should replace it.
18552                    replace = true;
18553                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18554                }
18555
18556                // Child packages are installed through the parent package
18557                if (pkg.parentPackage != null) {
18558                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18559                            "Package " + pkg.packageName + " is child of package "
18560                                    + pkg.parentPackage.parentPackage + ". Child packages "
18561                                    + "can be updated only through the parent package.");
18562                    return;
18563                }
18564
18565                if (replace) {
18566                    // Prevent apps opting out from runtime permissions
18567                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18568                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18569                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18570                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18571                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18572                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18573                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18574                                        + " doesn't support runtime permissions but the old"
18575                                        + " target SDK " + oldTargetSdk + " does.");
18576                        return;
18577                    }
18578                    // Prevent apps from downgrading their targetSandbox.
18579                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18580                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18581                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18582                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18583                                "Package " + pkg.packageName + " new target sandbox "
18584                                + newTargetSandbox + " is incompatible with the previous value of"
18585                                + oldTargetSandbox + ".");
18586                        return;
18587                    }
18588
18589                    // Prevent installing of child packages
18590                    if (oldPackage.parentPackage != null) {
18591                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18592                                "Package " + pkg.packageName + " is child of package "
18593                                        + oldPackage.parentPackage + ". Child packages "
18594                                        + "can be updated only through the parent package.");
18595                        return;
18596                    }
18597                }
18598            }
18599
18600            PackageSetting ps = mSettings.mPackages.get(pkgName);
18601            if (ps != null) {
18602                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18603
18604                // Static shared libs have same package with different versions where
18605                // we internally use a synthetic package name to allow multiple versions
18606                // of the same package, therefore we need to compare signatures against
18607                // the package setting for the latest library version.
18608                PackageSetting signatureCheckPs = ps;
18609                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18610                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18611                    if (libraryEntry != null) {
18612                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18613                    }
18614                }
18615
18616                // Quick sanity check that we're signed correctly if updating;
18617                // we'll check this again later when scanning, but we want to
18618                // bail early here before tripping over redefined permissions.
18619                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18620                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18621                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18622                                + pkg.packageName + " upgrade keys do not match the "
18623                                + "previously installed version");
18624                        return;
18625                    }
18626                } else {
18627                    try {
18628                        verifySignaturesLP(signatureCheckPs, pkg);
18629                    } catch (PackageManagerException e) {
18630                        res.setError(e.error, e.getMessage());
18631                        return;
18632                    }
18633                }
18634
18635                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18636                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18637                    systemApp = (ps.pkg.applicationInfo.flags &
18638                            ApplicationInfo.FLAG_SYSTEM) != 0;
18639                }
18640                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18641            }
18642
18643            int N = pkg.permissions.size();
18644            for (int i = N-1; i >= 0; i--) {
18645                PackageParser.Permission perm = pkg.permissions.get(i);
18646                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18647
18648                // Don't allow anyone but the system to define ephemeral permissions.
18649                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
18650                        && !systemApp) {
18651                    Slog.w(TAG, "Non-System package " + pkg.packageName
18652                            + " attempting to delcare ephemeral permission "
18653                            + perm.info.name + "; Removing ephemeral.");
18654                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
18655                }
18656                // Check whether the newly-scanned package wants to define an already-defined perm
18657                if (bp != null) {
18658                    // If the defining package is signed with our cert, it's okay.  This
18659                    // also includes the "updating the same package" case, of course.
18660                    // "updating same package" could also involve key-rotation.
18661                    final boolean sigsOk;
18662                    if (bp.sourcePackage.equals(pkg.packageName)
18663                            && (bp.packageSetting instanceof PackageSetting)
18664                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18665                                    scanFlags))) {
18666                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18667                    } else {
18668                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18669                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18670                    }
18671                    if (!sigsOk) {
18672                        // If the owning package is the system itself, we log but allow
18673                        // install to proceed; we fail the install on all other permission
18674                        // redefinitions.
18675                        if (!bp.sourcePackage.equals("android")) {
18676                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18677                                    + pkg.packageName + " attempting to redeclare permission "
18678                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18679                            res.origPermission = perm.info.name;
18680                            res.origPackage = bp.sourcePackage;
18681                            return;
18682                        } else {
18683                            Slog.w(TAG, "Package " + pkg.packageName
18684                                    + " attempting to redeclare system permission "
18685                                    + perm.info.name + "; ignoring new declaration");
18686                            pkg.permissions.remove(i);
18687                        }
18688                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18689                        // Prevent apps to change protection level to dangerous from any other
18690                        // type as this would allow a privilege escalation where an app adds a
18691                        // normal/signature permission in other app's group and later redefines
18692                        // it as dangerous leading to the group auto-grant.
18693                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18694                                == PermissionInfo.PROTECTION_DANGEROUS) {
18695                            if (bp != null && !bp.isRuntime()) {
18696                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18697                                        + "non-runtime permission " + perm.info.name
18698                                        + " to runtime; keeping old protection level");
18699                                perm.info.protectionLevel = bp.protectionLevel;
18700                            }
18701                        }
18702                    }
18703                }
18704            }
18705        }
18706
18707        if (systemApp) {
18708            if (onExternal) {
18709                // Abort update; system app can't be replaced with app on sdcard
18710                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18711                        "Cannot install updates to system apps on sdcard");
18712                return;
18713            } else if (instantApp) {
18714                // Abort update; system app can't be replaced with an instant app
18715                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18716                        "Cannot update a system app with an instant app");
18717                return;
18718            }
18719        }
18720
18721        if (args.move != null) {
18722            // We did an in-place move, so dex is ready to roll
18723            scanFlags |= SCAN_NO_DEX;
18724            scanFlags |= SCAN_MOVE;
18725
18726            synchronized (mPackages) {
18727                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18728                if (ps == null) {
18729                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18730                            "Missing settings for moved package " + pkgName);
18731                }
18732
18733                // We moved the entire application as-is, so bring over the
18734                // previously derived ABI information.
18735                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18736                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18737            }
18738
18739        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18740            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18741            scanFlags |= SCAN_NO_DEX;
18742
18743            try {
18744                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18745                    args.abiOverride : pkg.cpuAbiOverride);
18746                final boolean extractNativeLibs = !pkg.isLibrary();
18747                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18748                        extractNativeLibs, mAppLib32InstallDir);
18749            } catch (PackageManagerException pme) {
18750                Slog.e(TAG, "Error deriving application ABI", pme);
18751                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18752                return;
18753            }
18754
18755            // Shared libraries for the package need to be updated.
18756            synchronized (mPackages) {
18757                try {
18758                    updateSharedLibrariesLPr(pkg, null);
18759                } catch (PackageManagerException e) {
18760                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18761                }
18762            }
18763        }
18764
18765        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18766            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18767            return;
18768        }
18769
18770        // Verify if we need to dexopt the app.
18771        //
18772        // NOTE: it is *important* to call dexopt after doRename which will sync the
18773        // package data from PackageParser.Package and its corresponding ApplicationInfo.
18774        //
18775        // We only need to dexopt if the package meets ALL of the following conditions:
18776        //   1) it is not forward locked.
18777        //   2) it is not on on an external ASEC container.
18778        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18779        //
18780        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18781        // complete, so we skip this step during installation. Instead, we'll take extra time
18782        // the first time the instant app starts. It's preferred to do it this way to provide
18783        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18784        // middle of running an instant app. The default behaviour can be overridden
18785        // via gservices.
18786        final boolean performDexopt = !forwardLocked
18787            && !pkg.applicationInfo.isExternalAsec()
18788            && (!instantApp || Global.getInt(mContext.getContentResolver(),
18789                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18790
18791        if (performDexopt) {
18792            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18793            // Do not run PackageDexOptimizer through the local performDexOpt
18794            // method because `pkg` may not be in `mPackages` yet.
18795            //
18796            // Also, don't fail application installs if the dexopt step fails.
18797            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18798                REASON_INSTALL,
18799                DexoptOptions.DEXOPT_BOOT_COMPLETE);
18800            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18801                null /* instructionSets */,
18802                getOrCreateCompilerPackageStats(pkg),
18803                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18804                dexoptOptions);
18805            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18806        }
18807
18808        // Notify BackgroundDexOptService that the package has been changed.
18809        // If this is an update of a package which used to fail to compile,
18810        // BackgroundDexOptService will remove it from its blacklist.
18811        // TODO: Layering violation
18812        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18813
18814        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
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        synchronized (mPackages) {
18840            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18841            if (ps != null) {
18842                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18843                ps.setUpdateAvailable(false /*updateAvailable*/);
18844            }
18845
18846            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18847            for (int i = 0; i < childCount; i++) {
18848                PackageParser.Package childPkg = pkg.childPackages.get(i);
18849                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18850                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18851                if (childPs != null) {
18852                    childRes.newUsers = childPs.queryInstalledUsers(
18853                            sUserManager.getUserIds(), true);
18854                }
18855            }
18856
18857            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18858                updateSequenceNumberLP(ps, res.newUsers);
18859                updateInstantAppInstallerLocked(pkgName);
18860            }
18861        }
18862    }
18863
18864    private void startIntentFilterVerifications(int userId, boolean replacing,
18865            PackageParser.Package pkg) {
18866        if (mIntentFilterVerifierComponent == null) {
18867            Slog.w(TAG, "No IntentFilter verification will not be done as "
18868                    + "there is no IntentFilterVerifier available!");
18869            return;
18870        }
18871
18872        final int verifierUid = getPackageUid(
18873                mIntentFilterVerifierComponent.getPackageName(),
18874                MATCH_DEBUG_TRIAGED_MISSING,
18875                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18876
18877        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18878        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18879        mHandler.sendMessage(msg);
18880
18881        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18882        for (int i = 0; i < childCount; i++) {
18883            PackageParser.Package childPkg = pkg.childPackages.get(i);
18884            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18885            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18886            mHandler.sendMessage(msg);
18887        }
18888    }
18889
18890    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18891            PackageParser.Package pkg) {
18892        int size = pkg.activities.size();
18893        if (size == 0) {
18894            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18895                    "No activity, so no need to verify any IntentFilter!");
18896            return;
18897        }
18898
18899        final boolean hasDomainURLs = hasDomainURLs(pkg);
18900        if (!hasDomainURLs) {
18901            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18902                    "No domain URLs, so no need to verify any IntentFilter!");
18903            return;
18904        }
18905
18906        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18907                + " if any IntentFilter from the " + size
18908                + " Activities needs verification ...");
18909
18910        int count = 0;
18911        final String packageName = pkg.packageName;
18912
18913        synchronized (mPackages) {
18914            // If this is a new install and we see that we've already run verification for this
18915            // package, we have nothing to do: it means the state was restored from backup.
18916            if (!replacing) {
18917                IntentFilterVerificationInfo ivi =
18918                        mSettings.getIntentFilterVerificationLPr(packageName);
18919                if (ivi != null) {
18920                    if (DEBUG_DOMAIN_VERIFICATION) {
18921                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18922                                + ivi.getStatusString());
18923                    }
18924                    return;
18925                }
18926            }
18927
18928            // If any filters need to be verified, then all need to be.
18929            boolean needToVerify = false;
18930            for (PackageParser.Activity a : pkg.activities) {
18931                for (ActivityIntentInfo filter : a.intents) {
18932                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18933                        if (DEBUG_DOMAIN_VERIFICATION) {
18934                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18935                        }
18936                        needToVerify = true;
18937                        break;
18938                    }
18939                }
18940            }
18941
18942            if (needToVerify) {
18943                final int verificationId = mIntentFilterVerificationToken++;
18944                for (PackageParser.Activity a : pkg.activities) {
18945                    for (ActivityIntentInfo filter : a.intents) {
18946                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18947                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18948                                    "Verification needed for IntentFilter:" + filter.toString());
18949                            mIntentFilterVerifier.addOneIntentFilterVerification(
18950                                    verifierUid, userId, verificationId, filter, packageName);
18951                            count++;
18952                        }
18953                    }
18954                }
18955            }
18956        }
18957
18958        if (count > 0) {
18959            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18960                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18961                    +  " for userId:" + userId);
18962            mIntentFilterVerifier.startVerifications(userId);
18963        } else {
18964            if (DEBUG_DOMAIN_VERIFICATION) {
18965                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18966            }
18967        }
18968    }
18969
18970    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18971        final ComponentName cn  = filter.activity.getComponentName();
18972        final String packageName = cn.getPackageName();
18973
18974        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18975                packageName);
18976        if (ivi == null) {
18977            return true;
18978        }
18979        int status = ivi.getStatus();
18980        switch (status) {
18981            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18982            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18983                return true;
18984
18985            default:
18986                // Nothing to do
18987                return false;
18988        }
18989    }
18990
18991    private static boolean isMultiArch(ApplicationInfo info) {
18992        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18993    }
18994
18995    private static boolean isExternal(PackageParser.Package pkg) {
18996        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18997    }
18998
18999    private static boolean isExternal(PackageSetting ps) {
19000        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
19001    }
19002
19003    private static boolean isSystemApp(PackageParser.Package pkg) {
19004        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
19005    }
19006
19007    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
19008        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
19009    }
19010
19011    private static boolean hasDomainURLs(PackageParser.Package pkg) {
19012        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
19013    }
19014
19015    private static boolean isSystemApp(PackageSetting ps) {
19016        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
19017    }
19018
19019    private static boolean isUpdatedSystemApp(PackageSetting ps) {
19020        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
19021    }
19022
19023    private int packageFlagsToInstallFlags(PackageSetting ps) {
19024        int installFlags = 0;
19025        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
19026            // This existing package was an external ASEC install when we have
19027            // the external flag without a UUID
19028            installFlags |= PackageManager.INSTALL_EXTERNAL;
19029        }
19030        if (ps.isForwardLocked()) {
19031            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
19032        }
19033        return installFlags;
19034    }
19035
19036    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
19037        if (isExternal(pkg)) {
19038            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19039                return StorageManager.UUID_PRIMARY_PHYSICAL;
19040            } else {
19041                return pkg.volumeUuid;
19042            }
19043        } else {
19044            return StorageManager.UUID_PRIVATE_INTERNAL;
19045        }
19046    }
19047
19048    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
19049        if (isExternal(pkg)) {
19050            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19051                return mSettings.getExternalVersion();
19052            } else {
19053                return mSettings.findOrCreateVersion(pkg.volumeUuid);
19054            }
19055        } else {
19056            return mSettings.getInternalVersion();
19057        }
19058    }
19059
19060    private void deleteTempPackageFiles() {
19061        final FilenameFilter filter = new FilenameFilter() {
19062            public boolean accept(File dir, String name) {
19063                return name.startsWith("vmdl") && name.endsWith(".tmp");
19064            }
19065        };
19066        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
19067            file.delete();
19068        }
19069    }
19070
19071    @Override
19072    public void deletePackageAsUser(String packageName, int versionCode,
19073            IPackageDeleteObserver observer, int userId, int flags) {
19074        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
19075                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
19076    }
19077
19078    @Override
19079    public void deletePackageVersioned(VersionedPackage versionedPackage,
19080            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
19081        final int callingUid = Binder.getCallingUid();
19082        mContext.enforceCallingOrSelfPermission(
19083                android.Manifest.permission.DELETE_PACKAGES, null);
19084        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
19085        Preconditions.checkNotNull(versionedPackage);
19086        Preconditions.checkNotNull(observer);
19087        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
19088                PackageManager.VERSION_CODE_HIGHEST,
19089                Integer.MAX_VALUE, "versionCode must be >= -1");
19090
19091        final String packageName = versionedPackage.getPackageName();
19092        final int versionCode = versionedPackage.getVersionCode();
19093        final String internalPackageName;
19094        synchronized (mPackages) {
19095            // Normalize package name to handle renamed packages and static libs
19096            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
19097                    versionedPackage.getVersionCode());
19098        }
19099
19100        final int uid = Binder.getCallingUid();
19101        if (!isOrphaned(internalPackageName)
19102                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
19103            try {
19104                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
19105                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
19106                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
19107                observer.onUserActionRequired(intent);
19108            } catch (RemoteException re) {
19109            }
19110            return;
19111        }
19112        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
19113        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
19114        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
19115            mContext.enforceCallingOrSelfPermission(
19116                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
19117                    "deletePackage for user " + userId);
19118        }
19119
19120        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
19121            try {
19122                observer.onPackageDeleted(packageName,
19123                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
19124            } catch (RemoteException re) {
19125            }
19126            return;
19127        }
19128
19129        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
19130            try {
19131                observer.onPackageDeleted(packageName,
19132                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
19133            } catch (RemoteException re) {
19134            }
19135            return;
19136        }
19137
19138        if (DEBUG_REMOVE) {
19139            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
19140                    + " deleteAllUsers: " + deleteAllUsers + " version="
19141                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
19142                    ? "VERSION_CODE_HIGHEST" : versionCode));
19143        }
19144        // Queue up an async operation since the package deletion may take a little while.
19145        mHandler.post(new Runnable() {
19146            public void run() {
19147                mHandler.removeCallbacks(this);
19148                int returnCode;
19149                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
19150                boolean doDeletePackage = true;
19151                if (ps != null) {
19152                    final boolean targetIsInstantApp =
19153                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19154                    doDeletePackage = !targetIsInstantApp
19155                            || canViewInstantApps;
19156                }
19157                if (doDeletePackage) {
19158                    if (!deleteAllUsers) {
19159                        returnCode = deletePackageX(internalPackageName, versionCode,
19160                                userId, deleteFlags);
19161                    } else {
19162                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
19163                                internalPackageName, users);
19164                        // If nobody is blocking uninstall, proceed with delete for all users
19165                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
19166                            returnCode = deletePackageX(internalPackageName, versionCode,
19167                                    userId, deleteFlags);
19168                        } else {
19169                            // Otherwise uninstall individually for users with blockUninstalls=false
19170                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
19171                            for (int userId : users) {
19172                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
19173                                    returnCode = deletePackageX(internalPackageName, versionCode,
19174                                            userId, userFlags);
19175                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
19176                                        Slog.w(TAG, "Package delete failed for user " + userId
19177                                                + ", returnCode " + returnCode);
19178                                    }
19179                                }
19180                            }
19181                            // The app has only been marked uninstalled for certain users.
19182                            // We still need to report that delete was blocked
19183                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
19184                        }
19185                    }
19186                } else {
19187                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19188                }
19189                try {
19190                    observer.onPackageDeleted(packageName, returnCode, null);
19191                } catch (RemoteException e) {
19192                    Log.i(TAG, "Observer no longer exists.");
19193                } //end catch
19194            } //end run
19195        });
19196    }
19197
19198    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
19199        if (pkg.staticSharedLibName != null) {
19200            return pkg.manifestPackageName;
19201        }
19202        return pkg.packageName;
19203    }
19204
19205    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
19206        // Handle renamed packages
19207        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
19208        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
19209
19210        // Is this a static library?
19211        SparseArray<SharedLibraryEntry> versionedLib =
19212                mStaticLibsByDeclaringPackage.get(packageName);
19213        if (versionedLib == null || versionedLib.size() <= 0) {
19214            return packageName;
19215        }
19216
19217        // Figure out which lib versions the caller can see
19218        SparseIntArray versionsCallerCanSee = null;
19219        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19220        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19221                && callingAppId != Process.ROOT_UID) {
19222            versionsCallerCanSee = new SparseIntArray();
19223            String libName = versionedLib.valueAt(0).info.getName();
19224            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19225            if (uidPackages != null) {
19226                for (String uidPackage : uidPackages) {
19227                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19228                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19229                    if (libIdx >= 0) {
19230                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19231                        versionsCallerCanSee.append(libVersion, libVersion);
19232                    }
19233                }
19234            }
19235        }
19236
19237        // Caller can see nothing - done
19238        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19239            return packageName;
19240        }
19241
19242        // Find the version the caller can see and the app version code
19243        SharedLibraryEntry highestVersion = null;
19244        final int versionCount = versionedLib.size();
19245        for (int i = 0; i < versionCount; i++) {
19246            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19247            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19248                    libEntry.info.getVersion()) < 0) {
19249                continue;
19250            }
19251            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19252            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19253                if (libVersionCode == versionCode) {
19254                    return libEntry.apk;
19255                }
19256            } else if (highestVersion == null) {
19257                highestVersion = libEntry;
19258            } else if (libVersionCode  > highestVersion.info
19259                    .getDeclaringPackage().getVersionCode()) {
19260                highestVersion = libEntry;
19261            }
19262        }
19263
19264        if (highestVersion != null) {
19265            return highestVersion.apk;
19266        }
19267
19268        return packageName;
19269    }
19270
19271    boolean isCallerVerifier(int callingUid) {
19272        final int callingUserId = UserHandle.getUserId(callingUid);
19273        return mRequiredVerifierPackage != null &&
19274                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19275    }
19276
19277    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19278        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19279              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19280            return true;
19281        }
19282        final int callingUserId = UserHandle.getUserId(callingUid);
19283        // If the caller installed the pkgName, then allow it to silently uninstall.
19284        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19285            return true;
19286        }
19287
19288        // Allow package verifier to silently uninstall.
19289        if (mRequiredVerifierPackage != null &&
19290                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19291            return true;
19292        }
19293
19294        // Allow package uninstaller to silently uninstall.
19295        if (mRequiredUninstallerPackage != null &&
19296                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19297            return true;
19298        }
19299
19300        // Allow storage manager to silently uninstall.
19301        if (mStorageManagerPackage != null &&
19302                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19303            return true;
19304        }
19305
19306        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19307        // uninstall for device owner provisioning.
19308        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19309                == PERMISSION_GRANTED) {
19310            return true;
19311        }
19312
19313        return false;
19314    }
19315
19316    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19317        int[] result = EMPTY_INT_ARRAY;
19318        for (int userId : userIds) {
19319            if (getBlockUninstallForUser(packageName, userId)) {
19320                result = ArrayUtils.appendInt(result, userId);
19321            }
19322        }
19323        return result;
19324    }
19325
19326    @Override
19327    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19328        final int callingUid = Binder.getCallingUid();
19329        if (getInstantAppPackageName(callingUid) != null
19330                && !isCallerSameApp(packageName, callingUid)) {
19331            return false;
19332        }
19333        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19334    }
19335
19336    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19337        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19338                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19339        try {
19340            if (dpm != null) {
19341                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19342                        /* callingUserOnly =*/ false);
19343                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19344                        : deviceOwnerComponentName.getPackageName();
19345                // Does the package contains the device owner?
19346                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19347                // this check is probably not needed, since DO should be registered as a device
19348                // admin on some user too. (Original bug for this: b/17657954)
19349                if (packageName.equals(deviceOwnerPackageName)) {
19350                    return true;
19351                }
19352                // Does it contain a device admin for any user?
19353                int[] users;
19354                if (userId == UserHandle.USER_ALL) {
19355                    users = sUserManager.getUserIds();
19356                } else {
19357                    users = new int[]{userId};
19358                }
19359                for (int i = 0; i < users.length; ++i) {
19360                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19361                        return true;
19362                    }
19363                }
19364            }
19365        } catch (RemoteException e) {
19366        }
19367        return false;
19368    }
19369
19370    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19371        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19372    }
19373
19374    /**
19375     *  This method is an internal method that could be get invoked either
19376     *  to delete an installed package or to clean up a failed installation.
19377     *  After deleting an installed package, a broadcast is sent to notify any
19378     *  listeners that the package has been removed. For cleaning up a failed
19379     *  installation, the broadcast is not necessary since the package's
19380     *  installation wouldn't have sent the initial broadcast either
19381     *  The key steps in deleting a package are
19382     *  deleting the package information in internal structures like mPackages,
19383     *  deleting the packages base directories through installd
19384     *  updating mSettings to reflect current status
19385     *  persisting settings for later use
19386     *  sending a broadcast if necessary
19387     */
19388    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19389        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19390        final boolean res;
19391
19392        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19393                ? UserHandle.USER_ALL : userId;
19394
19395        if (isPackageDeviceAdmin(packageName, removeUser)) {
19396            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19397            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19398        }
19399
19400        PackageSetting uninstalledPs = null;
19401        PackageParser.Package pkg = null;
19402
19403        // for the uninstall-updates case and restricted profiles, remember the per-
19404        // user handle installed state
19405        int[] allUsers;
19406        synchronized (mPackages) {
19407            uninstalledPs = mSettings.mPackages.get(packageName);
19408            if (uninstalledPs == null) {
19409                Slog.w(TAG, "Not removing non-existent package " + packageName);
19410                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19411            }
19412
19413            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19414                    && uninstalledPs.versionCode != versionCode) {
19415                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19416                        + uninstalledPs.versionCode + " != " + versionCode);
19417                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19418            }
19419
19420            // Static shared libs can be declared by any package, so let us not
19421            // allow removing a package if it provides a lib others depend on.
19422            pkg = mPackages.get(packageName);
19423
19424            allUsers = sUserManager.getUserIds();
19425
19426            if (pkg != null && pkg.staticSharedLibName != null) {
19427                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19428                        pkg.staticSharedLibVersion);
19429                if (libEntry != null) {
19430                    for (int currUserId : allUsers) {
19431                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19432                            continue;
19433                        }
19434                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19435                                libEntry.info, 0, currUserId);
19436                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19437                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19438                                    + " hosting lib " + libEntry.info.getName() + " version "
19439                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19440                                    + " for user " + currUserId);
19441                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19442                        }
19443                    }
19444                }
19445            }
19446
19447            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19448        }
19449
19450        final int freezeUser;
19451        if (isUpdatedSystemApp(uninstalledPs)
19452                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19453            // We're downgrading a system app, which will apply to all users, so
19454            // freeze them all during the downgrade
19455            freezeUser = UserHandle.USER_ALL;
19456        } else {
19457            freezeUser = removeUser;
19458        }
19459
19460        synchronized (mInstallLock) {
19461            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19462            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19463                    deleteFlags, "deletePackageX")) {
19464                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19465                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19466            }
19467            synchronized (mPackages) {
19468                if (res) {
19469                    if (pkg != null) {
19470                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19471                    }
19472                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19473                    updateInstantAppInstallerLocked(packageName);
19474                }
19475            }
19476        }
19477
19478        if (res) {
19479            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19480            info.sendPackageRemovedBroadcasts(killApp);
19481            info.sendSystemPackageUpdatedBroadcasts();
19482            info.sendSystemPackageAppearedBroadcasts();
19483        }
19484        // Force a gc here.
19485        Runtime.getRuntime().gc();
19486        // Delete the resources here after sending the broadcast to let
19487        // other processes clean up before deleting resources.
19488        if (info.args != null) {
19489            synchronized (mInstallLock) {
19490                info.args.doPostDeleteLI(true);
19491            }
19492        }
19493
19494        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19495    }
19496
19497    static class PackageRemovedInfo {
19498        final PackageSender packageSender;
19499        String removedPackage;
19500        String installerPackageName;
19501        int uid = -1;
19502        int removedAppId = -1;
19503        int[] origUsers;
19504        int[] removedUsers = null;
19505        int[] broadcastUsers = null;
19506        SparseArray<Integer> installReasons;
19507        boolean isRemovedPackageSystemUpdate = false;
19508        boolean isUpdate;
19509        boolean dataRemoved;
19510        boolean removedForAllUsers;
19511        boolean isStaticSharedLib;
19512        // Clean up resources deleted packages.
19513        InstallArgs args = null;
19514        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19515        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19516
19517        PackageRemovedInfo(PackageSender packageSender) {
19518            this.packageSender = packageSender;
19519        }
19520
19521        void sendPackageRemovedBroadcasts(boolean killApp) {
19522            sendPackageRemovedBroadcastInternal(killApp);
19523            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19524            for (int i = 0; i < childCount; i++) {
19525                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19526                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19527            }
19528        }
19529
19530        void sendSystemPackageUpdatedBroadcasts() {
19531            if (isRemovedPackageSystemUpdate) {
19532                sendSystemPackageUpdatedBroadcastsInternal();
19533                final int childCount = (removedChildPackages != null)
19534                        ? removedChildPackages.size() : 0;
19535                for (int i = 0; i < childCount; i++) {
19536                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19537                    if (childInfo.isRemovedPackageSystemUpdate) {
19538                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19539                    }
19540                }
19541            }
19542        }
19543
19544        void sendSystemPackageAppearedBroadcasts() {
19545            final int packageCount = (appearedChildPackages != null)
19546                    ? appearedChildPackages.size() : 0;
19547            for (int i = 0; i < packageCount; i++) {
19548                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19549                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19550                    true /*sendBootCompleted*/, false /*startReceiver*/,
19551                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19552            }
19553        }
19554
19555        private void sendSystemPackageUpdatedBroadcastsInternal() {
19556            Bundle extras = new Bundle(2);
19557            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19558            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19559            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19560                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19561            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19562                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19563            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19564                null, null, 0, removedPackage, null, null);
19565            if (installerPackageName != null) {
19566                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19567                        removedPackage, extras, 0 /*flags*/,
19568                        installerPackageName, null, null);
19569                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19570                        removedPackage, extras, 0 /*flags*/,
19571                        installerPackageName, null, null);
19572            }
19573        }
19574
19575        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19576            // Don't send static shared library removal broadcasts as these
19577            // libs are visible only the the apps that depend on them an one
19578            // cannot remove the library if it has a dependency.
19579            if (isStaticSharedLib) {
19580                return;
19581            }
19582            Bundle extras = new Bundle(2);
19583            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19584            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19585            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19586            if (isUpdate || isRemovedPackageSystemUpdate) {
19587                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19588            }
19589            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19590            if (removedPackage != null) {
19591                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19592                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19593                if (installerPackageName != null) {
19594                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19595                            removedPackage, extras, 0 /*flags*/,
19596                            installerPackageName, null, broadcastUsers);
19597                }
19598                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19599                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19600                        removedPackage, extras,
19601                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19602                        null, null, broadcastUsers);
19603                }
19604            }
19605            if (removedAppId >= 0) {
19606                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19607                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19608                    null, null, broadcastUsers);
19609            }
19610        }
19611
19612        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19613            removedUsers = userIds;
19614            if (removedUsers == null) {
19615                broadcastUsers = null;
19616                return;
19617            }
19618
19619            broadcastUsers = EMPTY_INT_ARRAY;
19620            for (int i = userIds.length - 1; i >= 0; --i) {
19621                final int userId = userIds[i];
19622                if (deletedPackageSetting.getInstantApp(userId)) {
19623                    continue;
19624                }
19625                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19626            }
19627        }
19628    }
19629
19630    /*
19631     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19632     * flag is not set, the data directory is removed as well.
19633     * make sure this flag is set for partially installed apps. If not its meaningless to
19634     * delete a partially installed application.
19635     */
19636    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19637            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19638        String packageName = ps.name;
19639        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19640        // Retrieve object to delete permissions for shared user later on
19641        final PackageParser.Package deletedPkg;
19642        final PackageSetting deletedPs;
19643        // reader
19644        synchronized (mPackages) {
19645            deletedPkg = mPackages.get(packageName);
19646            deletedPs = mSettings.mPackages.get(packageName);
19647            if (outInfo != null) {
19648                outInfo.removedPackage = packageName;
19649                outInfo.installerPackageName = ps.installerPackageName;
19650                outInfo.isStaticSharedLib = deletedPkg != null
19651                        && deletedPkg.staticSharedLibName != null;
19652                outInfo.populateUsers(deletedPs == null ? null
19653                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19654            }
19655        }
19656
19657        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19658
19659        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19660            final PackageParser.Package resolvedPkg;
19661            if (deletedPkg != null) {
19662                resolvedPkg = deletedPkg;
19663            } else {
19664                // We don't have a parsed package when it lives on an ejected
19665                // adopted storage device, so fake something together
19666                resolvedPkg = new PackageParser.Package(ps.name);
19667                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19668            }
19669            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19670                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19671            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19672            if (outInfo != null) {
19673                outInfo.dataRemoved = true;
19674            }
19675            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19676        }
19677
19678        int removedAppId = -1;
19679
19680        // writer
19681        synchronized (mPackages) {
19682            boolean installedStateChanged = false;
19683            if (deletedPs != null) {
19684                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19685                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19686                    clearDefaultBrowserIfNeeded(packageName);
19687                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19688                    removedAppId = mSettings.removePackageLPw(packageName);
19689                    if (outInfo != null) {
19690                        outInfo.removedAppId = removedAppId;
19691                    }
19692                    updatePermissionsLPw(deletedPs.name, null, 0);
19693                    if (deletedPs.sharedUser != null) {
19694                        // Remove permissions associated with package. Since runtime
19695                        // permissions are per user we have to kill the removed package
19696                        // or packages running under the shared user of the removed
19697                        // package if revoking the permissions requested only by the removed
19698                        // package is successful and this causes a change in gids.
19699                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19700                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19701                                    userId);
19702                            if (userIdToKill == UserHandle.USER_ALL
19703                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19704                                // If gids changed for this user, kill all affected packages.
19705                                mHandler.post(new Runnable() {
19706                                    @Override
19707                                    public void run() {
19708                                        // This has to happen with no lock held.
19709                                        killApplication(deletedPs.name, deletedPs.appId,
19710                                                KILL_APP_REASON_GIDS_CHANGED);
19711                                    }
19712                                });
19713                                break;
19714                            }
19715                        }
19716                    }
19717                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19718                }
19719                // make sure to preserve per-user disabled state if this removal was just
19720                // a downgrade of a system app to the factory package
19721                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19722                    if (DEBUG_REMOVE) {
19723                        Slog.d(TAG, "Propagating install state across downgrade");
19724                    }
19725                    for (int userId : allUserHandles) {
19726                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19727                        if (DEBUG_REMOVE) {
19728                            Slog.d(TAG, "    user " + userId + " => " + installed);
19729                        }
19730                        if (installed != ps.getInstalled(userId)) {
19731                            installedStateChanged = true;
19732                        }
19733                        ps.setInstalled(installed, userId);
19734                    }
19735                }
19736            }
19737            // can downgrade to reader
19738            if (writeSettings) {
19739                // Save settings now
19740                mSettings.writeLPr();
19741            }
19742            if (installedStateChanged) {
19743                mSettings.writeKernelMappingLPr(ps);
19744            }
19745        }
19746        if (removedAppId != -1) {
19747            // A user ID was deleted here. Go through all users and remove it
19748            // from KeyStore.
19749            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19750        }
19751    }
19752
19753    static boolean locationIsPrivileged(File path) {
19754        try {
19755            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19756                    .getCanonicalPath();
19757            return path.getCanonicalPath().startsWith(privilegedAppDir);
19758        } catch (IOException e) {
19759            Slog.e(TAG, "Unable to access code path " + path);
19760        }
19761        return false;
19762    }
19763
19764    /*
19765     * Tries to delete system package.
19766     */
19767    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19768            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19769            boolean writeSettings) {
19770        if (deletedPs.parentPackageName != null) {
19771            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19772            return false;
19773        }
19774
19775        final boolean applyUserRestrictions
19776                = (allUserHandles != null) && (outInfo.origUsers != null);
19777        final PackageSetting disabledPs;
19778        // Confirm if the system package has been updated
19779        // An updated system app can be deleted. This will also have to restore
19780        // the system pkg from system partition
19781        // reader
19782        synchronized (mPackages) {
19783            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19784        }
19785
19786        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19787                + " disabledPs=" + disabledPs);
19788
19789        if (disabledPs == null) {
19790            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19791            return false;
19792        } else if (DEBUG_REMOVE) {
19793            Slog.d(TAG, "Deleting system pkg from data partition");
19794        }
19795
19796        if (DEBUG_REMOVE) {
19797            if (applyUserRestrictions) {
19798                Slog.d(TAG, "Remembering install states:");
19799                for (int userId : allUserHandles) {
19800                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19801                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19802                }
19803            }
19804        }
19805
19806        // Delete the updated package
19807        outInfo.isRemovedPackageSystemUpdate = true;
19808        if (outInfo.removedChildPackages != null) {
19809            final int childCount = (deletedPs.childPackageNames != null)
19810                    ? deletedPs.childPackageNames.size() : 0;
19811            for (int i = 0; i < childCount; i++) {
19812                String childPackageName = deletedPs.childPackageNames.get(i);
19813                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19814                        .contains(childPackageName)) {
19815                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19816                            childPackageName);
19817                    if (childInfo != null) {
19818                        childInfo.isRemovedPackageSystemUpdate = true;
19819                    }
19820                }
19821            }
19822        }
19823
19824        if (disabledPs.versionCode < deletedPs.versionCode) {
19825            // Delete data for downgrades
19826            flags &= ~PackageManager.DELETE_KEEP_DATA;
19827        } else {
19828            // Preserve data by setting flag
19829            flags |= PackageManager.DELETE_KEEP_DATA;
19830        }
19831
19832        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19833                outInfo, writeSettings, disabledPs.pkg);
19834        if (!ret) {
19835            return false;
19836        }
19837
19838        // writer
19839        synchronized (mPackages) {
19840            // NOTE: The system package always needs to be enabled; even if it's for
19841            // a compressed stub. If we don't, installing the system package fails
19842            // during scan [scanning checks the disabled packages]. We will reverse
19843            // this later, after we've "installed" the stub.
19844            // Reinstate the old system package
19845            enableSystemPackageLPw(disabledPs.pkg);
19846            // Remove any native libraries from the upgraded package.
19847            removeNativeBinariesLI(deletedPs);
19848        }
19849
19850        // Install the system package
19851        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19852        try {
19853            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
19854                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
19855        } catch (PackageManagerException e) {
19856            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19857                    + e.getMessage());
19858            return false;
19859        } finally {
19860            if (disabledPs.pkg.isStub) {
19861                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
19862            }
19863        }
19864        return true;
19865    }
19866
19867    /**
19868     * Installs a package that's already on the system partition.
19869     */
19870    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
19871            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
19872            @Nullable PermissionsState origPermissionState, boolean writeSettings)
19873                    throws PackageManagerException {
19874        int parseFlags = mDefParseFlags
19875                | PackageParser.PARSE_MUST_BE_APK
19876                | PackageParser.PARSE_IS_SYSTEM
19877                | PackageParser.PARSE_IS_SYSTEM_DIR;
19878        if (isPrivileged || locationIsPrivileged(codePath)) {
19879            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19880        }
19881
19882        final PackageParser.Package newPkg =
19883                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
19884
19885        try {
19886            // update shared libraries for the newly re-installed system package
19887            updateSharedLibrariesLPr(newPkg, null);
19888        } catch (PackageManagerException e) {
19889            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19890        }
19891
19892        prepareAppDataAfterInstallLIF(newPkg);
19893
19894        // writer
19895        synchronized (mPackages) {
19896            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19897
19898            // Propagate the permissions state as we do not want to drop on the floor
19899            // runtime permissions. The update permissions method below will take
19900            // care of removing obsolete permissions and grant install permissions.
19901            if (origPermissionState != null) {
19902                ps.getPermissionsState().copyFrom(origPermissionState);
19903            }
19904            updatePermissionsLPw(newPkg.packageName, newPkg,
19905                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19906
19907            final boolean applyUserRestrictions
19908                    = (allUserHandles != null) && (origUserHandles != null);
19909            if (applyUserRestrictions) {
19910                boolean installedStateChanged = false;
19911                if (DEBUG_REMOVE) {
19912                    Slog.d(TAG, "Propagating install state across reinstall");
19913                }
19914                for (int userId : allUserHandles) {
19915                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
19916                    if (DEBUG_REMOVE) {
19917                        Slog.d(TAG, "    user " + userId + " => " + installed);
19918                    }
19919                    if (installed != ps.getInstalled(userId)) {
19920                        installedStateChanged = true;
19921                    }
19922                    ps.setInstalled(installed, userId);
19923
19924                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19925                }
19926                // Regardless of writeSettings we need to ensure that this restriction
19927                // state propagation is persisted
19928                mSettings.writeAllUsersPackageRestrictionsLPr();
19929                if (installedStateChanged) {
19930                    mSettings.writeKernelMappingLPr(ps);
19931                }
19932            }
19933            // can downgrade to reader here
19934            if (writeSettings) {
19935                mSettings.writeLPr();
19936            }
19937        }
19938        return newPkg;
19939    }
19940
19941    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19942            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19943            PackageRemovedInfo outInfo, boolean writeSettings,
19944            PackageParser.Package replacingPackage) {
19945        synchronized (mPackages) {
19946            if (outInfo != null) {
19947                outInfo.uid = ps.appId;
19948            }
19949
19950            if (outInfo != null && outInfo.removedChildPackages != null) {
19951                final int childCount = (ps.childPackageNames != null)
19952                        ? ps.childPackageNames.size() : 0;
19953                for (int i = 0; i < childCount; i++) {
19954                    String childPackageName = ps.childPackageNames.get(i);
19955                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19956                    if (childPs == null) {
19957                        return false;
19958                    }
19959                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19960                            childPackageName);
19961                    if (childInfo != null) {
19962                        childInfo.uid = childPs.appId;
19963                    }
19964                }
19965            }
19966        }
19967
19968        // Delete package data from internal structures and also remove data if flag is set
19969        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19970
19971        // Delete the child packages data
19972        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19973        for (int i = 0; i < childCount; i++) {
19974            PackageSetting childPs;
19975            synchronized (mPackages) {
19976                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19977            }
19978            if (childPs != null) {
19979                PackageRemovedInfo childOutInfo = (outInfo != null
19980                        && outInfo.removedChildPackages != null)
19981                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19982                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19983                        && (replacingPackage != null
19984                        && !replacingPackage.hasChildPackage(childPs.name))
19985                        ? flags & ~DELETE_KEEP_DATA : flags;
19986                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19987                        deleteFlags, writeSettings);
19988            }
19989        }
19990
19991        // Delete application code and resources only for parent packages
19992        if (ps.parentPackageName == null) {
19993            if (deleteCodeAndResources && (outInfo != null)) {
19994                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19995                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19996                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19997            }
19998        }
19999
20000        return true;
20001    }
20002
20003    @Override
20004    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
20005            int userId) {
20006        mContext.enforceCallingOrSelfPermission(
20007                android.Manifest.permission.DELETE_PACKAGES, null);
20008        synchronized (mPackages) {
20009            // Cannot block uninstall of static shared libs as they are
20010            // considered a part of the using app (emulating static linking).
20011            // Also static libs are installed always on internal storage.
20012            PackageParser.Package pkg = mPackages.get(packageName);
20013            if (pkg != null && pkg.staticSharedLibName != null) {
20014                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
20015                        + " providing static shared library: " + pkg.staticSharedLibName);
20016                return false;
20017            }
20018            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
20019            mSettings.writePackageRestrictionsLPr(userId);
20020        }
20021        return true;
20022    }
20023
20024    @Override
20025    public boolean getBlockUninstallForUser(String packageName, int userId) {
20026        synchronized (mPackages) {
20027            final PackageSetting ps = mSettings.mPackages.get(packageName);
20028            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
20029                return false;
20030            }
20031            return mSettings.getBlockUninstallLPr(userId, packageName);
20032        }
20033    }
20034
20035    @Override
20036    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
20037        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
20038        synchronized (mPackages) {
20039            PackageSetting ps = mSettings.mPackages.get(packageName);
20040            if (ps == null) {
20041                Log.w(TAG, "Package doesn't exist: " + packageName);
20042                return false;
20043            }
20044            if (systemUserApp) {
20045                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20046            } else {
20047                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20048            }
20049            mSettings.writeLPr();
20050        }
20051        return true;
20052    }
20053
20054    /*
20055     * This method handles package deletion in general
20056     */
20057    private boolean deletePackageLIF(String packageName, UserHandle user,
20058            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
20059            PackageRemovedInfo outInfo, boolean writeSettings,
20060            PackageParser.Package replacingPackage) {
20061        if (packageName == null) {
20062            Slog.w(TAG, "Attempt to delete null packageName.");
20063            return false;
20064        }
20065
20066        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
20067
20068        PackageSetting ps;
20069        synchronized (mPackages) {
20070            ps = mSettings.mPackages.get(packageName);
20071            if (ps == null) {
20072                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20073                return false;
20074            }
20075
20076            if (ps.parentPackageName != null && (!isSystemApp(ps)
20077                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
20078                if (DEBUG_REMOVE) {
20079                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
20080                            + ((user == null) ? UserHandle.USER_ALL : user));
20081                }
20082                final int removedUserId = (user != null) ? user.getIdentifier()
20083                        : UserHandle.USER_ALL;
20084                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
20085                    return false;
20086                }
20087                markPackageUninstalledForUserLPw(ps, user);
20088                scheduleWritePackageRestrictionsLocked(user);
20089                return true;
20090            }
20091        }
20092
20093        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
20094                && user.getIdentifier() != UserHandle.USER_ALL)) {
20095            // The caller is asking that the package only be deleted for a single
20096            // user.  To do this, we just mark its uninstalled state and delete
20097            // its data. If this is a system app, we only allow this to happen if
20098            // they have set the special DELETE_SYSTEM_APP which requests different
20099            // semantics than normal for uninstalling system apps.
20100            markPackageUninstalledForUserLPw(ps, user);
20101
20102            if (!isSystemApp(ps)) {
20103                // Do not uninstall the APK if an app should be cached
20104                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
20105                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
20106                    // Other user still have this package installed, so all
20107                    // we need to do is clear this user's data and save that
20108                    // it is uninstalled.
20109                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
20110                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20111                        return false;
20112                    }
20113                    scheduleWritePackageRestrictionsLocked(user);
20114                    return true;
20115                } else {
20116                    // We need to set it back to 'installed' so the uninstall
20117                    // broadcasts will be sent correctly.
20118                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
20119                    ps.setInstalled(true, user.getIdentifier());
20120                    mSettings.writeKernelMappingLPr(ps);
20121                }
20122            } else {
20123                // This is a system app, so we assume that the
20124                // other users still have this package installed, so all
20125                // we need to do is clear this user's data and save that
20126                // it is uninstalled.
20127                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
20128                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20129                    return false;
20130                }
20131                scheduleWritePackageRestrictionsLocked(user);
20132                return true;
20133            }
20134        }
20135
20136        // If we are deleting a composite package for all users, keep track
20137        // of result for each child.
20138        if (ps.childPackageNames != null && outInfo != null) {
20139            synchronized (mPackages) {
20140                final int childCount = ps.childPackageNames.size();
20141                outInfo.removedChildPackages = new ArrayMap<>(childCount);
20142                for (int i = 0; i < childCount; i++) {
20143                    String childPackageName = ps.childPackageNames.get(i);
20144                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
20145                    childInfo.removedPackage = childPackageName;
20146                    childInfo.installerPackageName = ps.installerPackageName;
20147                    outInfo.removedChildPackages.put(childPackageName, childInfo);
20148                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20149                    if (childPs != null) {
20150                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
20151                    }
20152                }
20153            }
20154        }
20155
20156        boolean ret = false;
20157        if (isSystemApp(ps)) {
20158            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
20159            // When an updated system application is deleted we delete the existing resources
20160            // as well and fall back to existing code in system partition
20161            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
20162        } else {
20163            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
20164            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
20165                    outInfo, writeSettings, replacingPackage);
20166        }
20167
20168        // Take a note whether we deleted the package for all users
20169        if (outInfo != null) {
20170            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
20171            if (outInfo.removedChildPackages != null) {
20172                synchronized (mPackages) {
20173                    final int childCount = outInfo.removedChildPackages.size();
20174                    for (int i = 0; i < childCount; i++) {
20175                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
20176                        if (childInfo != null) {
20177                            childInfo.removedForAllUsers = mPackages.get(
20178                                    childInfo.removedPackage) == null;
20179                        }
20180                    }
20181                }
20182            }
20183            // If we uninstalled an update to a system app there may be some
20184            // child packages that appeared as they are declared in the system
20185            // app but were not declared in the update.
20186            if (isSystemApp(ps)) {
20187                synchronized (mPackages) {
20188                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
20189                    final int childCount = (updatedPs.childPackageNames != null)
20190                            ? updatedPs.childPackageNames.size() : 0;
20191                    for (int i = 0; i < childCount; i++) {
20192                        String childPackageName = updatedPs.childPackageNames.get(i);
20193                        if (outInfo.removedChildPackages == null
20194                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
20195                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20196                            if (childPs == null) {
20197                                continue;
20198                            }
20199                            PackageInstalledInfo installRes = new PackageInstalledInfo();
20200                            installRes.name = childPackageName;
20201                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
20202                            installRes.pkg = mPackages.get(childPackageName);
20203                            installRes.uid = childPs.pkg.applicationInfo.uid;
20204                            if (outInfo.appearedChildPackages == null) {
20205                                outInfo.appearedChildPackages = new ArrayMap<>();
20206                            }
20207                            outInfo.appearedChildPackages.put(childPackageName, installRes);
20208                        }
20209                    }
20210                }
20211            }
20212        }
20213
20214        return ret;
20215    }
20216
20217    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
20218        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
20219                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
20220        for (int nextUserId : userIds) {
20221            if (DEBUG_REMOVE) {
20222                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
20223            }
20224            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
20225                    false /*installed*/,
20226                    true /*stopped*/,
20227                    true /*notLaunched*/,
20228                    false /*hidden*/,
20229                    false /*suspended*/,
20230                    false /*instantApp*/,
20231                    false /*virtualPreload*/,
20232                    null /*lastDisableAppCaller*/,
20233                    null /*enabledComponents*/,
20234                    null /*disabledComponents*/,
20235                    ps.readUserState(nextUserId).domainVerificationStatus,
20236                    0, PackageManager.INSTALL_REASON_UNKNOWN);
20237        }
20238        mSettings.writeKernelMappingLPr(ps);
20239    }
20240
20241    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
20242            PackageRemovedInfo outInfo) {
20243        final PackageParser.Package pkg;
20244        synchronized (mPackages) {
20245            pkg = mPackages.get(ps.name);
20246        }
20247
20248        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20249                : new int[] {userId};
20250        for (int nextUserId : userIds) {
20251            if (DEBUG_REMOVE) {
20252                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20253                        + nextUserId);
20254            }
20255
20256            destroyAppDataLIF(pkg, userId,
20257                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20258            destroyAppProfilesLIF(pkg, userId);
20259            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20260            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20261            schedulePackageCleaning(ps.name, nextUserId, false);
20262            synchronized (mPackages) {
20263                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20264                    scheduleWritePackageRestrictionsLocked(nextUserId);
20265                }
20266                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20267            }
20268        }
20269
20270        if (outInfo != null) {
20271            outInfo.removedPackage = ps.name;
20272            outInfo.installerPackageName = ps.installerPackageName;
20273            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20274            outInfo.removedAppId = ps.appId;
20275            outInfo.removedUsers = userIds;
20276            outInfo.broadcastUsers = userIds;
20277        }
20278
20279        return true;
20280    }
20281
20282    private final class ClearStorageConnection implements ServiceConnection {
20283        IMediaContainerService mContainerService;
20284
20285        @Override
20286        public void onServiceConnected(ComponentName name, IBinder service) {
20287            synchronized (this) {
20288                mContainerService = IMediaContainerService.Stub
20289                        .asInterface(Binder.allowBlocking(service));
20290                notifyAll();
20291            }
20292        }
20293
20294        @Override
20295        public void onServiceDisconnected(ComponentName name) {
20296        }
20297    }
20298
20299    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20300        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20301
20302        final boolean mounted;
20303        if (Environment.isExternalStorageEmulated()) {
20304            mounted = true;
20305        } else {
20306            final String status = Environment.getExternalStorageState();
20307
20308            mounted = status.equals(Environment.MEDIA_MOUNTED)
20309                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20310        }
20311
20312        if (!mounted) {
20313            return;
20314        }
20315
20316        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20317        int[] users;
20318        if (userId == UserHandle.USER_ALL) {
20319            users = sUserManager.getUserIds();
20320        } else {
20321            users = new int[] { userId };
20322        }
20323        final ClearStorageConnection conn = new ClearStorageConnection();
20324        if (mContext.bindServiceAsUser(
20325                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20326            try {
20327                for (int curUser : users) {
20328                    long timeout = SystemClock.uptimeMillis() + 5000;
20329                    synchronized (conn) {
20330                        long now;
20331                        while (conn.mContainerService == null &&
20332                                (now = SystemClock.uptimeMillis()) < timeout) {
20333                            try {
20334                                conn.wait(timeout - now);
20335                            } catch (InterruptedException e) {
20336                            }
20337                        }
20338                    }
20339                    if (conn.mContainerService == null) {
20340                        return;
20341                    }
20342
20343                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20344                    clearDirectory(conn.mContainerService,
20345                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20346                    if (allData) {
20347                        clearDirectory(conn.mContainerService,
20348                                userEnv.buildExternalStorageAppDataDirs(packageName));
20349                        clearDirectory(conn.mContainerService,
20350                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20351                    }
20352                }
20353            } finally {
20354                mContext.unbindService(conn);
20355            }
20356        }
20357    }
20358
20359    @Override
20360    public void clearApplicationProfileData(String packageName) {
20361        enforceSystemOrRoot("Only the system can clear all profile data");
20362
20363        final PackageParser.Package pkg;
20364        synchronized (mPackages) {
20365            pkg = mPackages.get(packageName);
20366        }
20367
20368        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20369            synchronized (mInstallLock) {
20370                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20371            }
20372        }
20373    }
20374
20375    @Override
20376    public void clearApplicationUserData(final String packageName,
20377            final IPackageDataObserver observer, final int userId) {
20378        mContext.enforceCallingOrSelfPermission(
20379                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20380
20381        final int callingUid = Binder.getCallingUid();
20382        enforceCrossUserPermission(callingUid, userId,
20383                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20384
20385        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20386        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
20387        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20388            throw new SecurityException("Cannot clear data for a protected package: "
20389                    + packageName);
20390        }
20391        // Queue up an async operation since the package deletion may take a little while.
20392        mHandler.post(new Runnable() {
20393            public void run() {
20394                mHandler.removeCallbacks(this);
20395                final boolean succeeded;
20396                if (!filterApp) {
20397                    try (PackageFreezer freezer = freezePackage(packageName,
20398                            "clearApplicationUserData")) {
20399                        synchronized (mInstallLock) {
20400                            succeeded = clearApplicationUserDataLIF(packageName, userId);
20401                        }
20402                        clearExternalStorageDataSync(packageName, userId, true);
20403                        synchronized (mPackages) {
20404                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20405                                    packageName, userId);
20406                        }
20407                    }
20408                    if (succeeded) {
20409                        // invoke DeviceStorageMonitor's update method to clear any notifications
20410                        DeviceStorageMonitorInternal dsm = LocalServices
20411                                .getService(DeviceStorageMonitorInternal.class);
20412                        if (dsm != null) {
20413                            dsm.checkMemory();
20414                        }
20415                    }
20416                } else {
20417                    succeeded = false;
20418                }
20419                if (observer != null) {
20420                    try {
20421                        observer.onRemoveCompleted(packageName, succeeded);
20422                    } catch (RemoteException e) {
20423                        Log.i(TAG, "Observer no longer exists.");
20424                    }
20425                } //end if observer
20426            } //end run
20427        });
20428    }
20429
20430    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20431        if (packageName == null) {
20432            Slog.w(TAG, "Attempt to delete null packageName.");
20433            return false;
20434        }
20435
20436        // Try finding details about the requested package
20437        PackageParser.Package pkg;
20438        synchronized (mPackages) {
20439            pkg = mPackages.get(packageName);
20440            if (pkg == null) {
20441                final PackageSetting ps = mSettings.mPackages.get(packageName);
20442                if (ps != null) {
20443                    pkg = ps.pkg;
20444                }
20445            }
20446
20447            if (pkg == null) {
20448                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20449                return false;
20450            }
20451
20452            PackageSetting ps = (PackageSetting) pkg.mExtras;
20453            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20454        }
20455
20456        clearAppDataLIF(pkg, userId,
20457                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20458
20459        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20460        removeKeystoreDataIfNeeded(userId, appId);
20461
20462        UserManagerInternal umInternal = getUserManagerInternal();
20463        final int flags;
20464        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20465            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20466        } else if (umInternal.isUserRunning(userId)) {
20467            flags = StorageManager.FLAG_STORAGE_DE;
20468        } else {
20469            flags = 0;
20470        }
20471        prepareAppDataContentsLIF(pkg, userId, flags);
20472
20473        return true;
20474    }
20475
20476    /**
20477     * Reverts user permission state changes (permissions and flags) in
20478     * all packages for a given user.
20479     *
20480     * @param userId The device user for which to do a reset.
20481     */
20482    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20483        final int packageCount = mPackages.size();
20484        for (int i = 0; i < packageCount; i++) {
20485            PackageParser.Package pkg = mPackages.valueAt(i);
20486            PackageSetting ps = (PackageSetting) pkg.mExtras;
20487            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20488        }
20489    }
20490
20491    private void resetNetworkPolicies(int userId) {
20492        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20493    }
20494
20495    /**
20496     * Reverts user permission state changes (permissions and flags).
20497     *
20498     * @param ps The package for which to reset.
20499     * @param userId The device user for which to do a reset.
20500     */
20501    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20502            final PackageSetting ps, final int userId) {
20503        if (ps.pkg == null) {
20504            return;
20505        }
20506
20507        // These are flags that can change base on user actions.
20508        final int userSettableMask = FLAG_PERMISSION_USER_SET
20509                | FLAG_PERMISSION_USER_FIXED
20510                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20511                | FLAG_PERMISSION_REVIEW_REQUIRED;
20512
20513        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20514                | FLAG_PERMISSION_POLICY_FIXED;
20515
20516        boolean writeInstallPermissions = false;
20517        boolean writeRuntimePermissions = false;
20518
20519        final int permissionCount = ps.pkg.requestedPermissions.size();
20520        for (int i = 0; i < permissionCount; i++) {
20521            String permission = ps.pkg.requestedPermissions.get(i);
20522
20523            BasePermission bp = mSettings.mPermissions.get(permission);
20524            if (bp == null) {
20525                continue;
20526            }
20527
20528            // If shared user we just reset the state to which only this app contributed.
20529            if (ps.sharedUser != null) {
20530                boolean used = false;
20531                final int packageCount = ps.sharedUser.packages.size();
20532                for (int j = 0; j < packageCount; j++) {
20533                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20534                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20535                            && pkg.pkg.requestedPermissions.contains(permission)) {
20536                        used = true;
20537                        break;
20538                    }
20539                }
20540                if (used) {
20541                    continue;
20542                }
20543            }
20544
20545            PermissionsState permissionsState = ps.getPermissionsState();
20546
20547            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20548
20549            // Always clear the user settable flags.
20550            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20551                    bp.name) != null;
20552            // If permission review is enabled and this is a legacy app, mark the
20553            // permission as requiring a review as this is the initial state.
20554            int flags = 0;
20555            if (mPermissionReviewRequired
20556                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20557                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20558            }
20559            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20560                if (hasInstallState) {
20561                    writeInstallPermissions = true;
20562                } else {
20563                    writeRuntimePermissions = true;
20564                }
20565            }
20566
20567            // Below is only runtime permission handling.
20568            if (!bp.isRuntime()) {
20569                continue;
20570            }
20571
20572            // Never clobber system or policy.
20573            if ((oldFlags & policyOrSystemFlags) != 0) {
20574                continue;
20575            }
20576
20577            // If this permission was granted by default, make sure it is.
20578            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20579                if (permissionsState.grantRuntimePermission(bp, userId)
20580                        != PERMISSION_OPERATION_FAILURE) {
20581                    writeRuntimePermissions = true;
20582                }
20583            // If permission review is enabled the permissions for a legacy apps
20584            // are represented as constantly granted runtime ones, so don't revoke.
20585            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20586                // Otherwise, reset the permission.
20587                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20588                switch (revokeResult) {
20589                    case PERMISSION_OPERATION_SUCCESS:
20590                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20591                        writeRuntimePermissions = true;
20592                        final int appId = ps.appId;
20593                        mHandler.post(new Runnable() {
20594                            @Override
20595                            public void run() {
20596                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20597                            }
20598                        });
20599                    } break;
20600                }
20601            }
20602        }
20603
20604        // Synchronously write as we are taking permissions away.
20605        if (writeRuntimePermissions) {
20606            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20607        }
20608
20609        // Synchronously write as we are taking permissions away.
20610        if (writeInstallPermissions) {
20611            mSettings.writeLPr();
20612        }
20613    }
20614
20615    /**
20616     * Remove entries from the keystore daemon. Will only remove it if the
20617     * {@code appId} is valid.
20618     */
20619    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20620        if (appId < 0) {
20621            return;
20622        }
20623
20624        final KeyStore keyStore = KeyStore.getInstance();
20625        if (keyStore != null) {
20626            if (userId == UserHandle.USER_ALL) {
20627                for (final int individual : sUserManager.getUserIds()) {
20628                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20629                }
20630            } else {
20631                keyStore.clearUid(UserHandle.getUid(userId, appId));
20632            }
20633        } else {
20634            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20635        }
20636    }
20637
20638    @Override
20639    public void deleteApplicationCacheFiles(final String packageName,
20640            final IPackageDataObserver observer) {
20641        final int userId = UserHandle.getCallingUserId();
20642        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20643    }
20644
20645    @Override
20646    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20647            final IPackageDataObserver observer) {
20648        final int callingUid = Binder.getCallingUid();
20649        mContext.enforceCallingOrSelfPermission(
20650                android.Manifest.permission.DELETE_CACHE_FILES, null);
20651        enforceCrossUserPermission(callingUid, userId,
20652                /* requireFullPermission= */ true, /* checkShell= */ false,
20653                "delete application cache files");
20654        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20655                android.Manifest.permission.ACCESS_INSTANT_APPS);
20656
20657        final PackageParser.Package pkg;
20658        synchronized (mPackages) {
20659            pkg = mPackages.get(packageName);
20660        }
20661
20662        // Queue up an async operation since the package deletion may take a little while.
20663        mHandler.post(new Runnable() {
20664            public void run() {
20665                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20666                boolean doClearData = true;
20667                if (ps != null) {
20668                    final boolean targetIsInstantApp =
20669                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20670                    doClearData = !targetIsInstantApp
20671                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20672                }
20673                if (doClearData) {
20674                    synchronized (mInstallLock) {
20675                        final int flags = StorageManager.FLAG_STORAGE_DE
20676                                | StorageManager.FLAG_STORAGE_CE;
20677                        // We're only clearing cache files, so we don't care if the
20678                        // app is unfrozen and still able to run
20679                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20680                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20681                    }
20682                    clearExternalStorageDataSync(packageName, userId, false);
20683                }
20684                if (observer != null) {
20685                    try {
20686                        observer.onRemoveCompleted(packageName, true);
20687                    } catch (RemoteException e) {
20688                        Log.i(TAG, "Observer no longer exists.");
20689                    }
20690                }
20691            }
20692        });
20693    }
20694
20695    @Override
20696    public void getPackageSizeInfo(final String packageName, int userHandle,
20697            final IPackageStatsObserver observer) {
20698        throw new UnsupportedOperationException(
20699                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20700    }
20701
20702    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20703        final PackageSetting ps;
20704        synchronized (mPackages) {
20705            ps = mSettings.mPackages.get(packageName);
20706            if (ps == null) {
20707                Slog.w(TAG, "Failed to find settings for " + packageName);
20708                return false;
20709            }
20710        }
20711
20712        final String[] packageNames = { packageName };
20713        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20714        final String[] codePaths = { ps.codePathString };
20715
20716        try {
20717            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20718                    ps.appId, ceDataInodes, codePaths, stats);
20719
20720            // For now, ignore code size of packages on system partition
20721            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20722                stats.codeSize = 0;
20723            }
20724
20725            // External clients expect these to be tracked separately
20726            stats.dataSize -= stats.cacheSize;
20727
20728        } catch (InstallerException e) {
20729            Slog.w(TAG, String.valueOf(e));
20730            return false;
20731        }
20732
20733        return true;
20734    }
20735
20736    private int getUidTargetSdkVersionLockedLPr(int uid) {
20737        Object obj = mSettings.getUserIdLPr(uid);
20738        if (obj instanceof SharedUserSetting) {
20739            final SharedUserSetting sus = (SharedUserSetting) obj;
20740            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20741            final Iterator<PackageSetting> it = sus.packages.iterator();
20742            while (it.hasNext()) {
20743                final PackageSetting ps = it.next();
20744                if (ps.pkg != null) {
20745                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20746                    if (v < vers) vers = v;
20747                }
20748            }
20749            return vers;
20750        } else if (obj instanceof PackageSetting) {
20751            final PackageSetting ps = (PackageSetting) obj;
20752            if (ps.pkg != null) {
20753                return ps.pkg.applicationInfo.targetSdkVersion;
20754            }
20755        }
20756        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20757    }
20758
20759    @Override
20760    public void addPreferredActivity(IntentFilter filter, int match,
20761            ComponentName[] set, ComponentName activity, int userId) {
20762        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20763                "Adding preferred");
20764    }
20765
20766    private void addPreferredActivityInternal(IntentFilter filter, int match,
20767            ComponentName[] set, ComponentName activity, boolean always, int userId,
20768            String opname) {
20769        // writer
20770        int callingUid = Binder.getCallingUid();
20771        enforceCrossUserPermission(callingUid, userId,
20772                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20773        if (filter.countActions() == 0) {
20774            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20775            return;
20776        }
20777        synchronized (mPackages) {
20778            if (mContext.checkCallingOrSelfPermission(
20779                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20780                    != PackageManager.PERMISSION_GRANTED) {
20781                if (getUidTargetSdkVersionLockedLPr(callingUid)
20782                        < Build.VERSION_CODES.FROYO) {
20783                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20784                            + callingUid);
20785                    return;
20786                }
20787                mContext.enforceCallingOrSelfPermission(
20788                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20789            }
20790
20791            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20792            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20793                    + userId + ":");
20794            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20795            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20796            scheduleWritePackageRestrictionsLocked(userId);
20797            postPreferredActivityChangedBroadcast(userId);
20798        }
20799    }
20800
20801    private void postPreferredActivityChangedBroadcast(int userId) {
20802        mHandler.post(() -> {
20803            final IActivityManager am = ActivityManager.getService();
20804            if (am == null) {
20805                return;
20806            }
20807
20808            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20809            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20810            try {
20811                am.broadcastIntent(null, intent, null, null,
20812                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20813                        null, false, false, userId);
20814            } catch (RemoteException e) {
20815            }
20816        });
20817    }
20818
20819    @Override
20820    public void replacePreferredActivity(IntentFilter filter, int match,
20821            ComponentName[] set, ComponentName activity, int userId) {
20822        if (filter.countActions() != 1) {
20823            throw new IllegalArgumentException(
20824                    "replacePreferredActivity expects filter to have only 1 action.");
20825        }
20826        if (filter.countDataAuthorities() != 0
20827                || filter.countDataPaths() != 0
20828                || filter.countDataSchemes() > 1
20829                || filter.countDataTypes() != 0) {
20830            throw new IllegalArgumentException(
20831                    "replacePreferredActivity expects filter to have no data authorities, " +
20832                    "paths, or types; and at most one scheme.");
20833        }
20834
20835        final int callingUid = Binder.getCallingUid();
20836        enforceCrossUserPermission(callingUid, userId,
20837                true /* requireFullPermission */, false /* checkShell */,
20838                "replace preferred activity");
20839        synchronized (mPackages) {
20840            if (mContext.checkCallingOrSelfPermission(
20841                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20842                    != PackageManager.PERMISSION_GRANTED) {
20843                if (getUidTargetSdkVersionLockedLPr(callingUid)
20844                        < Build.VERSION_CODES.FROYO) {
20845                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20846                            + Binder.getCallingUid());
20847                    return;
20848                }
20849                mContext.enforceCallingOrSelfPermission(
20850                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20851            }
20852
20853            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20854            if (pir != null) {
20855                // Get all of the existing entries that exactly match this filter.
20856                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20857                if (existing != null && existing.size() == 1) {
20858                    PreferredActivity cur = existing.get(0);
20859                    if (DEBUG_PREFERRED) {
20860                        Slog.i(TAG, "Checking replace of preferred:");
20861                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20862                        if (!cur.mPref.mAlways) {
20863                            Slog.i(TAG, "  -- CUR; not mAlways!");
20864                        } else {
20865                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20866                            Slog.i(TAG, "  -- CUR: mSet="
20867                                    + Arrays.toString(cur.mPref.mSetComponents));
20868                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20869                            Slog.i(TAG, "  -- NEW: mMatch="
20870                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20871                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20872                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20873                        }
20874                    }
20875                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20876                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20877                            && cur.mPref.sameSet(set)) {
20878                        // Setting the preferred activity to what it happens to be already
20879                        if (DEBUG_PREFERRED) {
20880                            Slog.i(TAG, "Replacing with same preferred activity "
20881                                    + cur.mPref.mShortComponent + " for user "
20882                                    + userId + ":");
20883                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20884                        }
20885                        return;
20886                    }
20887                }
20888
20889                if (existing != null) {
20890                    if (DEBUG_PREFERRED) {
20891                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20892                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20893                    }
20894                    for (int i = 0; i < existing.size(); i++) {
20895                        PreferredActivity pa = existing.get(i);
20896                        if (DEBUG_PREFERRED) {
20897                            Slog.i(TAG, "Removing existing preferred activity "
20898                                    + pa.mPref.mComponent + ":");
20899                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20900                        }
20901                        pir.removeFilter(pa);
20902                    }
20903                }
20904            }
20905            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20906                    "Replacing preferred");
20907        }
20908    }
20909
20910    @Override
20911    public void clearPackagePreferredActivities(String packageName) {
20912        final int callingUid = Binder.getCallingUid();
20913        if (getInstantAppPackageName(callingUid) != null) {
20914            return;
20915        }
20916        // writer
20917        synchronized (mPackages) {
20918            PackageParser.Package pkg = mPackages.get(packageName);
20919            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20920                if (mContext.checkCallingOrSelfPermission(
20921                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20922                        != PackageManager.PERMISSION_GRANTED) {
20923                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20924                            < Build.VERSION_CODES.FROYO) {
20925                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20926                                + callingUid);
20927                        return;
20928                    }
20929                    mContext.enforceCallingOrSelfPermission(
20930                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20931                }
20932            }
20933            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20934            if (ps != null
20935                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20936                return;
20937            }
20938            int user = UserHandle.getCallingUserId();
20939            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20940                scheduleWritePackageRestrictionsLocked(user);
20941            }
20942        }
20943    }
20944
20945    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20946    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20947        ArrayList<PreferredActivity> removed = null;
20948        boolean changed = false;
20949        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20950            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20951            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20952            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20953                continue;
20954            }
20955            Iterator<PreferredActivity> it = pir.filterIterator();
20956            while (it.hasNext()) {
20957                PreferredActivity pa = it.next();
20958                // Mark entry for removal only if it matches the package name
20959                // and the entry is of type "always".
20960                if (packageName == null ||
20961                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20962                                && pa.mPref.mAlways)) {
20963                    if (removed == null) {
20964                        removed = new ArrayList<PreferredActivity>();
20965                    }
20966                    removed.add(pa);
20967                }
20968            }
20969            if (removed != null) {
20970                for (int j=0; j<removed.size(); j++) {
20971                    PreferredActivity pa = removed.get(j);
20972                    pir.removeFilter(pa);
20973                }
20974                changed = true;
20975            }
20976        }
20977        if (changed) {
20978            postPreferredActivityChangedBroadcast(userId);
20979        }
20980        return changed;
20981    }
20982
20983    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20984    private void clearIntentFilterVerificationsLPw(int userId) {
20985        final int packageCount = mPackages.size();
20986        for (int i = 0; i < packageCount; i++) {
20987            PackageParser.Package pkg = mPackages.valueAt(i);
20988            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20989        }
20990    }
20991
20992    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20993    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20994        if (userId == UserHandle.USER_ALL) {
20995            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20996                    sUserManager.getUserIds())) {
20997                for (int oneUserId : sUserManager.getUserIds()) {
20998                    scheduleWritePackageRestrictionsLocked(oneUserId);
20999                }
21000            }
21001        } else {
21002            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
21003                scheduleWritePackageRestrictionsLocked(userId);
21004            }
21005        }
21006    }
21007
21008    /** Clears state for all users, and touches intent filter verification policy */
21009    void clearDefaultBrowserIfNeeded(String packageName) {
21010        for (int oneUserId : sUserManager.getUserIds()) {
21011            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
21012        }
21013    }
21014
21015    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
21016        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
21017        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
21018            if (packageName.equals(defaultBrowserPackageName)) {
21019                setDefaultBrowserPackageName(null, userId);
21020            }
21021        }
21022    }
21023
21024    @Override
21025    public void resetApplicationPreferences(int userId) {
21026        mContext.enforceCallingOrSelfPermission(
21027                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
21028        final long identity = Binder.clearCallingIdentity();
21029        // writer
21030        try {
21031            synchronized (mPackages) {
21032                clearPackagePreferredActivitiesLPw(null, userId);
21033                mSettings.applyDefaultPreferredAppsLPw(this, userId);
21034                // TODO: We have to reset the default SMS and Phone. This requires
21035                // significant refactoring to keep all default apps in the package
21036                // manager (cleaner but more work) or have the services provide
21037                // callbacks to the package manager to request a default app reset.
21038                applyFactoryDefaultBrowserLPw(userId);
21039                clearIntentFilterVerificationsLPw(userId);
21040                primeDomainVerificationsLPw(userId);
21041                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
21042                scheduleWritePackageRestrictionsLocked(userId);
21043            }
21044            resetNetworkPolicies(userId);
21045        } finally {
21046            Binder.restoreCallingIdentity(identity);
21047        }
21048    }
21049
21050    @Override
21051    public int getPreferredActivities(List<IntentFilter> outFilters,
21052            List<ComponentName> outActivities, String packageName) {
21053        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21054            return 0;
21055        }
21056        int num = 0;
21057        final int userId = UserHandle.getCallingUserId();
21058        // reader
21059        synchronized (mPackages) {
21060            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
21061            if (pir != null) {
21062                final Iterator<PreferredActivity> it = pir.filterIterator();
21063                while (it.hasNext()) {
21064                    final PreferredActivity pa = it.next();
21065                    if (packageName == null
21066                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
21067                                    && pa.mPref.mAlways)) {
21068                        if (outFilters != null) {
21069                            outFilters.add(new IntentFilter(pa));
21070                        }
21071                        if (outActivities != null) {
21072                            outActivities.add(pa.mPref.mComponent);
21073                        }
21074                    }
21075                }
21076            }
21077        }
21078
21079        return num;
21080    }
21081
21082    @Override
21083    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
21084            int userId) {
21085        int callingUid = Binder.getCallingUid();
21086        if (callingUid != Process.SYSTEM_UID) {
21087            throw new SecurityException(
21088                    "addPersistentPreferredActivity can only be run by the system");
21089        }
21090        if (filter.countActions() == 0) {
21091            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
21092            return;
21093        }
21094        synchronized (mPackages) {
21095            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
21096                    ":");
21097            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
21098            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
21099                    new PersistentPreferredActivity(filter, activity));
21100            scheduleWritePackageRestrictionsLocked(userId);
21101            postPreferredActivityChangedBroadcast(userId);
21102        }
21103    }
21104
21105    @Override
21106    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
21107        int callingUid = Binder.getCallingUid();
21108        if (callingUid != Process.SYSTEM_UID) {
21109            throw new SecurityException(
21110                    "clearPackagePersistentPreferredActivities can only be run by the system");
21111        }
21112        ArrayList<PersistentPreferredActivity> removed = null;
21113        boolean changed = false;
21114        synchronized (mPackages) {
21115            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
21116                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
21117                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
21118                        .valueAt(i);
21119                if (userId != thisUserId) {
21120                    continue;
21121                }
21122                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
21123                while (it.hasNext()) {
21124                    PersistentPreferredActivity ppa = it.next();
21125                    // Mark entry for removal only if it matches the package name.
21126                    if (ppa.mComponent.getPackageName().equals(packageName)) {
21127                        if (removed == null) {
21128                            removed = new ArrayList<PersistentPreferredActivity>();
21129                        }
21130                        removed.add(ppa);
21131                    }
21132                }
21133                if (removed != null) {
21134                    for (int j=0; j<removed.size(); j++) {
21135                        PersistentPreferredActivity ppa = removed.get(j);
21136                        ppir.removeFilter(ppa);
21137                    }
21138                    changed = true;
21139                }
21140            }
21141
21142            if (changed) {
21143                scheduleWritePackageRestrictionsLocked(userId);
21144                postPreferredActivityChangedBroadcast(userId);
21145            }
21146        }
21147    }
21148
21149    /**
21150     * Common machinery for picking apart a restored XML blob and passing
21151     * it to a caller-supplied functor to be applied to the running system.
21152     */
21153    private void restoreFromXml(XmlPullParser parser, int userId,
21154            String expectedStartTag, BlobXmlRestorer functor)
21155            throws IOException, XmlPullParserException {
21156        int type;
21157        while ((type = parser.next()) != XmlPullParser.START_TAG
21158                && type != XmlPullParser.END_DOCUMENT) {
21159        }
21160        if (type != XmlPullParser.START_TAG) {
21161            // oops didn't find a start tag?!
21162            if (DEBUG_BACKUP) {
21163                Slog.e(TAG, "Didn't find start tag during restore");
21164            }
21165            return;
21166        }
21167Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
21168        // this is supposed to be TAG_PREFERRED_BACKUP
21169        if (!expectedStartTag.equals(parser.getName())) {
21170            if (DEBUG_BACKUP) {
21171                Slog.e(TAG, "Found unexpected tag " + parser.getName());
21172            }
21173            return;
21174        }
21175
21176        // skip interfering stuff, then we're aligned with the backing implementation
21177        while ((type = parser.next()) == XmlPullParser.TEXT) { }
21178Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
21179        functor.apply(parser, userId);
21180    }
21181
21182    private interface BlobXmlRestorer {
21183        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
21184    }
21185
21186    /**
21187     * Non-Binder method, support for the backup/restore mechanism: write the
21188     * full set of preferred activities in its canonical XML format.  Returns the
21189     * XML output as a byte array, or null if there is none.
21190     */
21191    @Override
21192    public byte[] getPreferredActivityBackup(int userId) {
21193        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21194            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
21195        }
21196
21197        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21198        try {
21199            final XmlSerializer serializer = new FastXmlSerializer();
21200            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21201            serializer.startDocument(null, true);
21202            serializer.startTag(null, TAG_PREFERRED_BACKUP);
21203
21204            synchronized (mPackages) {
21205                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
21206            }
21207
21208            serializer.endTag(null, TAG_PREFERRED_BACKUP);
21209            serializer.endDocument();
21210            serializer.flush();
21211        } catch (Exception e) {
21212            if (DEBUG_BACKUP) {
21213                Slog.e(TAG, "Unable to write preferred activities for backup", e);
21214            }
21215            return null;
21216        }
21217
21218        return dataStream.toByteArray();
21219    }
21220
21221    @Override
21222    public void restorePreferredActivities(byte[] backup, int userId) {
21223        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21224            throw new SecurityException("Only the system may call restorePreferredActivities()");
21225        }
21226
21227        try {
21228            final XmlPullParser parser = Xml.newPullParser();
21229            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21230            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
21231                    new BlobXmlRestorer() {
21232                        @Override
21233                        public void apply(XmlPullParser parser, int userId)
21234                                throws XmlPullParserException, IOException {
21235                            synchronized (mPackages) {
21236                                mSettings.readPreferredActivitiesLPw(parser, userId);
21237                            }
21238                        }
21239                    } );
21240        } catch (Exception e) {
21241            if (DEBUG_BACKUP) {
21242                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21243            }
21244        }
21245    }
21246
21247    /**
21248     * Non-Binder method, support for the backup/restore mechanism: write the
21249     * default browser (etc) settings in its canonical XML format.  Returns the default
21250     * browser XML representation as a byte array, or null if there is none.
21251     */
21252    @Override
21253    public byte[] getDefaultAppsBackup(int userId) {
21254        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21255            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21256        }
21257
21258        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21259        try {
21260            final XmlSerializer serializer = new FastXmlSerializer();
21261            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21262            serializer.startDocument(null, true);
21263            serializer.startTag(null, TAG_DEFAULT_APPS);
21264
21265            synchronized (mPackages) {
21266                mSettings.writeDefaultAppsLPr(serializer, userId);
21267            }
21268
21269            serializer.endTag(null, TAG_DEFAULT_APPS);
21270            serializer.endDocument();
21271            serializer.flush();
21272        } catch (Exception e) {
21273            if (DEBUG_BACKUP) {
21274                Slog.e(TAG, "Unable to write default apps for backup", e);
21275            }
21276            return null;
21277        }
21278
21279        return dataStream.toByteArray();
21280    }
21281
21282    @Override
21283    public void restoreDefaultApps(byte[] backup, int userId) {
21284        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21285            throw new SecurityException("Only the system may call restoreDefaultApps()");
21286        }
21287
21288        try {
21289            final XmlPullParser parser = Xml.newPullParser();
21290            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21291            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21292                    new BlobXmlRestorer() {
21293                        @Override
21294                        public void apply(XmlPullParser parser, int userId)
21295                                throws XmlPullParserException, IOException {
21296                            synchronized (mPackages) {
21297                                mSettings.readDefaultAppsLPw(parser, userId);
21298                            }
21299                        }
21300                    } );
21301        } catch (Exception e) {
21302            if (DEBUG_BACKUP) {
21303                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21304            }
21305        }
21306    }
21307
21308    @Override
21309    public byte[] getIntentFilterVerificationBackup(int userId) {
21310        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21311            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21312        }
21313
21314        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21315        try {
21316            final XmlSerializer serializer = new FastXmlSerializer();
21317            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21318            serializer.startDocument(null, true);
21319            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21320
21321            synchronized (mPackages) {
21322                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21323            }
21324
21325            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21326            serializer.endDocument();
21327            serializer.flush();
21328        } catch (Exception e) {
21329            if (DEBUG_BACKUP) {
21330                Slog.e(TAG, "Unable to write default apps for backup", e);
21331            }
21332            return null;
21333        }
21334
21335        return dataStream.toByteArray();
21336    }
21337
21338    @Override
21339    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21340        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21341            throw new SecurityException("Only the system may call restorePreferredActivities()");
21342        }
21343
21344        try {
21345            final XmlPullParser parser = Xml.newPullParser();
21346            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21347            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21348                    new BlobXmlRestorer() {
21349                        @Override
21350                        public void apply(XmlPullParser parser, int userId)
21351                                throws XmlPullParserException, IOException {
21352                            synchronized (mPackages) {
21353                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21354                                mSettings.writeLPr();
21355                            }
21356                        }
21357                    } );
21358        } catch (Exception e) {
21359            if (DEBUG_BACKUP) {
21360                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21361            }
21362        }
21363    }
21364
21365    @Override
21366    public byte[] getPermissionGrantBackup(int userId) {
21367        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21368            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21369        }
21370
21371        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21372        try {
21373            final XmlSerializer serializer = new FastXmlSerializer();
21374            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21375            serializer.startDocument(null, true);
21376            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21377
21378            synchronized (mPackages) {
21379                serializeRuntimePermissionGrantsLPr(serializer, userId);
21380            }
21381
21382            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21383            serializer.endDocument();
21384            serializer.flush();
21385        } catch (Exception e) {
21386            if (DEBUG_BACKUP) {
21387                Slog.e(TAG, "Unable to write default apps for backup", e);
21388            }
21389            return null;
21390        }
21391
21392        return dataStream.toByteArray();
21393    }
21394
21395    @Override
21396    public void restorePermissionGrants(byte[] backup, int userId) {
21397        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21398            throw new SecurityException("Only the system may call restorePermissionGrants()");
21399        }
21400
21401        try {
21402            final XmlPullParser parser = Xml.newPullParser();
21403            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21404            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21405                    new BlobXmlRestorer() {
21406                        @Override
21407                        public void apply(XmlPullParser parser, int userId)
21408                                throws XmlPullParserException, IOException {
21409                            synchronized (mPackages) {
21410                                processRestoredPermissionGrantsLPr(parser, userId);
21411                            }
21412                        }
21413                    } );
21414        } catch (Exception e) {
21415            if (DEBUG_BACKUP) {
21416                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21417            }
21418        }
21419    }
21420
21421    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21422            throws IOException {
21423        serializer.startTag(null, TAG_ALL_GRANTS);
21424
21425        final int N = mSettings.mPackages.size();
21426        for (int i = 0; i < N; i++) {
21427            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21428            boolean pkgGrantsKnown = false;
21429
21430            PermissionsState packagePerms = ps.getPermissionsState();
21431
21432            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21433                final int grantFlags = state.getFlags();
21434                // only look at grants that are not system/policy fixed
21435                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21436                    final boolean isGranted = state.isGranted();
21437                    // And only back up the user-twiddled state bits
21438                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21439                        final String packageName = mSettings.mPackages.keyAt(i);
21440                        if (!pkgGrantsKnown) {
21441                            serializer.startTag(null, TAG_GRANT);
21442                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21443                            pkgGrantsKnown = true;
21444                        }
21445
21446                        final boolean userSet =
21447                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21448                        final boolean userFixed =
21449                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21450                        final boolean revoke =
21451                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21452
21453                        serializer.startTag(null, TAG_PERMISSION);
21454                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21455                        if (isGranted) {
21456                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21457                        }
21458                        if (userSet) {
21459                            serializer.attribute(null, ATTR_USER_SET, "true");
21460                        }
21461                        if (userFixed) {
21462                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21463                        }
21464                        if (revoke) {
21465                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21466                        }
21467                        serializer.endTag(null, TAG_PERMISSION);
21468                    }
21469                }
21470            }
21471
21472            if (pkgGrantsKnown) {
21473                serializer.endTag(null, TAG_GRANT);
21474            }
21475        }
21476
21477        serializer.endTag(null, TAG_ALL_GRANTS);
21478    }
21479
21480    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21481            throws XmlPullParserException, IOException {
21482        String pkgName = null;
21483        int outerDepth = parser.getDepth();
21484        int type;
21485        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21486                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21487            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21488                continue;
21489            }
21490
21491            final String tagName = parser.getName();
21492            if (tagName.equals(TAG_GRANT)) {
21493                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21494                if (DEBUG_BACKUP) {
21495                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21496                }
21497            } else if (tagName.equals(TAG_PERMISSION)) {
21498
21499                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21500                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21501
21502                int newFlagSet = 0;
21503                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21504                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21505                }
21506                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21507                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21508                }
21509                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21510                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21511                }
21512                if (DEBUG_BACKUP) {
21513                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21514                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21515                }
21516                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21517                if (ps != null) {
21518                    // Already installed so we apply the grant immediately
21519                    if (DEBUG_BACKUP) {
21520                        Slog.v(TAG, "        + already installed; applying");
21521                    }
21522                    PermissionsState perms = ps.getPermissionsState();
21523                    BasePermission bp = mSettings.mPermissions.get(permName);
21524                    if (bp != null) {
21525                        if (isGranted) {
21526                            perms.grantRuntimePermission(bp, userId);
21527                        }
21528                        if (newFlagSet != 0) {
21529                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21530                        }
21531                    }
21532                } else {
21533                    // Need to wait for post-restore install to apply the grant
21534                    if (DEBUG_BACKUP) {
21535                        Slog.v(TAG, "        - not yet installed; saving for later");
21536                    }
21537                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21538                            isGranted, newFlagSet, userId);
21539                }
21540            } else {
21541                PackageManagerService.reportSettingsProblem(Log.WARN,
21542                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21543                XmlUtils.skipCurrentTag(parser);
21544            }
21545        }
21546
21547        scheduleWriteSettingsLocked();
21548        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21549    }
21550
21551    @Override
21552    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21553            int sourceUserId, int targetUserId, int flags) {
21554        mContext.enforceCallingOrSelfPermission(
21555                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21556        int callingUid = Binder.getCallingUid();
21557        enforceOwnerRights(ownerPackage, callingUid);
21558        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21559        if (intentFilter.countActions() == 0) {
21560            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21561            return;
21562        }
21563        synchronized (mPackages) {
21564            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21565                    ownerPackage, targetUserId, flags);
21566            CrossProfileIntentResolver resolver =
21567                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21568            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21569            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21570            if (existing != null) {
21571                int size = existing.size();
21572                for (int i = 0; i < size; i++) {
21573                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21574                        return;
21575                    }
21576                }
21577            }
21578            resolver.addFilter(newFilter);
21579            scheduleWritePackageRestrictionsLocked(sourceUserId);
21580        }
21581    }
21582
21583    @Override
21584    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21585        mContext.enforceCallingOrSelfPermission(
21586                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21587        final int callingUid = Binder.getCallingUid();
21588        enforceOwnerRights(ownerPackage, callingUid);
21589        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21590        synchronized (mPackages) {
21591            CrossProfileIntentResolver resolver =
21592                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21593            ArraySet<CrossProfileIntentFilter> set =
21594                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21595            for (CrossProfileIntentFilter filter : set) {
21596                if (filter.getOwnerPackage().equals(ownerPackage)) {
21597                    resolver.removeFilter(filter);
21598                }
21599            }
21600            scheduleWritePackageRestrictionsLocked(sourceUserId);
21601        }
21602    }
21603
21604    // Enforcing that callingUid is owning pkg on userId
21605    private void enforceOwnerRights(String pkg, int callingUid) {
21606        // The system owns everything.
21607        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21608            return;
21609        }
21610        final int callingUserId = UserHandle.getUserId(callingUid);
21611        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21612        if (pi == null) {
21613            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21614                    + callingUserId);
21615        }
21616        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21617            throw new SecurityException("Calling uid " + callingUid
21618                    + " does not own package " + pkg);
21619        }
21620    }
21621
21622    @Override
21623    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21624        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21625            return null;
21626        }
21627        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21628    }
21629
21630    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21631        UserManagerService ums = UserManagerService.getInstance();
21632        if (ums != null) {
21633            final UserInfo parent = ums.getProfileParent(userId);
21634            final int launcherUid = (parent != null) ? parent.id : userId;
21635            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21636            if (launcherComponent != null) {
21637                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21638                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21639                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21640                        .setPackage(launcherComponent.getPackageName());
21641                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21642            }
21643        }
21644    }
21645
21646    /**
21647     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21648     * then reports the most likely home activity or null if there are more than one.
21649     */
21650    private ComponentName getDefaultHomeActivity(int userId) {
21651        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21652        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21653        if (cn != null) {
21654            return cn;
21655        }
21656
21657        // Find the launcher with the highest priority and return that component if there are no
21658        // other home activity with the same priority.
21659        int lastPriority = Integer.MIN_VALUE;
21660        ComponentName lastComponent = null;
21661        final int size = allHomeCandidates.size();
21662        for (int i = 0; i < size; i++) {
21663            final ResolveInfo ri = allHomeCandidates.get(i);
21664            if (ri.priority > lastPriority) {
21665                lastComponent = ri.activityInfo.getComponentName();
21666                lastPriority = ri.priority;
21667            } else if (ri.priority == lastPriority) {
21668                // Two components found with same priority.
21669                lastComponent = null;
21670            }
21671        }
21672        return lastComponent;
21673    }
21674
21675    private Intent getHomeIntent() {
21676        Intent intent = new Intent(Intent.ACTION_MAIN);
21677        intent.addCategory(Intent.CATEGORY_HOME);
21678        intent.addCategory(Intent.CATEGORY_DEFAULT);
21679        return intent;
21680    }
21681
21682    private IntentFilter getHomeFilter() {
21683        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21684        filter.addCategory(Intent.CATEGORY_HOME);
21685        filter.addCategory(Intent.CATEGORY_DEFAULT);
21686        return filter;
21687    }
21688
21689    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21690            int userId) {
21691        Intent intent  = getHomeIntent();
21692        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21693                PackageManager.GET_META_DATA, userId);
21694        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21695                true, false, false, userId);
21696
21697        allHomeCandidates.clear();
21698        if (list != null) {
21699            for (ResolveInfo ri : list) {
21700                allHomeCandidates.add(ri);
21701            }
21702        }
21703        return (preferred == null || preferred.activityInfo == null)
21704                ? null
21705                : new ComponentName(preferred.activityInfo.packageName,
21706                        preferred.activityInfo.name);
21707    }
21708
21709    @Override
21710    public void setHomeActivity(ComponentName comp, int userId) {
21711        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21712            return;
21713        }
21714        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21715        getHomeActivitiesAsUser(homeActivities, userId);
21716
21717        boolean found = false;
21718
21719        final int size = homeActivities.size();
21720        final ComponentName[] set = new ComponentName[size];
21721        for (int i = 0; i < size; i++) {
21722            final ResolveInfo candidate = homeActivities.get(i);
21723            final ActivityInfo info = candidate.activityInfo;
21724            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21725            set[i] = activityName;
21726            if (!found && activityName.equals(comp)) {
21727                found = true;
21728            }
21729        }
21730        if (!found) {
21731            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21732                    + userId);
21733        }
21734        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21735                set, comp, userId);
21736    }
21737
21738    private @Nullable String getSetupWizardPackageName() {
21739        final Intent intent = new Intent(Intent.ACTION_MAIN);
21740        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21741
21742        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21743                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21744                        | MATCH_DISABLED_COMPONENTS,
21745                UserHandle.myUserId());
21746        if (matches.size() == 1) {
21747            return matches.get(0).getComponentInfo().packageName;
21748        } else {
21749            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21750                    + ": matches=" + matches);
21751            return null;
21752        }
21753    }
21754
21755    private @Nullable String getStorageManagerPackageName() {
21756        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21757
21758        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21759                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21760                        | MATCH_DISABLED_COMPONENTS,
21761                UserHandle.myUserId());
21762        if (matches.size() == 1) {
21763            return matches.get(0).getComponentInfo().packageName;
21764        } else {
21765            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21766                    + matches.size() + ": matches=" + matches);
21767            return null;
21768        }
21769    }
21770
21771    @Override
21772    public void setApplicationEnabledSetting(String appPackageName,
21773            int newState, int flags, int userId, String callingPackage) {
21774        if (!sUserManager.exists(userId)) return;
21775        if (callingPackage == null) {
21776            callingPackage = Integer.toString(Binder.getCallingUid());
21777        }
21778        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21779    }
21780
21781    @Override
21782    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21783        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21784        synchronized (mPackages) {
21785            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21786            if (pkgSetting != null) {
21787                pkgSetting.setUpdateAvailable(updateAvailable);
21788            }
21789        }
21790    }
21791
21792    @Override
21793    public void setComponentEnabledSetting(ComponentName componentName,
21794            int newState, int flags, int userId) {
21795        if (!sUserManager.exists(userId)) return;
21796        setEnabledSetting(componentName.getPackageName(),
21797                componentName.getClassName(), newState, flags, userId, null);
21798    }
21799
21800    private void setEnabledSetting(final String packageName, String className, int newState,
21801            final int flags, int userId, String callingPackage) {
21802        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21803              || newState == COMPONENT_ENABLED_STATE_ENABLED
21804              || newState == COMPONENT_ENABLED_STATE_DISABLED
21805              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21806              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21807            throw new IllegalArgumentException("Invalid new component state: "
21808                    + newState);
21809        }
21810        PackageSetting pkgSetting;
21811        final int callingUid = Binder.getCallingUid();
21812        final int permission;
21813        if (callingUid == Process.SYSTEM_UID) {
21814            permission = PackageManager.PERMISSION_GRANTED;
21815        } else {
21816            permission = mContext.checkCallingOrSelfPermission(
21817                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21818        }
21819        enforceCrossUserPermission(callingUid, userId,
21820                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21821        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21822        boolean sendNow = false;
21823        boolean isApp = (className == null);
21824        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21825        String componentName = isApp ? packageName : className;
21826        int packageUid = -1;
21827        ArrayList<String> components;
21828
21829        // reader
21830        synchronized (mPackages) {
21831            pkgSetting = mSettings.mPackages.get(packageName);
21832            if (pkgSetting == null) {
21833                if (!isCallerInstantApp) {
21834                    if (className == null) {
21835                        throw new IllegalArgumentException("Unknown package: " + packageName);
21836                    }
21837                    throw new IllegalArgumentException(
21838                            "Unknown component: " + packageName + "/" + className);
21839                } else {
21840                    // throw SecurityException to prevent leaking package information
21841                    throw new SecurityException(
21842                            "Attempt to change component state; "
21843                            + "pid=" + Binder.getCallingPid()
21844                            + ", uid=" + callingUid
21845                            + (className == null
21846                                    ? ", package=" + packageName
21847                                    : ", component=" + packageName + "/" + className));
21848                }
21849            }
21850        }
21851
21852        // Limit who can change which apps
21853        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21854            // Don't allow apps that don't have permission to modify other apps
21855            if (!allowedByPermission
21856                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21857                throw new SecurityException(
21858                        "Attempt to change component state; "
21859                        + "pid=" + Binder.getCallingPid()
21860                        + ", uid=" + callingUid
21861                        + (className == null
21862                                ? ", package=" + packageName
21863                                : ", component=" + packageName + "/" + className));
21864            }
21865            // Don't allow changing protected packages.
21866            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21867                throw new SecurityException("Cannot disable a protected package: " + packageName);
21868            }
21869        }
21870
21871        synchronized (mPackages) {
21872            if (callingUid == Process.SHELL_UID
21873                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21874                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21875                // unless it is a test package.
21876                int oldState = pkgSetting.getEnabled(userId);
21877                if (className == null
21878                        &&
21879                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21880                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21881                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21882                        &&
21883                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21884                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
21885                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21886                    // ok
21887                } else {
21888                    throw new SecurityException(
21889                            "Shell cannot change component state for " + packageName + "/"
21890                                    + className + " to " + newState);
21891                }
21892            }
21893        }
21894        if (className == null) {
21895            // We're dealing with an application/package level state change
21896            synchronized (mPackages) {
21897                if (pkgSetting.getEnabled(userId) == newState) {
21898                    // Nothing to do
21899                    return;
21900                }
21901            }
21902            // If we're enabling a system stub, there's a little more work to do.
21903            // Prior to enabling the package, we need to decompress the APK(s) to the
21904            // data partition and then replace the version on the system partition.
21905            final PackageParser.Package deletedPkg = pkgSetting.pkg;
21906            final boolean isSystemStub = deletedPkg.isStub
21907                    && deletedPkg.isSystemApp();
21908            if (isSystemStub
21909                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21910                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
21911                final File codePath = decompressPackage(deletedPkg);
21912                if (codePath == null) {
21913                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
21914                    return;
21915                }
21916                // TODO remove direct parsing of the package object during internal cleanup
21917                // of scan package
21918                // We need to call parse directly here for no other reason than we need
21919                // the new package in order to disable the old one [we use the information
21920                // for some internal optimization to optionally create a new package setting
21921                // object on replace]. However, we can't get the package from the scan
21922                // because the scan modifies live structures and we need to remove the
21923                // old [system] package from the system before a scan can be attempted.
21924                // Once scan is indempotent we can remove this parse and use the package
21925                // object we scanned, prior to adding it to package settings.
21926                final PackageParser pp = new PackageParser();
21927                pp.setSeparateProcesses(mSeparateProcesses);
21928                pp.setDisplayMetrics(mMetrics);
21929                pp.setCallback(mPackageParserCallback);
21930                final PackageParser.Package tmpPkg;
21931                try {
21932                    final int parseFlags = mDefParseFlags
21933                            | PackageParser.PARSE_MUST_BE_APK
21934                            | PackageParser.PARSE_IS_SYSTEM
21935                            | PackageParser.PARSE_IS_SYSTEM_DIR;
21936                    tmpPkg = pp.parsePackage(codePath, parseFlags);
21937                } catch (PackageParserException e) {
21938                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
21939                    return;
21940                }
21941                synchronized (mInstallLock) {
21942                    // Disable the stub and remove any package entries
21943                    removePackageLI(deletedPkg, true);
21944                    synchronized (mPackages) {
21945                        disableSystemPackageLPw(deletedPkg, tmpPkg);
21946                    }
21947                    final PackageParser.Package newPkg;
21948                    try (PackageFreezer freezer =
21949                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21950                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
21951                                | PackageParser.PARSE_ENFORCE_CODE;
21952                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
21953                                0 /*currentTime*/, null /*user*/);
21954                        prepareAppDataAfterInstallLIF(newPkg);
21955                        synchronized (mPackages) {
21956                            try {
21957                                updateSharedLibrariesLPr(newPkg, null);
21958                            } catch (PackageManagerException e) {
21959                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
21960                            }
21961                            updatePermissionsLPw(newPkg.packageName, newPkg,
21962                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
21963                            mSettings.writeLPr();
21964                        }
21965                    } catch (PackageManagerException e) {
21966                        // Whoops! Something went wrong; try to roll back to the stub
21967                        Slog.w(TAG, "Failed to install compressed system package:"
21968                                + pkgSetting.name, e);
21969                        // Remove the failed install
21970                        removeCodePathLI(codePath);
21971
21972                        // Install the system package
21973                        try (PackageFreezer freezer =
21974                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21975                            synchronized (mPackages) {
21976                                // NOTE: The system package always needs to be enabled; even
21977                                // if it's for a compressed stub. If we don't, installing the
21978                                // system package fails during scan [scanning checks the disabled
21979                                // packages]. We will reverse this later, after we've "installed"
21980                                // the stub.
21981                                // This leaves us in a fragile state; the stub should never be
21982                                // enabled, so, cross your fingers and hope nothing goes wrong
21983                                // until we can disable the package later.
21984                                enableSystemPackageLPw(deletedPkg);
21985                            }
21986                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
21987                                    false /*isPrivileged*/, null /*allUserHandles*/,
21988                                    null /*origUserHandles*/, null /*origPermissionsState*/,
21989                                    true /*writeSettings*/);
21990                        } catch (PackageManagerException pme) {
21991                            Slog.w(TAG, "Failed to restore system package:"
21992                                    + deletedPkg.packageName, pme);
21993                        } finally {
21994                            synchronized (mPackages) {
21995                                mSettings.disableSystemPackageLPw(
21996                                        deletedPkg.packageName, true /*replaced*/);
21997                                mSettings.writeLPr();
21998                            }
21999                        }
22000                        return;
22001                    }
22002                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
22003                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22004                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
22005                    mDexManager.notifyPackageUpdated(newPkg.packageName,
22006                            newPkg.baseCodePath, newPkg.splitCodePaths);
22007                }
22008            }
22009            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
22010                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
22011                // Don't care about who enables an app.
22012                callingPackage = null;
22013            }
22014            synchronized (mPackages) {
22015                pkgSetting.setEnabled(newState, userId, callingPackage);
22016            }
22017        } else {
22018            synchronized (mPackages) {
22019                // We're dealing with a component level state change
22020                // First, verify that this is a valid class name.
22021                PackageParser.Package pkg = pkgSetting.pkg;
22022                if (pkg == null || !pkg.hasComponentClassName(className)) {
22023                    if (pkg != null &&
22024                            pkg.applicationInfo.targetSdkVersion >=
22025                                    Build.VERSION_CODES.JELLY_BEAN) {
22026                        throw new IllegalArgumentException("Component class " + className
22027                                + " does not exist in " + packageName);
22028                    } else {
22029                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
22030                                + className + " does not exist in " + packageName);
22031                    }
22032                }
22033                switch (newState) {
22034                    case COMPONENT_ENABLED_STATE_ENABLED:
22035                        if (!pkgSetting.enableComponentLPw(className, userId)) {
22036                            return;
22037                        }
22038                        break;
22039                    case COMPONENT_ENABLED_STATE_DISABLED:
22040                        if (!pkgSetting.disableComponentLPw(className, userId)) {
22041                            return;
22042                        }
22043                        break;
22044                    case COMPONENT_ENABLED_STATE_DEFAULT:
22045                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
22046                            return;
22047                        }
22048                        break;
22049                    default:
22050                        Slog.e(TAG, "Invalid new component state: " + newState);
22051                        return;
22052                }
22053            }
22054        }
22055        synchronized (mPackages) {
22056            scheduleWritePackageRestrictionsLocked(userId);
22057            updateSequenceNumberLP(pkgSetting, new int[] { userId });
22058            final long callingId = Binder.clearCallingIdentity();
22059            try {
22060                updateInstantAppInstallerLocked(packageName);
22061            } finally {
22062                Binder.restoreCallingIdentity(callingId);
22063            }
22064            components = mPendingBroadcasts.get(userId, packageName);
22065            final boolean newPackage = components == null;
22066            if (newPackage) {
22067                components = new ArrayList<String>();
22068            }
22069            if (!components.contains(componentName)) {
22070                components.add(componentName);
22071            }
22072            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
22073                sendNow = true;
22074                // Purge entry from pending broadcast list if another one exists already
22075                // since we are sending one right away.
22076                mPendingBroadcasts.remove(userId, packageName);
22077            } else {
22078                if (newPackage) {
22079                    mPendingBroadcasts.put(userId, packageName, components);
22080                }
22081                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
22082                    // Schedule a message
22083                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
22084                }
22085            }
22086        }
22087
22088        long callingId = Binder.clearCallingIdentity();
22089        try {
22090            if (sendNow) {
22091                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
22092                sendPackageChangedBroadcast(packageName,
22093                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
22094            }
22095        } finally {
22096            Binder.restoreCallingIdentity(callingId);
22097        }
22098    }
22099
22100    @Override
22101    public void flushPackageRestrictionsAsUser(int userId) {
22102        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22103            return;
22104        }
22105        if (!sUserManager.exists(userId)) {
22106            return;
22107        }
22108        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
22109                false /* checkShell */, "flushPackageRestrictions");
22110        synchronized (mPackages) {
22111            mSettings.writePackageRestrictionsLPr(userId);
22112            mDirtyUsers.remove(userId);
22113            if (mDirtyUsers.isEmpty()) {
22114                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
22115            }
22116        }
22117    }
22118
22119    private void sendPackageChangedBroadcast(String packageName,
22120            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
22121        if (DEBUG_INSTALL)
22122            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
22123                    + componentNames);
22124        Bundle extras = new Bundle(4);
22125        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
22126        String nameList[] = new String[componentNames.size()];
22127        componentNames.toArray(nameList);
22128        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
22129        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
22130        extras.putInt(Intent.EXTRA_UID, packageUid);
22131        // If this is not reporting a change of the overall package, then only send it
22132        // to registered receivers.  We don't want to launch a swath of apps for every
22133        // little component state change.
22134        final int flags = !componentNames.contains(packageName)
22135                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
22136        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
22137                new int[] {UserHandle.getUserId(packageUid)});
22138    }
22139
22140    @Override
22141    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
22142        if (!sUserManager.exists(userId)) return;
22143        final int callingUid = Binder.getCallingUid();
22144        if (getInstantAppPackageName(callingUid) != null) {
22145            return;
22146        }
22147        final int permission = mContext.checkCallingOrSelfPermission(
22148                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
22149        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
22150        enforceCrossUserPermission(callingUid, userId,
22151                true /* requireFullPermission */, true /* checkShell */, "stop package");
22152        // writer
22153        synchronized (mPackages) {
22154            final PackageSetting ps = mSettings.mPackages.get(packageName);
22155            if (!filterAppAccessLPr(ps, callingUid, userId)
22156                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
22157                            allowedByPermission, callingUid, userId)) {
22158                scheduleWritePackageRestrictionsLocked(userId);
22159            }
22160        }
22161    }
22162
22163    @Override
22164    public String getInstallerPackageName(String packageName) {
22165        final int callingUid = Binder.getCallingUid();
22166        if (getInstantAppPackageName(callingUid) != null) {
22167            return null;
22168        }
22169        // reader
22170        synchronized (mPackages) {
22171            final PackageSetting ps = mSettings.mPackages.get(packageName);
22172            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
22173                return null;
22174            }
22175            return mSettings.getInstallerPackageNameLPr(packageName);
22176        }
22177    }
22178
22179    public boolean isOrphaned(String packageName) {
22180        // reader
22181        synchronized (mPackages) {
22182            return mSettings.isOrphaned(packageName);
22183        }
22184    }
22185
22186    @Override
22187    public int getApplicationEnabledSetting(String packageName, int userId) {
22188        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22189        int callingUid = Binder.getCallingUid();
22190        enforceCrossUserPermission(callingUid, userId,
22191                false /* requireFullPermission */, false /* checkShell */, "get enabled");
22192        // reader
22193        synchronized (mPackages) {
22194            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
22195                return COMPONENT_ENABLED_STATE_DISABLED;
22196            }
22197            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
22198        }
22199    }
22200
22201    @Override
22202    public int getComponentEnabledSetting(ComponentName component, int userId) {
22203        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22204        int callingUid = Binder.getCallingUid();
22205        enforceCrossUserPermission(callingUid, userId,
22206                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
22207        synchronized (mPackages) {
22208            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
22209                    component, TYPE_UNKNOWN, userId)) {
22210                return COMPONENT_ENABLED_STATE_DISABLED;
22211            }
22212            return mSettings.getComponentEnabledSettingLPr(component, userId);
22213        }
22214    }
22215
22216    @Override
22217    public void enterSafeMode() {
22218        enforceSystemOrRoot("Only the system can request entering safe mode");
22219
22220        if (!mSystemReady) {
22221            mSafeMode = true;
22222        }
22223    }
22224
22225    @Override
22226    public void systemReady() {
22227        enforceSystemOrRoot("Only the system can claim the system is ready");
22228
22229        mSystemReady = true;
22230        final ContentResolver resolver = mContext.getContentResolver();
22231        ContentObserver co = new ContentObserver(mHandler) {
22232            @Override
22233            public void onChange(boolean selfChange) {
22234                mEphemeralAppsDisabled =
22235                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
22236                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
22237            }
22238        };
22239        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22240                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
22241                false, co, UserHandle.USER_SYSTEM);
22242        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22243                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
22244        co.onChange(true);
22245
22246        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
22247        // disabled after already being started.
22248        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
22249                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
22250
22251        // Read the compatibilty setting when the system is ready.
22252        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
22253                mContext.getContentResolver(),
22254                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
22255        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
22256        if (DEBUG_SETTINGS) {
22257            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
22258        }
22259
22260        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
22261
22262        synchronized (mPackages) {
22263            // Verify that all of the preferred activity components actually
22264            // exist.  It is possible for applications to be updated and at
22265            // that point remove a previously declared activity component that
22266            // had been set as a preferred activity.  We try to clean this up
22267            // the next time we encounter that preferred activity, but it is
22268            // possible for the user flow to never be able to return to that
22269            // situation so here we do a sanity check to make sure we haven't
22270            // left any junk around.
22271            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
22272            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22273                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22274                removed.clear();
22275                for (PreferredActivity pa : pir.filterSet()) {
22276                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
22277                        removed.add(pa);
22278                    }
22279                }
22280                if (removed.size() > 0) {
22281                    for (int r=0; r<removed.size(); r++) {
22282                        PreferredActivity pa = removed.get(r);
22283                        Slog.w(TAG, "Removing dangling preferred activity: "
22284                                + pa.mPref.mComponent);
22285                        pir.removeFilter(pa);
22286                    }
22287                    mSettings.writePackageRestrictionsLPr(
22288                            mSettings.mPreferredActivities.keyAt(i));
22289                }
22290            }
22291
22292            for (int userId : UserManagerService.getInstance().getUserIds()) {
22293                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
22294                    grantPermissionsUserIds = ArrayUtils.appendInt(
22295                            grantPermissionsUserIds, userId);
22296                }
22297            }
22298        }
22299        sUserManager.systemReady();
22300
22301        // If we upgraded grant all default permissions before kicking off.
22302        for (int userId : grantPermissionsUserIds) {
22303            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22304        }
22305
22306        // If we did not grant default permissions, we preload from this the
22307        // default permission exceptions lazily to ensure we don't hit the
22308        // disk on a new user creation.
22309        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
22310            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
22311        }
22312
22313        // Kick off any messages waiting for system ready
22314        if (mPostSystemReadyMessages != null) {
22315            for (Message msg : mPostSystemReadyMessages) {
22316                msg.sendToTarget();
22317            }
22318            mPostSystemReadyMessages = null;
22319        }
22320
22321        // Watch for external volumes that come and go over time
22322        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22323        storage.registerListener(mStorageListener);
22324
22325        mInstallerService.systemReady();
22326        mPackageDexOptimizer.systemReady();
22327
22328        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22329                StorageManagerInternal.class);
22330        StorageManagerInternal.addExternalStoragePolicy(
22331                new StorageManagerInternal.ExternalStorageMountPolicy() {
22332            @Override
22333            public int getMountMode(int uid, String packageName) {
22334                if (Process.isIsolated(uid)) {
22335                    return Zygote.MOUNT_EXTERNAL_NONE;
22336                }
22337                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22338                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22339                }
22340                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22341                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22342                }
22343                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22344                    return Zygote.MOUNT_EXTERNAL_READ;
22345                }
22346                return Zygote.MOUNT_EXTERNAL_WRITE;
22347            }
22348
22349            @Override
22350            public boolean hasExternalStorage(int uid, String packageName) {
22351                return true;
22352            }
22353        });
22354
22355        // Now that we're mostly running, clean up stale users and apps
22356        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22357        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22358
22359        if (mPrivappPermissionsViolations != null) {
22360            Slog.wtf(TAG,"Signature|privileged permissions not in "
22361                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22362            mPrivappPermissionsViolations = null;
22363        }
22364    }
22365
22366    public void waitForAppDataPrepared() {
22367        if (mPrepareAppDataFuture == null) {
22368            return;
22369        }
22370        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22371        mPrepareAppDataFuture = null;
22372    }
22373
22374    @Override
22375    public boolean isSafeMode() {
22376        // allow instant applications
22377        return mSafeMode;
22378    }
22379
22380    @Override
22381    public boolean hasSystemUidErrors() {
22382        // allow instant applications
22383        return mHasSystemUidErrors;
22384    }
22385
22386    static String arrayToString(int[] array) {
22387        StringBuffer buf = new StringBuffer(128);
22388        buf.append('[');
22389        if (array != null) {
22390            for (int i=0; i<array.length; i++) {
22391                if (i > 0) buf.append(", ");
22392                buf.append(array[i]);
22393            }
22394        }
22395        buf.append(']');
22396        return buf.toString();
22397    }
22398
22399    static class DumpState {
22400        public static final int DUMP_LIBS = 1 << 0;
22401        public static final int DUMP_FEATURES = 1 << 1;
22402        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22403        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22404        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22405        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22406        public static final int DUMP_PERMISSIONS = 1 << 6;
22407        public static final int DUMP_PACKAGES = 1 << 7;
22408        public static final int DUMP_SHARED_USERS = 1 << 8;
22409        public static final int DUMP_MESSAGES = 1 << 9;
22410        public static final int DUMP_PROVIDERS = 1 << 10;
22411        public static final int DUMP_VERIFIERS = 1 << 11;
22412        public static final int DUMP_PREFERRED = 1 << 12;
22413        public static final int DUMP_PREFERRED_XML = 1 << 13;
22414        public static final int DUMP_KEYSETS = 1 << 14;
22415        public static final int DUMP_VERSION = 1 << 15;
22416        public static final int DUMP_INSTALLS = 1 << 16;
22417        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22418        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22419        public static final int DUMP_FROZEN = 1 << 19;
22420        public static final int DUMP_DEXOPT = 1 << 20;
22421        public static final int DUMP_COMPILER_STATS = 1 << 21;
22422        public static final int DUMP_CHANGES = 1 << 22;
22423        public static final int DUMP_VOLUMES = 1 << 23;
22424
22425        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22426
22427        private int mTypes;
22428
22429        private int mOptions;
22430
22431        private boolean mTitlePrinted;
22432
22433        private SharedUserSetting mSharedUser;
22434
22435        public boolean isDumping(int type) {
22436            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22437                return true;
22438            }
22439
22440            return (mTypes & type) != 0;
22441        }
22442
22443        public void setDump(int type) {
22444            mTypes |= type;
22445        }
22446
22447        public boolean isOptionEnabled(int option) {
22448            return (mOptions & option) != 0;
22449        }
22450
22451        public void setOptionEnabled(int option) {
22452            mOptions |= option;
22453        }
22454
22455        public boolean onTitlePrinted() {
22456            final boolean printed = mTitlePrinted;
22457            mTitlePrinted = true;
22458            return printed;
22459        }
22460
22461        public boolean getTitlePrinted() {
22462            return mTitlePrinted;
22463        }
22464
22465        public void setTitlePrinted(boolean enabled) {
22466            mTitlePrinted = enabled;
22467        }
22468
22469        public SharedUserSetting getSharedUser() {
22470            return mSharedUser;
22471        }
22472
22473        public void setSharedUser(SharedUserSetting user) {
22474            mSharedUser = user;
22475        }
22476    }
22477
22478    @Override
22479    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22480            FileDescriptor err, String[] args, ShellCallback callback,
22481            ResultReceiver resultReceiver) {
22482        (new PackageManagerShellCommand(this)).exec(
22483                this, in, out, err, args, callback, resultReceiver);
22484    }
22485
22486    @Override
22487    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22488        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22489
22490        DumpState dumpState = new DumpState();
22491        boolean fullPreferred = false;
22492        boolean checkin = false;
22493
22494        String packageName = null;
22495        ArraySet<String> permissionNames = null;
22496
22497        int opti = 0;
22498        while (opti < args.length) {
22499            String opt = args[opti];
22500            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22501                break;
22502            }
22503            opti++;
22504
22505            if ("-a".equals(opt)) {
22506                // Right now we only know how to print all.
22507            } else if ("-h".equals(opt)) {
22508                pw.println("Package manager dump options:");
22509                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22510                pw.println("    --checkin: dump for a checkin");
22511                pw.println("    -f: print details of intent filters");
22512                pw.println("    -h: print this help");
22513                pw.println("  cmd may be one of:");
22514                pw.println("    l[ibraries]: list known shared libraries");
22515                pw.println("    f[eatures]: list device features");
22516                pw.println("    k[eysets]: print known keysets");
22517                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22518                pw.println("    perm[issions]: dump permissions");
22519                pw.println("    permission [name ...]: dump declaration and use of given permission");
22520                pw.println("    pref[erred]: print preferred package settings");
22521                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22522                pw.println("    prov[iders]: dump content providers");
22523                pw.println("    p[ackages]: dump installed packages");
22524                pw.println("    s[hared-users]: dump shared user IDs");
22525                pw.println("    m[essages]: print collected runtime messages");
22526                pw.println("    v[erifiers]: print package verifier info");
22527                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22528                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22529                pw.println("    version: print database version info");
22530                pw.println("    write: write current settings now");
22531                pw.println("    installs: details about install sessions");
22532                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22533                pw.println("    dexopt: dump dexopt state");
22534                pw.println("    compiler-stats: dump compiler statistics");
22535                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22536                pw.println("    <package.name>: info about given package");
22537                return;
22538            } else if ("--checkin".equals(opt)) {
22539                checkin = true;
22540            } else if ("-f".equals(opt)) {
22541                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22542            } else if ("--proto".equals(opt)) {
22543                dumpProto(fd);
22544                return;
22545            } else {
22546                pw.println("Unknown argument: " + opt + "; use -h for help");
22547            }
22548        }
22549
22550        // Is the caller requesting to dump a particular piece of data?
22551        if (opti < args.length) {
22552            String cmd = args[opti];
22553            opti++;
22554            // Is this a package name?
22555            if ("android".equals(cmd) || cmd.contains(".")) {
22556                packageName = cmd;
22557                // When dumping a single package, we always dump all of its
22558                // filter information since the amount of data will be reasonable.
22559                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22560            } else if ("check-permission".equals(cmd)) {
22561                if (opti >= args.length) {
22562                    pw.println("Error: check-permission missing permission argument");
22563                    return;
22564                }
22565                String perm = args[opti];
22566                opti++;
22567                if (opti >= args.length) {
22568                    pw.println("Error: check-permission missing package argument");
22569                    return;
22570                }
22571
22572                String pkg = args[opti];
22573                opti++;
22574                int user = UserHandle.getUserId(Binder.getCallingUid());
22575                if (opti < args.length) {
22576                    try {
22577                        user = Integer.parseInt(args[opti]);
22578                    } catch (NumberFormatException e) {
22579                        pw.println("Error: check-permission user argument is not a number: "
22580                                + args[opti]);
22581                        return;
22582                    }
22583                }
22584
22585                // Normalize package name to handle renamed packages and static libs
22586                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22587
22588                pw.println(checkPermission(perm, pkg, user));
22589                return;
22590            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22591                dumpState.setDump(DumpState.DUMP_LIBS);
22592            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22593                dumpState.setDump(DumpState.DUMP_FEATURES);
22594            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22595                if (opti >= args.length) {
22596                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22597                            | DumpState.DUMP_SERVICE_RESOLVERS
22598                            | DumpState.DUMP_RECEIVER_RESOLVERS
22599                            | DumpState.DUMP_CONTENT_RESOLVERS);
22600                } else {
22601                    while (opti < args.length) {
22602                        String name = args[opti];
22603                        if ("a".equals(name) || "activity".equals(name)) {
22604                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22605                        } else if ("s".equals(name) || "service".equals(name)) {
22606                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22607                        } else if ("r".equals(name) || "receiver".equals(name)) {
22608                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22609                        } else if ("c".equals(name) || "content".equals(name)) {
22610                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22611                        } else {
22612                            pw.println("Error: unknown resolver table type: " + name);
22613                            return;
22614                        }
22615                        opti++;
22616                    }
22617                }
22618            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22619                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22620            } else if ("permission".equals(cmd)) {
22621                if (opti >= args.length) {
22622                    pw.println("Error: permission requires permission name");
22623                    return;
22624                }
22625                permissionNames = new ArraySet<>();
22626                while (opti < args.length) {
22627                    permissionNames.add(args[opti]);
22628                    opti++;
22629                }
22630                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22631                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22632            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22633                dumpState.setDump(DumpState.DUMP_PREFERRED);
22634            } else if ("preferred-xml".equals(cmd)) {
22635                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22636                if (opti < args.length && "--full".equals(args[opti])) {
22637                    fullPreferred = true;
22638                    opti++;
22639                }
22640            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22641                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22642            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22643                dumpState.setDump(DumpState.DUMP_PACKAGES);
22644            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22645                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22646            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22647                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22648            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22649                dumpState.setDump(DumpState.DUMP_MESSAGES);
22650            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22651                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22652            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22653                    || "intent-filter-verifiers".equals(cmd)) {
22654                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22655            } else if ("version".equals(cmd)) {
22656                dumpState.setDump(DumpState.DUMP_VERSION);
22657            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22658                dumpState.setDump(DumpState.DUMP_KEYSETS);
22659            } else if ("installs".equals(cmd)) {
22660                dumpState.setDump(DumpState.DUMP_INSTALLS);
22661            } else if ("frozen".equals(cmd)) {
22662                dumpState.setDump(DumpState.DUMP_FROZEN);
22663            } else if ("volumes".equals(cmd)) {
22664                dumpState.setDump(DumpState.DUMP_VOLUMES);
22665            } else if ("dexopt".equals(cmd)) {
22666                dumpState.setDump(DumpState.DUMP_DEXOPT);
22667            } else if ("compiler-stats".equals(cmd)) {
22668                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22669            } else if ("changes".equals(cmd)) {
22670                dumpState.setDump(DumpState.DUMP_CHANGES);
22671            } else if ("write".equals(cmd)) {
22672                synchronized (mPackages) {
22673                    mSettings.writeLPr();
22674                    pw.println("Settings written.");
22675                    return;
22676                }
22677            }
22678        }
22679
22680        if (checkin) {
22681            pw.println("vers,1");
22682        }
22683
22684        // reader
22685        synchronized (mPackages) {
22686            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22687                if (!checkin) {
22688                    if (dumpState.onTitlePrinted())
22689                        pw.println();
22690                    pw.println("Database versions:");
22691                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22692                }
22693            }
22694
22695            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22696                if (!checkin) {
22697                    if (dumpState.onTitlePrinted())
22698                        pw.println();
22699                    pw.println("Verifiers:");
22700                    pw.print("  Required: ");
22701                    pw.print(mRequiredVerifierPackage);
22702                    pw.print(" (uid=");
22703                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22704                            UserHandle.USER_SYSTEM));
22705                    pw.println(")");
22706                } else if (mRequiredVerifierPackage != null) {
22707                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22708                    pw.print(",");
22709                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22710                            UserHandle.USER_SYSTEM));
22711                }
22712            }
22713
22714            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22715                    packageName == null) {
22716                if (mIntentFilterVerifierComponent != null) {
22717                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22718                    if (!checkin) {
22719                        if (dumpState.onTitlePrinted())
22720                            pw.println();
22721                        pw.println("Intent Filter Verifier:");
22722                        pw.print("  Using: ");
22723                        pw.print(verifierPackageName);
22724                        pw.print(" (uid=");
22725                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22726                                UserHandle.USER_SYSTEM));
22727                        pw.println(")");
22728                    } else if (verifierPackageName != null) {
22729                        pw.print("ifv,"); pw.print(verifierPackageName);
22730                        pw.print(",");
22731                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22732                                UserHandle.USER_SYSTEM));
22733                    }
22734                } else {
22735                    pw.println();
22736                    pw.println("No Intent Filter Verifier available!");
22737                }
22738            }
22739
22740            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22741                boolean printedHeader = false;
22742                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22743                while (it.hasNext()) {
22744                    String libName = it.next();
22745                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22746                    if (versionedLib == null) {
22747                        continue;
22748                    }
22749                    final int versionCount = versionedLib.size();
22750                    for (int i = 0; i < versionCount; i++) {
22751                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22752                        if (!checkin) {
22753                            if (!printedHeader) {
22754                                if (dumpState.onTitlePrinted())
22755                                    pw.println();
22756                                pw.println("Libraries:");
22757                                printedHeader = true;
22758                            }
22759                            pw.print("  ");
22760                        } else {
22761                            pw.print("lib,");
22762                        }
22763                        pw.print(libEntry.info.getName());
22764                        if (libEntry.info.isStatic()) {
22765                            pw.print(" version=" + libEntry.info.getVersion());
22766                        }
22767                        if (!checkin) {
22768                            pw.print(" -> ");
22769                        }
22770                        if (libEntry.path != null) {
22771                            pw.print(" (jar) ");
22772                            pw.print(libEntry.path);
22773                        } else {
22774                            pw.print(" (apk) ");
22775                            pw.print(libEntry.apk);
22776                        }
22777                        pw.println();
22778                    }
22779                }
22780            }
22781
22782            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22783                if (dumpState.onTitlePrinted())
22784                    pw.println();
22785                if (!checkin) {
22786                    pw.println("Features:");
22787                }
22788
22789                synchronized (mAvailableFeatures) {
22790                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22791                        if (checkin) {
22792                            pw.print("feat,");
22793                            pw.print(feat.name);
22794                            pw.print(",");
22795                            pw.println(feat.version);
22796                        } else {
22797                            pw.print("  ");
22798                            pw.print(feat.name);
22799                            if (feat.version > 0) {
22800                                pw.print(" version=");
22801                                pw.print(feat.version);
22802                            }
22803                            pw.println();
22804                        }
22805                    }
22806                }
22807            }
22808
22809            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22810                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22811                        : "Activity Resolver Table:", "  ", packageName,
22812                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22813                    dumpState.setTitlePrinted(true);
22814                }
22815            }
22816            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22817                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22818                        : "Receiver Resolver Table:", "  ", packageName,
22819                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22820                    dumpState.setTitlePrinted(true);
22821                }
22822            }
22823            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22824                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22825                        : "Service Resolver Table:", "  ", packageName,
22826                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22827                    dumpState.setTitlePrinted(true);
22828                }
22829            }
22830            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22831                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22832                        : "Provider Resolver Table:", "  ", packageName,
22833                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22834                    dumpState.setTitlePrinted(true);
22835                }
22836            }
22837
22838            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22839                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22840                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22841                    int user = mSettings.mPreferredActivities.keyAt(i);
22842                    if (pir.dump(pw,
22843                            dumpState.getTitlePrinted()
22844                                ? "\nPreferred Activities User " + user + ":"
22845                                : "Preferred Activities User " + user + ":", "  ",
22846                            packageName, true, false)) {
22847                        dumpState.setTitlePrinted(true);
22848                    }
22849                }
22850            }
22851
22852            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22853                pw.flush();
22854                FileOutputStream fout = new FileOutputStream(fd);
22855                BufferedOutputStream str = new BufferedOutputStream(fout);
22856                XmlSerializer serializer = new FastXmlSerializer();
22857                try {
22858                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22859                    serializer.startDocument(null, true);
22860                    serializer.setFeature(
22861                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22862                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22863                    serializer.endDocument();
22864                    serializer.flush();
22865                } catch (IllegalArgumentException e) {
22866                    pw.println("Failed writing: " + e);
22867                } catch (IllegalStateException e) {
22868                    pw.println("Failed writing: " + e);
22869                } catch (IOException e) {
22870                    pw.println("Failed writing: " + e);
22871                }
22872            }
22873
22874            if (!checkin
22875                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22876                    && packageName == null) {
22877                pw.println();
22878                int count = mSettings.mPackages.size();
22879                if (count == 0) {
22880                    pw.println("No applications!");
22881                    pw.println();
22882                } else {
22883                    final String prefix = "  ";
22884                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22885                    if (allPackageSettings.size() == 0) {
22886                        pw.println("No domain preferred apps!");
22887                        pw.println();
22888                    } else {
22889                        pw.println("App verification status:");
22890                        pw.println();
22891                        count = 0;
22892                        for (PackageSetting ps : allPackageSettings) {
22893                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22894                            if (ivi == null || ivi.getPackageName() == null) continue;
22895                            pw.println(prefix + "Package: " + ivi.getPackageName());
22896                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22897                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22898                            pw.println();
22899                            count++;
22900                        }
22901                        if (count == 0) {
22902                            pw.println(prefix + "No app verification established.");
22903                            pw.println();
22904                        }
22905                        for (int userId : sUserManager.getUserIds()) {
22906                            pw.println("App linkages for user " + userId + ":");
22907                            pw.println();
22908                            count = 0;
22909                            for (PackageSetting ps : allPackageSettings) {
22910                                final long status = ps.getDomainVerificationStatusForUser(userId);
22911                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22912                                        && !DEBUG_DOMAIN_VERIFICATION) {
22913                                    continue;
22914                                }
22915                                pw.println(prefix + "Package: " + ps.name);
22916                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22917                                String statusStr = IntentFilterVerificationInfo.
22918                                        getStatusStringFromValue(status);
22919                                pw.println(prefix + "Status:  " + statusStr);
22920                                pw.println();
22921                                count++;
22922                            }
22923                            if (count == 0) {
22924                                pw.println(prefix + "No configured app linkages.");
22925                                pw.println();
22926                            }
22927                        }
22928                    }
22929                }
22930            }
22931
22932            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22933                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22934                if (packageName == null && permissionNames == null) {
22935                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22936                        if (iperm == 0) {
22937                            if (dumpState.onTitlePrinted())
22938                                pw.println();
22939                            pw.println("AppOp Permissions:");
22940                        }
22941                        pw.print("  AppOp Permission ");
22942                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22943                        pw.println(":");
22944                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22945                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22946                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22947                        }
22948                    }
22949                }
22950            }
22951
22952            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22953                boolean printedSomething = false;
22954                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22955                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22956                        continue;
22957                    }
22958                    if (!printedSomething) {
22959                        if (dumpState.onTitlePrinted())
22960                            pw.println();
22961                        pw.println("Registered ContentProviders:");
22962                        printedSomething = true;
22963                    }
22964                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22965                    pw.print("    "); pw.println(p.toString());
22966                }
22967                printedSomething = false;
22968                for (Map.Entry<String, PackageParser.Provider> entry :
22969                        mProvidersByAuthority.entrySet()) {
22970                    PackageParser.Provider p = entry.getValue();
22971                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22972                        continue;
22973                    }
22974                    if (!printedSomething) {
22975                        if (dumpState.onTitlePrinted())
22976                            pw.println();
22977                        pw.println("ContentProvider Authorities:");
22978                        printedSomething = true;
22979                    }
22980                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22981                    pw.print("    "); pw.println(p.toString());
22982                    if (p.info != null && p.info.applicationInfo != null) {
22983                        final String appInfo = p.info.applicationInfo.toString();
22984                        pw.print("      applicationInfo="); pw.println(appInfo);
22985                    }
22986                }
22987            }
22988
22989            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22990                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22991            }
22992
22993            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22994                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22995            }
22996
22997            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22998                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22999            }
23000
23001            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
23002                if (dumpState.onTitlePrinted()) pw.println();
23003                pw.println("Package Changes:");
23004                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
23005                final int K = mChangedPackages.size();
23006                for (int i = 0; i < K; i++) {
23007                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
23008                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
23009                    final int N = changes.size();
23010                    if (N == 0) {
23011                        pw.print("    "); pw.println("No packages changed");
23012                    } else {
23013                        for (int j = 0; j < N; j++) {
23014                            final String pkgName = changes.valueAt(j);
23015                            final int sequenceNumber = changes.keyAt(j);
23016                            pw.print("    ");
23017                            pw.print("seq=");
23018                            pw.print(sequenceNumber);
23019                            pw.print(", package=");
23020                            pw.println(pkgName);
23021                        }
23022                    }
23023                }
23024            }
23025
23026            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
23027                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
23028            }
23029
23030            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
23031                // XXX should handle packageName != null by dumping only install data that
23032                // the given package is involved with.
23033                if (dumpState.onTitlePrinted()) pw.println();
23034
23035                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23036                ipw.println();
23037                ipw.println("Frozen packages:");
23038                ipw.increaseIndent();
23039                if (mFrozenPackages.size() == 0) {
23040                    ipw.println("(none)");
23041                } else {
23042                    for (int i = 0; i < mFrozenPackages.size(); i++) {
23043                        ipw.println(mFrozenPackages.valueAt(i));
23044                    }
23045                }
23046                ipw.decreaseIndent();
23047            }
23048
23049            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
23050                if (dumpState.onTitlePrinted()) pw.println();
23051
23052                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23053                ipw.println();
23054                ipw.println("Loaded volumes:");
23055                ipw.increaseIndent();
23056                if (mLoadedVolumes.size() == 0) {
23057                    ipw.println("(none)");
23058                } else {
23059                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
23060                        ipw.println(mLoadedVolumes.valueAt(i));
23061                    }
23062                }
23063                ipw.decreaseIndent();
23064            }
23065
23066            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
23067                if (dumpState.onTitlePrinted()) pw.println();
23068                dumpDexoptStateLPr(pw, packageName);
23069            }
23070
23071            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
23072                if (dumpState.onTitlePrinted()) pw.println();
23073                dumpCompilerStatsLPr(pw, packageName);
23074            }
23075
23076            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
23077                if (dumpState.onTitlePrinted()) pw.println();
23078                mSettings.dumpReadMessagesLPr(pw, dumpState);
23079
23080                pw.println();
23081                pw.println("Package warning messages:");
23082                BufferedReader in = null;
23083                String line = null;
23084                try {
23085                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23086                    while ((line = in.readLine()) != null) {
23087                        if (line.contains("ignored: updated version")) continue;
23088                        pw.println(line);
23089                    }
23090                } catch (IOException ignored) {
23091                } finally {
23092                    IoUtils.closeQuietly(in);
23093                }
23094            }
23095
23096            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
23097                BufferedReader in = null;
23098                String line = null;
23099                try {
23100                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23101                    while ((line = in.readLine()) != null) {
23102                        if (line.contains("ignored: updated version")) continue;
23103                        pw.print("msg,");
23104                        pw.println(line);
23105                    }
23106                } catch (IOException ignored) {
23107                } finally {
23108                    IoUtils.closeQuietly(in);
23109                }
23110            }
23111        }
23112
23113        // PackageInstaller should be called outside of mPackages lock
23114        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
23115            // XXX should handle packageName != null by dumping only install data that
23116            // the given package is involved with.
23117            if (dumpState.onTitlePrinted()) pw.println();
23118            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
23119        }
23120    }
23121
23122    private void dumpProto(FileDescriptor fd) {
23123        final ProtoOutputStream proto = new ProtoOutputStream(fd);
23124
23125        synchronized (mPackages) {
23126            final long requiredVerifierPackageToken =
23127                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
23128            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
23129            proto.write(
23130                    PackageServiceDumpProto.PackageShortProto.UID,
23131                    getPackageUid(
23132                            mRequiredVerifierPackage,
23133                            MATCH_DEBUG_TRIAGED_MISSING,
23134                            UserHandle.USER_SYSTEM));
23135            proto.end(requiredVerifierPackageToken);
23136
23137            if (mIntentFilterVerifierComponent != null) {
23138                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
23139                final long verifierPackageToken =
23140                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
23141                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
23142                proto.write(
23143                        PackageServiceDumpProto.PackageShortProto.UID,
23144                        getPackageUid(
23145                                verifierPackageName,
23146                                MATCH_DEBUG_TRIAGED_MISSING,
23147                                UserHandle.USER_SYSTEM));
23148                proto.end(verifierPackageToken);
23149            }
23150
23151            dumpSharedLibrariesProto(proto);
23152            dumpFeaturesProto(proto);
23153            mSettings.dumpPackagesProto(proto);
23154            mSettings.dumpSharedUsersProto(proto);
23155            dumpMessagesProto(proto);
23156        }
23157        proto.flush();
23158    }
23159
23160    private void dumpMessagesProto(ProtoOutputStream proto) {
23161        BufferedReader in = null;
23162        String line = null;
23163        try {
23164            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23165            while ((line = in.readLine()) != null) {
23166                if (line.contains("ignored: updated version")) continue;
23167                proto.write(PackageServiceDumpProto.MESSAGES, line);
23168            }
23169        } catch (IOException ignored) {
23170        } finally {
23171            IoUtils.closeQuietly(in);
23172        }
23173    }
23174
23175    private void dumpFeaturesProto(ProtoOutputStream proto) {
23176        synchronized (mAvailableFeatures) {
23177            final int count = mAvailableFeatures.size();
23178            for (int i = 0; i < count; i++) {
23179                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
23180                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
23181                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
23182                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
23183                proto.end(featureToken);
23184            }
23185        }
23186    }
23187
23188    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
23189        final int count = mSharedLibraries.size();
23190        for (int i = 0; i < count; i++) {
23191            final String libName = mSharedLibraries.keyAt(i);
23192            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
23193            if (versionedLib == null) {
23194                continue;
23195            }
23196            final int versionCount = versionedLib.size();
23197            for (int j = 0; j < versionCount; j++) {
23198                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
23199                final long sharedLibraryToken =
23200                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
23201                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
23202                final boolean isJar = (libEntry.path != null);
23203                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
23204                if (isJar) {
23205                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
23206                } else {
23207                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
23208                }
23209                proto.end(sharedLibraryToken);
23210            }
23211        }
23212    }
23213
23214    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
23215        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23216        ipw.println();
23217        ipw.println("Dexopt state:");
23218        ipw.increaseIndent();
23219        Collection<PackageParser.Package> packages = null;
23220        if (packageName != null) {
23221            PackageParser.Package targetPackage = mPackages.get(packageName);
23222            if (targetPackage != null) {
23223                packages = Collections.singletonList(targetPackage);
23224            } else {
23225                ipw.println("Unable to find package: " + packageName);
23226                return;
23227            }
23228        } else {
23229            packages = mPackages.values();
23230        }
23231
23232        for (PackageParser.Package pkg : packages) {
23233            ipw.println("[" + pkg.packageName + "]");
23234            ipw.increaseIndent();
23235            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
23236                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
23237            ipw.decreaseIndent();
23238        }
23239    }
23240
23241    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
23242        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23243        ipw.println();
23244        ipw.println("Compiler stats:");
23245        ipw.increaseIndent();
23246        Collection<PackageParser.Package> packages = null;
23247        if (packageName != null) {
23248            PackageParser.Package targetPackage = mPackages.get(packageName);
23249            if (targetPackage != null) {
23250                packages = Collections.singletonList(targetPackage);
23251            } else {
23252                ipw.println("Unable to find package: " + packageName);
23253                return;
23254            }
23255        } else {
23256            packages = mPackages.values();
23257        }
23258
23259        for (PackageParser.Package pkg : packages) {
23260            ipw.println("[" + pkg.packageName + "]");
23261            ipw.increaseIndent();
23262
23263            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
23264            if (stats == null) {
23265                ipw.println("(No recorded stats)");
23266            } else {
23267                stats.dump(ipw);
23268            }
23269            ipw.decreaseIndent();
23270        }
23271    }
23272
23273    private String dumpDomainString(String packageName) {
23274        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
23275                .getList();
23276        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
23277
23278        ArraySet<String> result = new ArraySet<>();
23279        if (iviList.size() > 0) {
23280            for (IntentFilterVerificationInfo ivi : iviList) {
23281                for (String host : ivi.getDomains()) {
23282                    result.add(host);
23283                }
23284            }
23285        }
23286        if (filters != null && filters.size() > 0) {
23287            for (IntentFilter filter : filters) {
23288                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
23289                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
23290                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
23291                    result.addAll(filter.getHostsList());
23292                }
23293            }
23294        }
23295
23296        StringBuilder sb = new StringBuilder(result.size() * 16);
23297        for (String domain : result) {
23298            if (sb.length() > 0) sb.append(" ");
23299            sb.append(domain);
23300        }
23301        return sb.toString();
23302    }
23303
23304    // ------- apps on sdcard specific code -------
23305    static final boolean DEBUG_SD_INSTALL = false;
23306
23307    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
23308
23309    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
23310
23311    private boolean mMediaMounted = false;
23312
23313    static String getEncryptKey() {
23314        try {
23315            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
23316                    SD_ENCRYPTION_KEYSTORE_NAME);
23317            if (sdEncKey == null) {
23318                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23319                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23320                if (sdEncKey == null) {
23321                    Slog.e(TAG, "Failed to create encryption keys");
23322                    return null;
23323                }
23324            }
23325            return sdEncKey;
23326        } catch (NoSuchAlgorithmException nsae) {
23327            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23328            return null;
23329        } catch (IOException ioe) {
23330            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23331            return null;
23332        }
23333    }
23334
23335    /*
23336     * Update media status on PackageManager.
23337     */
23338    @Override
23339    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
23340        enforceSystemOrRoot("Media status can only be updated by the system");
23341        // reader; this apparently protects mMediaMounted, but should probably
23342        // be a different lock in that case.
23343        synchronized (mPackages) {
23344            Log.i(TAG, "Updating external media status from "
23345                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
23346                    + (mediaStatus ? "mounted" : "unmounted"));
23347            if (DEBUG_SD_INSTALL)
23348                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
23349                        + ", mMediaMounted=" + mMediaMounted);
23350            if (mediaStatus == mMediaMounted) {
23351                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
23352                        : 0, -1);
23353                mHandler.sendMessage(msg);
23354                return;
23355            }
23356            mMediaMounted = mediaStatus;
23357        }
23358        // Queue up an async operation since the package installation may take a
23359        // little while.
23360        mHandler.post(new Runnable() {
23361            public void run() {
23362                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23363            }
23364        });
23365    }
23366
23367    /**
23368     * Called by StorageManagerService when the initial ASECs to scan are available.
23369     * Should block until all the ASEC containers are finished being scanned.
23370     */
23371    public void scanAvailableAsecs() {
23372        updateExternalMediaStatusInner(true, false, false);
23373    }
23374
23375    /*
23376     * Collect information of applications on external media, map them against
23377     * existing containers and update information based on current mount status.
23378     * Please note that we always have to report status if reportStatus has been
23379     * set to true especially when unloading packages.
23380     */
23381    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23382            boolean externalStorage) {
23383        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23384        int[] uidArr = EmptyArray.INT;
23385
23386        final String[] list = PackageHelper.getSecureContainerList();
23387        if (ArrayUtils.isEmpty(list)) {
23388            Log.i(TAG, "No secure containers found");
23389        } else {
23390            // Process list of secure containers and categorize them
23391            // as active or stale based on their package internal state.
23392
23393            // reader
23394            synchronized (mPackages) {
23395                for (String cid : list) {
23396                    // Leave stages untouched for now; installer service owns them
23397                    if (PackageInstallerService.isStageName(cid)) continue;
23398
23399                    if (DEBUG_SD_INSTALL)
23400                        Log.i(TAG, "Processing container " + cid);
23401                    String pkgName = getAsecPackageName(cid);
23402                    if (pkgName == null) {
23403                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23404                        continue;
23405                    }
23406                    if (DEBUG_SD_INSTALL)
23407                        Log.i(TAG, "Looking for pkg : " + pkgName);
23408
23409                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23410                    if (ps == null) {
23411                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23412                        continue;
23413                    }
23414
23415                    /*
23416                     * Skip packages that are not external if we're unmounting
23417                     * external storage.
23418                     */
23419                    if (externalStorage && !isMounted && !isExternal(ps)) {
23420                        continue;
23421                    }
23422
23423                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23424                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23425                    // The package status is changed only if the code path
23426                    // matches between settings and the container id.
23427                    if (ps.codePathString != null
23428                            && ps.codePathString.startsWith(args.getCodePath())) {
23429                        if (DEBUG_SD_INSTALL) {
23430                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23431                                    + " at code path: " + ps.codePathString);
23432                        }
23433
23434                        // We do have a valid package installed on sdcard
23435                        processCids.put(args, ps.codePathString);
23436                        final int uid = ps.appId;
23437                        if (uid != -1) {
23438                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23439                        }
23440                    } else {
23441                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23442                                + ps.codePathString);
23443                    }
23444                }
23445            }
23446
23447            Arrays.sort(uidArr);
23448        }
23449
23450        // Process packages with valid entries.
23451        if (isMounted) {
23452            if (DEBUG_SD_INSTALL)
23453                Log.i(TAG, "Loading packages");
23454            loadMediaPackages(processCids, uidArr, externalStorage);
23455            startCleaningPackages();
23456            mInstallerService.onSecureContainersAvailable();
23457        } else {
23458            if (DEBUG_SD_INSTALL)
23459                Log.i(TAG, "Unloading packages");
23460            unloadMediaPackages(processCids, uidArr, reportStatus);
23461        }
23462    }
23463
23464    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23465            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23466        final int size = infos.size();
23467        final String[] packageNames = new String[size];
23468        final int[] packageUids = new int[size];
23469        for (int i = 0; i < size; i++) {
23470            final ApplicationInfo info = infos.get(i);
23471            packageNames[i] = info.packageName;
23472            packageUids[i] = info.uid;
23473        }
23474        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23475                finishedReceiver);
23476    }
23477
23478    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23479            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23480        sendResourcesChangedBroadcast(mediaStatus, replacing,
23481                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23482    }
23483
23484    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23485            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23486        int size = pkgList.length;
23487        if (size > 0) {
23488            // Send broadcasts here
23489            Bundle extras = new Bundle();
23490            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23491            if (uidArr != null) {
23492                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23493            }
23494            if (replacing) {
23495                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23496            }
23497            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23498                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23499            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23500        }
23501    }
23502
23503   /*
23504     * Look at potentially valid container ids from processCids If package
23505     * information doesn't match the one on record or package scanning fails,
23506     * the cid is added to list of removeCids. We currently don't delete stale
23507     * containers.
23508     */
23509    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23510            boolean externalStorage) {
23511        ArrayList<String> pkgList = new ArrayList<String>();
23512        Set<AsecInstallArgs> keys = processCids.keySet();
23513
23514        for (AsecInstallArgs args : keys) {
23515            String codePath = processCids.get(args);
23516            if (DEBUG_SD_INSTALL)
23517                Log.i(TAG, "Loading container : " + args.cid);
23518            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23519            try {
23520                // Make sure there are no container errors first.
23521                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23522                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23523                            + " when installing from sdcard");
23524                    continue;
23525                }
23526                // Check code path here.
23527                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23528                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23529                            + " does not match one in settings " + codePath);
23530                    continue;
23531                }
23532                // Parse package
23533                int parseFlags = mDefParseFlags;
23534                if (args.isExternalAsec()) {
23535                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23536                }
23537                if (args.isFwdLocked()) {
23538                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23539                }
23540
23541                synchronized (mInstallLock) {
23542                    PackageParser.Package pkg = null;
23543                    try {
23544                        // Sadly we don't know the package name yet to freeze it
23545                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23546                                SCAN_IGNORE_FROZEN, 0, null);
23547                    } catch (PackageManagerException e) {
23548                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23549                    }
23550                    // Scan the package
23551                    if (pkg != null) {
23552                        /*
23553                         * TODO why is the lock being held? doPostInstall is
23554                         * called in other places without the lock. This needs
23555                         * to be straightened out.
23556                         */
23557                        // writer
23558                        synchronized (mPackages) {
23559                            retCode = PackageManager.INSTALL_SUCCEEDED;
23560                            pkgList.add(pkg.packageName);
23561                            // Post process args
23562                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23563                                    pkg.applicationInfo.uid);
23564                        }
23565                    } else {
23566                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23567                    }
23568                }
23569
23570            } finally {
23571                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23572                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23573                }
23574            }
23575        }
23576        // writer
23577        synchronized (mPackages) {
23578            // If the platform SDK has changed since the last time we booted,
23579            // we need to re-grant app permission to catch any new ones that
23580            // appear. This is really a hack, and means that apps can in some
23581            // cases get permissions that the user didn't initially explicitly
23582            // allow... it would be nice to have some better way to handle
23583            // this situation.
23584            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23585                    : mSettings.getInternalVersion();
23586            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23587                    : StorageManager.UUID_PRIVATE_INTERNAL;
23588
23589            int updateFlags = UPDATE_PERMISSIONS_ALL;
23590            if (ver.sdkVersion != mSdkVersion) {
23591                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23592                        + mSdkVersion + "; regranting permissions for external");
23593                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23594            }
23595            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23596
23597            // Yay, everything is now upgraded
23598            ver.forceCurrent();
23599
23600            // can downgrade to reader
23601            // Persist settings
23602            mSettings.writeLPr();
23603        }
23604        // Send a broadcast to let everyone know we are done processing
23605        if (pkgList.size() > 0) {
23606            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23607        }
23608    }
23609
23610   /*
23611     * Utility method to unload a list of specified containers
23612     */
23613    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23614        // Just unmount all valid containers.
23615        for (AsecInstallArgs arg : cidArgs) {
23616            synchronized (mInstallLock) {
23617                arg.doPostDeleteLI(false);
23618           }
23619       }
23620   }
23621
23622    /*
23623     * Unload packages mounted on external media. This involves deleting package
23624     * data from internal structures, sending broadcasts about disabled packages,
23625     * gc'ing to free up references, unmounting all secure containers
23626     * corresponding to packages on external media, and posting a
23627     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23628     * that we always have to post this message if status has been requested no
23629     * matter what.
23630     */
23631    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23632            final boolean reportStatus) {
23633        if (DEBUG_SD_INSTALL)
23634            Log.i(TAG, "unloading media packages");
23635        ArrayList<String> pkgList = new ArrayList<String>();
23636        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23637        final Set<AsecInstallArgs> keys = processCids.keySet();
23638        for (AsecInstallArgs args : keys) {
23639            String pkgName = args.getPackageName();
23640            if (DEBUG_SD_INSTALL)
23641                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23642            // Delete package internally
23643            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23644            synchronized (mInstallLock) {
23645                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23646                final boolean res;
23647                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23648                        "unloadMediaPackages")) {
23649                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23650                            null);
23651                }
23652                if (res) {
23653                    pkgList.add(pkgName);
23654                } else {
23655                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23656                    failedList.add(args);
23657                }
23658            }
23659        }
23660
23661        // reader
23662        synchronized (mPackages) {
23663            // We didn't update the settings after removing each package;
23664            // write them now for all packages.
23665            mSettings.writeLPr();
23666        }
23667
23668        // We have to absolutely send UPDATED_MEDIA_STATUS only
23669        // after confirming that all the receivers processed the ordered
23670        // broadcast when packages get disabled, force a gc to clean things up.
23671        // and unload all the containers.
23672        if (pkgList.size() > 0) {
23673            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23674                    new IIntentReceiver.Stub() {
23675                public void performReceive(Intent intent, int resultCode, String data,
23676                        Bundle extras, boolean ordered, boolean sticky,
23677                        int sendingUser) throws RemoteException {
23678                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23679                            reportStatus ? 1 : 0, 1, keys);
23680                    mHandler.sendMessage(msg);
23681                }
23682            });
23683        } else {
23684            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23685                    keys);
23686            mHandler.sendMessage(msg);
23687        }
23688    }
23689
23690    private void loadPrivatePackages(final VolumeInfo vol) {
23691        mHandler.post(new Runnable() {
23692            @Override
23693            public void run() {
23694                loadPrivatePackagesInner(vol);
23695            }
23696        });
23697    }
23698
23699    private void loadPrivatePackagesInner(VolumeInfo vol) {
23700        final String volumeUuid = vol.fsUuid;
23701        if (TextUtils.isEmpty(volumeUuid)) {
23702            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23703            return;
23704        }
23705
23706        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23707        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23708        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23709
23710        final VersionInfo ver;
23711        final List<PackageSetting> packages;
23712        synchronized (mPackages) {
23713            ver = mSettings.findOrCreateVersion(volumeUuid);
23714            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23715        }
23716
23717        for (PackageSetting ps : packages) {
23718            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23719            synchronized (mInstallLock) {
23720                final PackageParser.Package pkg;
23721                try {
23722                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23723                    loaded.add(pkg.applicationInfo);
23724
23725                } catch (PackageManagerException e) {
23726                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23727                }
23728
23729                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23730                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23731                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23732                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23733                }
23734            }
23735        }
23736
23737        // Reconcile app data for all started/unlocked users
23738        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23739        final UserManager um = mContext.getSystemService(UserManager.class);
23740        UserManagerInternal umInternal = getUserManagerInternal();
23741        for (UserInfo user : um.getUsers()) {
23742            final int flags;
23743            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23744                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23745            } else if (umInternal.isUserRunning(user.id)) {
23746                flags = StorageManager.FLAG_STORAGE_DE;
23747            } else {
23748                continue;
23749            }
23750
23751            try {
23752                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23753                synchronized (mInstallLock) {
23754                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23755                }
23756            } catch (IllegalStateException e) {
23757                // Device was probably ejected, and we'll process that event momentarily
23758                Slog.w(TAG, "Failed to prepare storage: " + e);
23759            }
23760        }
23761
23762        synchronized (mPackages) {
23763            int updateFlags = UPDATE_PERMISSIONS_ALL;
23764            if (ver.sdkVersion != mSdkVersion) {
23765                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23766                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23767                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23768            }
23769            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23770
23771            // Yay, everything is now upgraded
23772            ver.forceCurrent();
23773
23774            mSettings.writeLPr();
23775        }
23776
23777        for (PackageFreezer freezer : freezers) {
23778            freezer.close();
23779        }
23780
23781        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23782        sendResourcesChangedBroadcast(true, false, loaded, null);
23783        mLoadedVolumes.add(vol.getId());
23784    }
23785
23786    private void unloadPrivatePackages(final VolumeInfo vol) {
23787        mHandler.post(new Runnable() {
23788            @Override
23789            public void run() {
23790                unloadPrivatePackagesInner(vol);
23791            }
23792        });
23793    }
23794
23795    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23796        final String volumeUuid = vol.fsUuid;
23797        if (TextUtils.isEmpty(volumeUuid)) {
23798            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23799            return;
23800        }
23801
23802        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23803        synchronized (mInstallLock) {
23804        synchronized (mPackages) {
23805            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23806            for (PackageSetting ps : packages) {
23807                if (ps.pkg == null) continue;
23808
23809                final ApplicationInfo info = ps.pkg.applicationInfo;
23810                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23811                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23812
23813                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23814                        "unloadPrivatePackagesInner")) {
23815                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23816                            false, null)) {
23817                        unloaded.add(info);
23818                    } else {
23819                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23820                    }
23821                }
23822
23823                // Try very hard to release any references to this package
23824                // so we don't risk the system server being killed due to
23825                // open FDs
23826                AttributeCache.instance().removePackage(ps.name);
23827            }
23828
23829            mSettings.writeLPr();
23830        }
23831        }
23832
23833        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23834        sendResourcesChangedBroadcast(false, false, unloaded, null);
23835        mLoadedVolumes.remove(vol.getId());
23836
23837        // Try very hard to release any references to this path so we don't risk
23838        // the system server being killed due to open FDs
23839        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23840
23841        for (int i = 0; i < 3; i++) {
23842            System.gc();
23843            System.runFinalization();
23844        }
23845    }
23846
23847    private void assertPackageKnown(String volumeUuid, String packageName)
23848            throws PackageManagerException {
23849        synchronized (mPackages) {
23850            // Normalize package name to handle renamed packages
23851            packageName = normalizePackageNameLPr(packageName);
23852
23853            final PackageSetting ps = mSettings.mPackages.get(packageName);
23854            if (ps == null) {
23855                throw new PackageManagerException("Package " + packageName + " is unknown");
23856            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23857                throw new PackageManagerException(
23858                        "Package " + packageName + " found on unknown volume " + volumeUuid
23859                                + "; expected volume " + ps.volumeUuid);
23860            }
23861        }
23862    }
23863
23864    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23865            throws PackageManagerException {
23866        synchronized (mPackages) {
23867            // Normalize package name to handle renamed packages
23868            packageName = normalizePackageNameLPr(packageName);
23869
23870            final PackageSetting ps = mSettings.mPackages.get(packageName);
23871            if (ps == null) {
23872                throw new PackageManagerException("Package " + packageName + " is unknown");
23873            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23874                throw new PackageManagerException(
23875                        "Package " + packageName + " found on unknown volume " + volumeUuid
23876                                + "; expected volume " + ps.volumeUuid);
23877            } else if (!ps.getInstalled(userId)) {
23878                throw new PackageManagerException(
23879                        "Package " + packageName + " not installed for user " + userId);
23880            }
23881        }
23882    }
23883
23884    private List<String> collectAbsoluteCodePaths() {
23885        synchronized (mPackages) {
23886            List<String> codePaths = new ArrayList<>();
23887            final int packageCount = mSettings.mPackages.size();
23888            for (int i = 0; i < packageCount; i++) {
23889                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23890                codePaths.add(ps.codePath.getAbsolutePath());
23891            }
23892            return codePaths;
23893        }
23894    }
23895
23896    /**
23897     * Examine all apps present on given mounted volume, and destroy apps that
23898     * aren't expected, either due to uninstallation or reinstallation on
23899     * another volume.
23900     */
23901    private void reconcileApps(String volumeUuid) {
23902        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23903        List<File> filesToDelete = null;
23904
23905        final File[] files = FileUtils.listFilesOrEmpty(
23906                Environment.getDataAppDirectory(volumeUuid));
23907        for (File file : files) {
23908            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23909                    && !PackageInstallerService.isStageName(file.getName());
23910            if (!isPackage) {
23911                // Ignore entries which are not packages
23912                continue;
23913            }
23914
23915            String absolutePath = file.getAbsolutePath();
23916
23917            boolean pathValid = false;
23918            final int absoluteCodePathCount = absoluteCodePaths.size();
23919            for (int i = 0; i < absoluteCodePathCount; i++) {
23920                String absoluteCodePath = absoluteCodePaths.get(i);
23921                if (absolutePath.startsWith(absoluteCodePath)) {
23922                    pathValid = true;
23923                    break;
23924                }
23925            }
23926
23927            if (!pathValid) {
23928                if (filesToDelete == null) {
23929                    filesToDelete = new ArrayList<>();
23930                }
23931                filesToDelete.add(file);
23932            }
23933        }
23934
23935        if (filesToDelete != null) {
23936            final int fileToDeleteCount = filesToDelete.size();
23937            for (int i = 0; i < fileToDeleteCount; i++) {
23938                File fileToDelete = filesToDelete.get(i);
23939                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23940                synchronized (mInstallLock) {
23941                    removeCodePathLI(fileToDelete);
23942                }
23943            }
23944        }
23945    }
23946
23947    /**
23948     * Reconcile all app data for the given user.
23949     * <p>
23950     * Verifies that directories exist and that ownership and labeling is
23951     * correct for all installed apps on all mounted volumes.
23952     */
23953    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23954        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23955        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23956            final String volumeUuid = vol.getFsUuid();
23957            synchronized (mInstallLock) {
23958                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23959            }
23960        }
23961    }
23962
23963    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23964            boolean migrateAppData) {
23965        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23966    }
23967
23968    /**
23969     * Reconcile all app data on given mounted volume.
23970     * <p>
23971     * Destroys app data that isn't expected, either due to uninstallation or
23972     * reinstallation on another volume.
23973     * <p>
23974     * Verifies that directories exist and that ownership and labeling is
23975     * correct for all installed apps.
23976     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23977     */
23978    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23979            boolean migrateAppData, boolean onlyCoreApps) {
23980        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23981                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23982        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23983
23984        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23985        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23986
23987        // First look for stale data that doesn't belong, and check if things
23988        // have changed since we did our last restorecon
23989        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23990            if (StorageManager.isFileEncryptedNativeOrEmulated()
23991                    && !StorageManager.isUserKeyUnlocked(userId)) {
23992                throw new RuntimeException(
23993                        "Yikes, someone asked us to reconcile CE storage while " + userId
23994                                + " was still locked; this would have caused massive data loss!");
23995            }
23996
23997            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23998            for (File file : files) {
23999                final String packageName = file.getName();
24000                try {
24001                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
24002                } catch (PackageManagerException e) {
24003                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
24004                    try {
24005                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
24006                                StorageManager.FLAG_STORAGE_CE, 0);
24007                    } catch (InstallerException e2) {
24008                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
24009                    }
24010                }
24011            }
24012        }
24013        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
24014            final File[] files = FileUtils.listFilesOrEmpty(deDir);
24015            for (File file : files) {
24016                final String packageName = file.getName();
24017                try {
24018                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
24019                } catch (PackageManagerException e) {
24020                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
24021                    try {
24022                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
24023                                StorageManager.FLAG_STORAGE_DE, 0);
24024                    } catch (InstallerException e2) {
24025                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
24026                    }
24027                }
24028            }
24029        }
24030
24031        // Ensure that data directories are ready to roll for all packages
24032        // installed for this volume and user
24033        final List<PackageSetting> packages;
24034        synchronized (mPackages) {
24035            packages = mSettings.getVolumePackagesLPr(volumeUuid);
24036        }
24037        int preparedCount = 0;
24038        for (PackageSetting ps : packages) {
24039            final String packageName = ps.name;
24040            if (ps.pkg == null) {
24041                Slog.w(TAG, "Odd, missing scanned package " + packageName);
24042                // TODO: might be due to legacy ASEC apps; we should circle back
24043                // and reconcile again once they're scanned
24044                continue;
24045            }
24046            // Skip non-core apps if requested
24047            if (onlyCoreApps && !ps.pkg.coreApp) {
24048                result.add(packageName);
24049                continue;
24050            }
24051
24052            if (ps.getInstalled(userId)) {
24053                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
24054                preparedCount++;
24055            }
24056        }
24057
24058        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
24059        return result;
24060    }
24061
24062    /**
24063     * Prepare app data for the given app just after it was installed or
24064     * upgraded. This method carefully only touches users that it's installed
24065     * for, and it forces a restorecon to handle any seinfo changes.
24066     * <p>
24067     * Verifies that directories exist and that ownership and labeling is
24068     * correct for all installed apps. If there is an ownership mismatch, it
24069     * will try recovering system apps by wiping data; third-party app data is
24070     * left intact.
24071     * <p>
24072     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
24073     */
24074    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
24075        final PackageSetting ps;
24076        synchronized (mPackages) {
24077            ps = mSettings.mPackages.get(pkg.packageName);
24078            mSettings.writeKernelMappingLPr(ps);
24079        }
24080
24081        final UserManager um = mContext.getSystemService(UserManager.class);
24082        UserManagerInternal umInternal = getUserManagerInternal();
24083        for (UserInfo user : um.getUsers()) {
24084            final int flags;
24085            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
24086                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
24087            } else if (umInternal.isUserRunning(user.id)) {
24088                flags = StorageManager.FLAG_STORAGE_DE;
24089            } else {
24090                continue;
24091            }
24092
24093            if (ps.getInstalled(user.id)) {
24094                // TODO: when user data is locked, mark that we're still dirty
24095                prepareAppDataLIF(pkg, user.id, flags);
24096            }
24097        }
24098    }
24099
24100    /**
24101     * Prepare app data for the given app.
24102     * <p>
24103     * Verifies that directories exist and that ownership and labeling is
24104     * correct for all installed apps. If there is an ownership mismatch, this
24105     * will try recovering system apps by wiping data; third-party app data is
24106     * left intact.
24107     */
24108    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
24109        if (pkg == null) {
24110            Slog.wtf(TAG, "Package was null!", new Throwable());
24111            return;
24112        }
24113        prepareAppDataLeafLIF(pkg, userId, flags);
24114        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24115        for (int i = 0; i < childCount; i++) {
24116            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
24117        }
24118    }
24119
24120    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
24121            boolean maybeMigrateAppData) {
24122        prepareAppDataLIF(pkg, userId, flags);
24123
24124        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
24125            // We may have just shuffled around app data directories, so
24126            // prepare them one more time
24127            prepareAppDataLIF(pkg, userId, flags);
24128        }
24129    }
24130
24131    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24132        if (DEBUG_APP_DATA) {
24133            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
24134                    + Integer.toHexString(flags));
24135        }
24136
24137        final String volumeUuid = pkg.volumeUuid;
24138        final String packageName = pkg.packageName;
24139        final ApplicationInfo app = pkg.applicationInfo;
24140        final int appId = UserHandle.getAppId(app.uid);
24141
24142        Preconditions.checkNotNull(app.seInfo);
24143
24144        long ceDataInode = -1;
24145        try {
24146            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24147                    appId, app.seInfo, app.targetSdkVersion);
24148        } catch (InstallerException e) {
24149            if (app.isSystemApp()) {
24150                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
24151                        + ", but trying to recover: " + e);
24152                destroyAppDataLeafLIF(pkg, userId, flags);
24153                try {
24154                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24155                            appId, app.seInfo, app.targetSdkVersion);
24156                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
24157                } catch (InstallerException e2) {
24158                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
24159                }
24160            } else {
24161                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
24162            }
24163        }
24164
24165        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
24166            // TODO: mark this structure as dirty so we persist it!
24167            synchronized (mPackages) {
24168                final PackageSetting ps = mSettings.mPackages.get(packageName);
24169                if (ps != null) {
24170                    ps.setCeDataInode(ceDataInode, userId);
24171                }
24172            }
24173        }
24174
24175        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24176    }
24177
24178    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
24179        if (pkg == null) {
24180            Slog.wtf(TAG, "Package was null!", new Throwable());
24181            return;
24182        }
24183        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24184        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24185        for (int i = 0; i < childCount; i++) {
24186            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
24187        }
24188    }
24189
24190    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24191        final String volumeUuid = pkg.volumeUuid;
24192        final String packageName = pkg.packageName;
24193        final ApplicationInfo app = pkg.applicationInfo;
24194
24195        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24196            // Create a native library symlink only if we have native libraries
24197            // and if the native libraries are 32 bit libraries. We do not provide
24198            // this symlink for 64 bit libraries.
24199            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
24200                final String nativeLibPath = app.nativeLibraryDir;
24201                try {
24202                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
24203                            nativeLibPath, userId);
24204                } catch (InstallerException e) {
24205                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
24206                }
24207            }
24208        }
24209    }
24210
24211    /**
24212     * For system apps on non-FBE devices, this method migrates any existing
24213     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
24214     * requested by the app.
24215     */
24216    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
24217        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
24218                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
24219            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
24220                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
24221            try {
24222                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
24223                        storageTarget);
24224            } catch (InstallerException e) {
24225                logCriticalInfo(Log.WARN,
24226                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
24227            }
24228            return true;
24229        } else {
24230            return false;
24231        }
24232    }
24233
24234    public PackageFreezer freezePackage(String packageName, String killReason) {
24235        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
24236    }
24237
24238    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
24239        return new PackageFreezer(packageName, userId, killReason);
24240    }
24241
24242    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
24243            String killReason) {
24244        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
24245    }
24246
24247    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
24248            String killReason) {
24249        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
24250            return new PackageFreezer();
24251        } else {
24252            return freezePackage(packageName, userId, killReason);
24253        }
24254    }
24255
24256    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
24257            String killReason) {
24258        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
24259    }
24260
24261    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
24262            String killReason) {
24263        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
24264            return new PackageFreezer();
24265        } else {
24266            return freezePackage(packageName, userId, killReason);
24267        }
24268    }
24269
24270    /**
24271     * Class that freezes and kills the given package upon creation, and
24272     * unfreezes it upon closing. This is typically used when doing surgery on
24273     * app code/data to prevent the app from running while you're working.
24274     */
24275    private class PackageFreezer implements AutoCloseable {
24276        private final String mPackageName;
24277        private final PackageFreezer[] mChildren;
24278
24279        private final boolean mWeFroze;
24280
24281        private final AtomicBoolean mClosed = new AtomicBoolean();
24282        private final CloseGuard mCloseGuard = CloseGuard.get();
24283
24284        /**
24285         * Create and return a stub freezer that doesn't actually do anything,
24286         * typically used when someone requested
24287         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
24288         * {@link PackageManager#DELETE_DONT_KILL_APP}.
24289         */
24290        public PackageFreezer() {
24291            mPackageName = null;
24292            mChildren = null;
24293            mWeFroze = false;
24294            mCloseGuard.open("close");
24295        }
24296
24297        public PackageFreezer(String packageName, int userId, String killReason) {
24298            synchronized (mPackages) {
24299                mPackageName = packageName;
24300                mWeFroze = mFrozenPackages.add(mPackageName);
24301
24302                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
24303                if (ps != null) {
24304                    killApplication(ps.name, ps.appId, userId, killReason);
24305                }
24306
24307                final PackageParser.Package p = mPackages.get(packageName);
24308                if (p != null && p.childPackages != null) {
24309                    final int N = p.childPackages.size();
24310                    mChildren = new PackageFreezer[N];
24311                    for (int i = 0; i < N; i++) {
24312                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
24313                                userId, killReason);
24314                    }
24315                } else {
24316                    mChildren = null;
24317                }
24318            }
24319            mCloseGuard.open("close");
24320        }
24321
24322        @Override
24323        protected void finalize() throws Throwable {
24324            try {
24325                if (mCloseGuard != null) {
24326                    mCloseGuard.warnIfOpen();
24327                }
24328
24329                close();
24330            } finally {
24331                super.finalize();
24332            }
24333        }
24334
24335        @Override
24336        public void close() {
24337            mCloseGuard.close();
24338            if (mClosed.compareAndSet(false, true)) {
24339                synchronized (mPackages) {
24340                    if (mWeFroze) {
24341                        mFrozenPackages.remove(mPackageName);
24342                    }
24343
24344                    if (mChildren != null) {
24345                        for (PackageFreezer freezer : mChildren) {
24346                            freezer.close();
24347                        }
24348                    }
24349                }
24350            }
24351        }
24352    }
24353
24354    /**
24355     * Verify that given package is currently frozen.
24356     */
24357    private void checkPackageFrozen(String packageName) {
24358        synchronized (mPackages) {
24359            if (!mFrozenPackages.contains(packageName)) {
24360                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24361            }
24362        }
24363    }
24364
24365    @Override
24366    public int movePackage(final String packageName, final String volumeUuid) {
24367        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24368
24369        final int callingUid = Binder.getCallingUid();
24370        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24371        final int moveId = mNextMoveId.getAndIncrement();
24372        mHandler.post(new Runnable() {
24373            @Override
24374            public void run() {
24375                try {
24376                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24377                } catch (PackageManagerException e) {
24378                    Slog.w(TAG, "Failed to move " + packageName, e);
24379                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24380                }
24381            }
24382        });
24383        return moveId;
24384    }
24385
24386    private void movePackageInternal(final String packageName, final String volumeUuid,
24387            final int moveId, final int callingUid, UserHandle user)
24388                    throws PackageManagerException {
24389        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24390        final PackageManager pm = mContext.getPackageManager();
24391
24392        final boolean currentAsec;
24393        final String currentVolumeUuid;
24394        final File codeFile;
24395        final String installerPackageName;
24396        final String packageAbiOverride;
24397        final int appId;
24398        final String seinfo;
24399        final String label;
24400        final int targetSdkVersion;
24401        final PackageFreezer freezer;
24402        final int[] installedUserIds;
24403
24404        // reader
24405        synchronized (mPackages) {
24406            final PackageParser.Package pkg = mPackages.get(packageName);
24407            final PackageSetting ps = mSettings.mPackages.get(packageName);
24408            if (pkg == null
24409                    || ps == null
24410                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24411                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24412            }
24413            if (pkg.applicationInfo.isSystemApp()) {
24414                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24415                        "Cannot move system application");
24416            }
24417
24418            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24419            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24420                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24421            if (isInternalStorage && !allow3rdPartyOnInternal) {
24422                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24423                        "3rd party apps are not allowed on internal storage");
24424            }
24425
24426            if (pkg.applicationInfo.isExternalAsec()) {
24427                currentAsec = true;
24428                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24429            } else if (pkg.applicationInfo.isForwardLocked()) {
24430                currentAsec = true;
24431                currentVolumeUuid = "forward_locked";
24432            } else {
24433                currentAsec = false;
24434                currentVolumeUuid = ps.volumeUuid;
24435
24436                final File probe = new File(pkg.codePath);
24437                final File probeOat = new File(probe, "oat");
24438                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24439                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24440                            "Move only supported for modern cluster style installs");
24441                }
24442            }
24443
24444            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24445                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24446                        "Package already moved to " + volumeUuid);
24447            }
24448            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24449                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24450                        "Device admin cannot be moved");
24451            }
24452
24453            if (mFrozenPackages.contains(packageName)) {
24454                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24455                        "Failed to move already frozen package");
24456            }
24457
24458            codeFile = new File(pkg.codePath);
24459            installerPackageName = ps.installerPackageName;
24460            packageAbiOverride = ps.cpuAbiOverrideString;
24461            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24462            seinfo = pkg.applicationInfo.seInfo;
24463            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24464            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24465            freezer = freezePackage(packageName, "movePackageInternal");
24466            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24467        }
24468
24469        final Bundle extras = new Bundle();
24470        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24471        extras.putString(Intent.EXTRA_TITLE, label);
24472        mMoveCallbacks.notifyCreated(moveId, extras);
24473
24474        int installFlags;
24475        final boolean moveCompleteApp;
24476        final File measurePath;
24477
24478        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24479            installFlags = INSTALL_INTERNAL;
24480            moveCompleteApp = !currentAsec;
24481            measurePath = Environment.getDataAppDirectory(volumeUuid);
24482        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24483            installFlags = INSTALL_EXTERNAL;
24484            moveCompleteApp = false;
24485            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24486        } else {
24487            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24488            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24489                    || !volume.isMountedWritable()) {
24490                freezer.close();
24491                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24492                        "Move location not mounted private volume");
24493            }
24494
24495            Preconditions.checkState(!currentAsec);
24496
24497            installFlags = INSTALL_INTERNAL;
24498            moveCompleteApp = true;
24499            measurePath = Environment.getDataAppDirectory(volumeUuid);
24500        }
24501
24502        // If we're moving app data around, we need all the users unlocked
24503        if (moveCompleteApp) {
24504            for (int userId : installedUserIds) {
24505                if (StorageManager.isFileEncryptedNativeOrEmulated()
24506                        && !StorageManager.isUserKeyUnlocked(userId)) {
24507                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24508                            "User " + userId + " must be unlocked");
24509                }
24510            }
24511        }
24512
24513        final PackageStats stats = new PackageStats(null, -1);
24514        synchronized (mInstaller) {
24515            for (int userId : installedUserIds) {
24516                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24517                    freezer.close();
24518                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24519                            "Failed to measure package size");
24520                }
24521            }
24522        }
24523
24524        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24525                + stats.dataSize);
24526
24527        final long startFreeBytes = measurePath.getUsableSpace();
24528        final long sizeBytes;
24529        if (moveCompleteApp) {
24530            sizeBytes = stats.codeSize + stats.dataSize;
24531        } else {
24532            sizeBytes = stats.codeSize;
24533        }
24534
24535        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24536            freezer.close();
24537            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24538                    "Not enough free space to move");
24539        }
24540
24541        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24542
24543        final CountDownLatch installedLatch = new CountDownLatch(1);
24544        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24545            @Override
24546            public void onUserActionRequired(Intent intent) throws RemoteException {
24547                throw new IllegalStateException();
24548            }
24549
24550            @Override
24551            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24552                    Bundle extras) throws RemoteException {
24553                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24554                        + PackageManager.installStatusToString(returnCode, msg));
24555
24556                installedLatch.countDown();
24557                freezer.close();
24558
24559                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24560                switch (status) {
24561                    case PackageInstaller.STATUS_SUCCESS:
24562                        mMoveCallbacks.notifyStatusChanged(moveId,
24563                                PackageManager.MOVE_SUCCEEDED);
24564                        break;
24565                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24566                        mMoveCallbacks.notifyStatusChanged(moveId,
24567                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24568                        break;
24569                    default:
24570                        mMoveCallbacks.notifyStatusChanged(moveId,
24571                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24572                        break;
24573                }
24574            }
24575        };
24576
24577        final MoveInfo move;
24578        if (moveCompleteApp) {
24579            // Kick off a thread to report progress estimates
24580            new Thread() {
24581                @Override
24582                public void run() {
24583                    while (true) {
24584                        try {
24585                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24586                                break;
24587                            }
24588                        } catch (InterruptedException ignored) {
24589                        }
24590
24591                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24592                        final int progress = 10 + (int) MathUtils.constrain(
24593                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24594                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24595                    }
24596                }
24597            }.start();
24598
24599            final String dataAppName = codeFile.getName();
24600            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24601                    dataAppName, appId, seinfo, targetSdkVersion);
24602        } else {
24603            move = null;
24604        }
24605
24606        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24607
24608        final Message msg = mHandler.obtainMessage(INIT_COPY);
24609        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24610        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24611                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24612                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24613                PackageManager.INSTALL_REASON_UNKNOWN);
24614        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24615        msg.obj = params;
24616
24617        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24618                System.identityHashCode(msg.obj));
24619        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24620                System.identityHashCode(msg.obj));
24621
24622        mHandler.sendMessage(msg);
24623    }
24624
24625    @Override
24626    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24627        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24628
24629        final int realMoveId = mNextMoveId.getAndIncrement();
24630        final Bundle extras = new Bundle();
24631        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24632        mMoveCallbacks.notifyCreated(realMoveId, extras);
24633
24634        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24635            @Override
24636            public void onCreated(int moveId, Bundle extras) {
24637                // Ignored
24638            }
24639
24640            @Override
24641            public void onStatusChanged(int moveId, int status, long estMillis) {
24642                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24643            }
24644        };
24645
24646        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24647        storage.setPrimaryStorageUuid(volumeUuid, callback);
24648        return realMoveId;
24649    }
24650
24651    @Override
24652    public int getMoveStatus(int moveId) {
24653        mContext.enforceCallingOrSelfPermission(
24654                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24655        return mMoveCallbacks.mLastStatus.get(moveId);
24656    }
24657
24658    @Override
24659    public void registerMoveCallback(IPackageMoveObserver callback) {
24660        mContext.enforceCallingOrSelfPermission(
24661                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24662        mMoveCallbacks.register(callback);
24663    }
24664
24665    @Override
24666    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24667        mContext.enforceCallingOrSelfPermission(
24668                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24669        mMoveCallbacks.unregister(callback);
24670    }
24671
24672    @Override
24673    public boolean setInstallLocation(int loc) {
24674        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24675                null);
24676        if (getInstallLocation() == loc) {
24677            return true;
24678        }
24679        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24680                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24681            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24682                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24683            return true;
24684        }
24685        return false;
24686   }
24687
24688    @Override
24689    public int getInstallLocation() {
24690        // allow instant app access
24691        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24692                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24693                PackageHelper.APP_INSTALL_AUTO);
24694    }
24695
24696    /** Called by UserManagerService */
24697    void cleanUpUser(UserManagerService userManager, int userHandle) {
24698        synchronized (mPackages) {
24699            mDirtyUsers.remove(userHandle);
24700            mUserNeedsBadging.delete(userHandle);
24701            mSettings.removeUserLPw(userHandle);
24702            mPendingBroadcasts.remove(userHandle);
24703            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24704            removeUnusedPackagesLPw(userManager, userHandle);
24705        }
24706    }
24707
24708    /**
24709     * We're removing userHandle and would like to remove any downloaded packages
24710     * that are no longer in use by any other user.
24711     * @param userHandle the user being removed
24712     */
24713    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24714        final boolean DEBUG_CLEAN_APKS = false;
24715        int [] users = userManager.getUserIds();
24716        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24717        while (psit.hasNext()) {
24718            PackageSetting ps = psit.next();
24719            if (ps.pkg == null) {
24720                continue;
24721            }
24722            final String packageName = ps.pkg.packageName;
24723            // Skip over if system app
24724            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24725                continue;
24726            }
24727            if (DEBUG_CLEAN_APKS) {
24728                Slog.i(TAG, "Checking package " + packageName);
24729            }
24730            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24731            if (keep) {
24732                if (DEBUG_CLEAN_APKS) {
24733                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24734                }
24735            } else {
24736                for (int i = 0; i < users.length; i++) {
24737                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24738                        keep = true;
24739                        if (DEBUG_CLEAN_APKS) {
24740                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24741                                    + users[i]);
24742                        }
24743                        break;
24744                    }
24745                }
24746            }
24747            if (!keep) {
24748                if (DEBUG_CLEAN_APKS) {
24749                    Slog.i(TAG, "  Removing package " + packageName);
24750                }
24751                mHandler.post(new Runnable() {
24752                    public void run() {
24753                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24754                                userHandle, 0);
24755                    } //end run
24756                });
24757            }
24758        }
24759    }
24760
24761    /** Called by UserManagerService */
24762    void createNewUser(int userId, String[] disallowedPackages) {
24763        synchronized (mInstallLock) {
24764            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24765        }
24766        synchronized (mPackages) {
24767            scheduleWritePackageRestrictionsLocked(userId);
24768            scheduleWritePackageListLocked(userId);
24769            applyFactoryDefaultBrowserLPw(userId);
24770            primeDomainVerificationsLPw(userId);
24771        }
24772    }
24773
24774    void onNewUserCreated(final int userId) {
24775        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24776        // If permission review for legacy apps is required, we represent
24777        // dagerous permissions for such apps as always granted runtime
24778        // permissions to keep per user flag state whether review is needed.
24779        // Hence, if a new user is added we have to propagate dangerous
24780        // permission grants for these legacy apps.
24781        if (mPermissionReviewRequired) {
24782            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24783                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24784        }
24785    }
24786
24787    @Override
24788    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24789        mContext.enforceCallingOrSelfPermission(
24790                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24791                "Only package verification agents can read the verifier device identity");
24792
24793        synchronized (mPackages) {
24794            return mSettings.getVerifierDeviceIdentityLPw();
24795        }
24796    }
24797
24798    @Override
24799    public void setPermissionEnforced(String permission, boolean enforced) {
24800        // TODO: Now that we no longer change GID for storage, this should to away.
24801        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24802                "setPermissionEnforced");
24803        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24804            synchronized (mPackages) {
24805                if (mSettings.mReadExternalStorageEnforced == null
24806                        || mSettings.mReadExternalStorageEnforced != enforced) {
24807                    mSettings.mReadExternalStorageEnforced = enforced;
24808                    mSettings.writeLPr();
24809                }
24810            }
24811            // kill any non-foreground processes so we restart them and
24812            // grant/revoke the GID.
24813            final IActivityManager am = ActivityManager.getService();
24814            if (am != null) {
24815                final long token = Binder.clearCallingIdentity();
24816                try {
24817                    am.killProcessesBelowForeground("setPermissionEnforcement");
24818                } catch (RemoteException e) {
24819                } finally {
24820                    Binder.restoreCallingIdentity(token);
24821                }
24822            }
24823        } else {
24824            throw new IllegalArgumentException("No selective enforcement for " + permission);
24825        }
24826    }
24827
24828    @Override
24829    @Deprecated
24830    public boolean isPermissionEnforced(String permission) {
24831        // allow instant applications
24832        return true;
24833    }
24834
24835    @Override
24836    public boolean isStorageLow() {
24837        // allow instant applications
24838        final long token = Binder.clearCallingIdentity();
24839        try {
24840            final DeviceStorageMonitorInternal
24841                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24842            if (dsm != null) {
24843                return dsm.isMemoryLow();
24844            } else {
24845                return false;
24846            }
24847        } finally {
24848            Binder.restoreCallingIdentity(token);
24849        }
24850    }
24851
24852    @Override
24853    public IPackageInstaller getPackageInstaller() {
24854        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24855            return null;
24856        }
24857        return mInstallerService;
24858    }
24859
24860    private boolean userNeedsBadging(int userId) {
24861        int index = mUserNeedsBadging.indexOfKey(userId);
24862        if (index < 0) {
24863            final UserInfo userInfo;
24864            final long token = Binder.clearCallingIdentity();
24865            try {
24866                userInfo = sUserManager.getUserInfo(userId);
24867            } finally {
24868                Binder.restoreCallingIdentity(token);
24869            }
24870            final boolean b;
24871            if (userInfo != null && userInfo.isManagedProfile()) {
24872                b = true;
24873            } else {
24874                b = false;
24875            }
24876            mUserNeedsBadging.put(userId, b);
24877            return b;
24878        }
24879        return mUserNeedsBadging.valueAt(index);
24880    }
24881
24882    @Override
24883    public KeySet getKeySetByAlias(String packageName, String alias) {
24884        if (packageName == null || alias == null) {
24885            return null;
24886        }
24887        synchronized(mPackages) {
24888            final PackageParser.Package pkg = mPackages.get(packageName);
24889            if (pkg == null) {
24890                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24891                throw new IllegalArgumentException("Unknown package: " + packageName);
24892            }
24893            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24894            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24895                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24896                throw new IllegalArgumentException("Unknown package: " + packageName);
24897            }
24898            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24899            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24900        }
24901    }
24902
24903    @Override
24904    public KeySet getSigningKeySet(String packageName) {
24905        if (packageName == null) {
24906            return null;
24907        }
24908        synchronized(mPackages) {
24909            final int callingUid = Binder.getCallingUid();
24910            final int callingUserId = UserHandle.getUserId(callingUid);
24911            final PackageParser.Package pkg = mPackages.get(packageName);
24912            if (pkg == null) {
24913                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24914                throw new IllegalArgumentException("Unknown package: " + packageName);
24915            }
24916            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24917            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24918                // filter and pretend the package doesn't exist
24919                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24920                        + ", uid:" + callingUid);
24921                throw new IllegalArgumentException("Unknown package: " + packageName);
24922            }
24923            if (pkg.applicationInfo.uid != callingUid
24924                    && Process.SYSTEM_UID != callingUid) {
24925                throw new SecurityException("May not access signing KeySet of other apps.");
24926            }
24927            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24928            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24929        }
24930    }
24931
24932    @Override
24933    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24934        final int callingUid = Binder.getCallingUid();
24935        if (getInstantAppPackageName(callingUid) != null) {
24936            return false;
24937        }
24938        if (packageName == null || ks == null) {
24939            return false;
24940        }
24941        synchronized(mPackages) {
24942            final PackageParser.Package pkg = mPackages.get(packageName);
24943            if (pkg == null
24944                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24945                            UserHandle.getUserId(callingUid))) {
24946                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24947                throw new IllegalArgumentException("Unknown package: " + packageName);
24948            }
24949            IBinder ksh = ks.getToken();
24950            if (ksh instanceof KeySetHandle) {
24951                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24952                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24953            }
24954            return false;
24955        }
24956    }
24957
24958    @Override
24959    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24960        final int callingUid = Binder.getCallingUid();
24961        if (getInstantAppPackageName(callingUid) != null) {
24962            return false;
24963        }
24964        if (packageName == null || ks == null) {
24965            return false;
24966        }
24967        synchronized(mPackages) {
24968            final PackageParser.Package pkg = mPackages.get(packageName);
24969            if (pkg == null
24970                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24971                            UserHandle.getUserId(callingUid))) {
24972                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24973                throw new IllegalArgumentException("Unknown package: " + packageName);
24974            }
24975            IBinder ksh = ks.getToken();
24976            if (ksh instanceof KeySetHandle) {
24977                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24978                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24979            }
24980            return false;
24981        }
24982    }
24983
24984    private void deletePackageIfUnusedLPr(final String packageName) {
24985        PackageSetting ps = mSettings.mPackages.get(packageName);
24986        if (ps == null) {
24987            return;
24988        }
24989        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24990            // TODO Implement atomic delete if package is unused
24991            // It is currently possible that the package will be deleted even if it is installed
24992            // after this method returns.
24993            mHandler.post(new Runnable() {
24994                public void run() {
24995                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24996                            0, PackageManager.DELETE_ALL_USERS);
24997                }
24998            });
24999        }
25000    }
25001
25002    /**
25003     * Check and throw if the given before/after packages would be considered a
25004     * downgrade.
25005     */
25006    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
25007            throws PackageManagerException {
25008        if (after.versionCode < before.mVersionCode) {
25009            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25010                    "Update version code " + after.versionCode + " is older than current "
25011                    + before.mVersionCode);
25012        } else if (after.versionCode == before.mVersionCode) {
25013            if (after.baseRevisionCode < before.baseRevisionCode) {
25014                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25015                        "Update base revision code " + after.baseRevisionCode
25016                        + " is older than current " + before.baseRevisionCode);
25017            }
25018
25019            if (!ArrayUtils.isEmpty(after.splitNames)) {
25020                for (int i = 0; i < after.splitNames.length; i++) {
25021                    final String splitName = after.splitNames[i];
25022                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
25023                    if (j != -1) {
25024                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
25025                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25026                                    "Update split " + splitName + " revision code "
25027                                    + after.splitRevisionCodes[i] + " is older than current "
25028                                    + before.splitRevisionCodes[j]);
25029                        }
25030                    }
25031                }
25032            }
25033        }
25034    }
25035
25036    private static class MoveCallbacks extends Handler {
25037        private static final int MSG_CREATED = 1;
25038        private static final int MSG_STATUS_CHANGED = 2;
25039
25040        private final RemoteCallbackList<IPackageMoveObserver>
25041                mCallbacks = new RemoteCallbackList<>();
25042
25043        private final SparseIntArray mLastStatus = new SparseIntArray();
25044
25045        public MoveCallbacks(Looper looper) {
25046            super(looper);
25047        }
25048
25049        public void register(IPackageMoveObserver callback) {
25050            mCallbacks.register(callback);
25051        }
25052
25053        public void unregister(IPackageMoveObserver callback) {
25054            mCallbacks.unregister(callback);
25055        }
25056
25057        @Override
25058        public void handleMessage(Message msg) {
25059            final SomeArgs args = (SomeArgs) msg.obj;
25060            final int n = mCallbacks.beginBroadcast();
25061            for (int i = 0; i < n; i++) {
25062                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
25063                try {
25064                    invokeCallback(callback, msg.what, args);
25065                } catch (RemoteException ignored) {
25066                }
25067            }
25068            mCallbacks.finishBroadcast();
25069            args.recycle();
25070        }
25071
25072        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
25073                throws RemoteException {
25074            switch (what) {
25075                case MSG_CREATED: {
25076                    callback.onCreated(args.argi1, (Bundle) args.arg2);
25077                    break;
25078                }
25079                case MSG_STATUS_CHANGED: {
25080                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
25081                    break;
25082                }
25083            }
25084        }
25085
25086        private void notifyCreated(int moveId, Bundle extras) {
25087            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
25088
25089            final SomeArgs args = SomeArgs.obtain();
25090            args.argi1 = moveId;
25091            args.arg2 = extras;
25092            obtainMessage(MSG_CREATED, args).sendToTarget();
25093        }
25094
25095        private void notifyStatusChanged(int moveId, int status) {
25096            notifyStatusChanged(moveId, status, -1);
25097        }
25098
25099        private void notifyStatusChanged(int moveId, int status, long estMillis) {
25100            Slog.v(TAG, "Move " + moveId + " status " + status);
25101
25102            final SomeArgs args = SomeArgs.obtain();
25103            args.argi1 = moveId;
25104            args.argi2 = status;
25105            args.arg3 = estMillis;
25106            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
25107
25108            synchronized (mLastStatus) {
25109                mLastStatus.put(moveId, status);
25110            }
25111        }
25112    }
25113
25114    private final static class OnPermissionChangeListeners extends Handler {
25115        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
25116
25117        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
25118                new RemoteCallbackList<>();
25119
25120        public OnPermissionChangeListeners(Looper looper) {
25121            super(looper);
25122        }
25123
25124        @Override
25125        public void handleMessage(Message msg) {
25126            switch (msg.what) {
25127                case MSG_ON_PERMISSIONS_CHANGED: {
25128                    final int uid = msg.arg1;
25129                    handleOnPermissionsChanged(uid);
25130                } break;
25131            }
25132        }
25133
25134        public void addListenerLocked(IOnPermissionsChangeListener listener) {
25135            mPermissionListeners.register(listener);
25136
25137        }
25138
25139        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
25140            mPermissionListeners.unregister(listener);
25141        }
25142
25143        public void onPermissionsChanged(int uid) {
25144            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
25145                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
25146            }
25147        }
25148
25149        private void handleOnPermissionsChanged(int uid) {
25150            final int count = mPermissionListeners.beginBroadcast();
25151            try {
25152                for (int i = 0; i < count; i++) {
25153                    IOnPermissionsChangeListener callback = mPermissionListeners
25154                            .getBroadcastItem(i);
25155                    try {
25156                        callback.onPermissionsChanged(uid);
25157                    } catch (RemoteException e) {
25158                        Log.e(TAG, "Permission listener is dead", e);
25159                    }
25160                }
25161            } finally {
25162                mPermissionListeners.finishBroadcast();
25163            }
25164        }
25165    }
25166
25167    private class PackageManagerNative extends IPackageManagerNative.Stub {
25168        @Override
25169        public String[] getNamesForUids(int[] uids) throws RemoteException {
25170            final String[] results = PackageManagerService.this.getNamesForUids(uids);
25171            // massage results so they can be parsed by the native binder
25172            for (int i = results.length - 1; i >= 0; --i) {
25173                if (results[i] == null) {
25174                    results[i] = "";
25175                }
25176            }
25177            return results;
25178        }
25179
25180        // NB: this differentiates between preloads and sideloads
25181        @Override
25182        public String getInstallerForPackage(String packageName) throws RemoteException {
25183            final String installerName = getInstallerPackageName(packageName);
25184            if (!TextUtils.isEmpty(installerName)) {
25185                return installerName;
25186            }
25187            // differentiate between preload and sideload
25188            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
25189            ApplicationInfo appInfo = getApplicationInfo(packageName,
25190                                    /*flags*/ 0,
25191                                    /*userId*/ callingUser);
25192            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
25193                return "preload";
25194            }
25195            return "";
25196        }
25197
25198        @Override
25199        public int getVersionCodeForPackage(String packageName) throws RemoteException {
25200            try {
25201                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
25202                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
25203                if (pInfo != null) {
25204                    return pInfo.versionCode;
25205                }
25206            } catch (Exception e) {
25207            }
25208            return 0;
25209        }
25210    }
25211
25212    private class PackageManagerInternalImpl extends PackageManagerInternal {
25213        @Override
25214        public void setLocationPackagesProvider(PackagesProvider provider) {
25215            synchronized (mPackages) {
25216                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
25217            }
25218        }
25219
25220        @Override
25221        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
25222            synchronized (mPackages) {
25223                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
25224            }
25225        }
25226
25227        @Override
25228        public void setSmsAppPackagesProvider(PackagesProvider provider) {
25229            synchronized (mPackages) {
25230                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
25231            }
25232        }
25233
25234        @Override
25235        public void setDialerAppPackagesProvider(PackagesProvider provider) {
25236            synchronized (mPackages) {
25237                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
25238            }
25239        }
25240
25241        @Override
25242        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
25243            synchronized (mPackages) {
25244                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
25245            }
25246        }
25247
25248        @Override
25249        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
25250            synchronized (mPackages) {
25251                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
25252            }
25253        }
25254
25255        @Override
25256        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
25257            synchronized (mPackages) {
25258                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
25259                        packageName, userId);
25260            }
25261        }
25262
25263        @Override
25264        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
25265            synchronized (mPackages) {
25266                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
25267                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
25268                        packageName, userId);
25269            }
25270        }
25271
25272        @Override
25273        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
25274            synchronized (mPackages) {
25275                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
25276                        packageName, userId);
25277            }
25278        }
25279
25280        @Override
25281        public void setKeepUninstalledPackages(final List<String> packageList) {
25282            Preconditions.checkNotNull(packageList);
25283            List<String> removedFromList = null;
25284            synchronized (mPackages) {
25285                if (mKeepUninstalledPackages != null) {
25286                    final int packagesCount = mKeepUninstalledPackages.size();
25287                    for (int i = 0; i < packagesCount; i++) {
25288                        String oldPackage = mKeepUninstalledPackages.get(i);
25289                        if (packageList != null && packageList.contains(oldPackage)) {
25290                            continue;
25291                        }
25292                        if (removedFromList == null) {
25293                            removedFromList = new ArrayList<>();
25294                        }
25295                        removedFromList.add(oldPackage);
25296                    }
25297                }
25298                mKeepUninstalledPackages = new ArrayList<>(packageList);
25299                if (removedFromList != null) {
25300                    final int removedCount = removedFromList.size();
25301                    for (int i = 0; i < removedCount; i++) {
25302                        deletePackageIfUnusedLPr(removedFromList.get(i));
25303                    }
25304                }
25305            }
25306        }
25307
25308        @Override
25309        public boolean isPermissionsReviewRequired(String packageName, int userId) {
25310            synchronized (mPackages) {
25311                // If we do not support permission review, done.
25312                if (!mPermissionReviewRequired) {
25313                    return false;
25314                }
25315
25316                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
25317                if (packageSetting == null) {
25318                    return false;
25319                }
25320
25321                // Permission review applies only to apps not supporting the new permission model.
25322                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
25323                    return false;
25324                }
25325
25326                // Legacy apps have the permission and get user consent on launch.
25327                PermissionsState permissionsState = packageSetting.getPermissionsState();
25328                return permissionsState.isPermissionReviewRequired(userId);
25329            }
25330        }
25331
25332        @Override
25333        public PackageInfo getPackageInfo(
25334                String packageName, int flags, int filterCallingUid, int userId) {
25335            return PackageManagerService.this
25336                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
25337                            flags, filterCallingUid, userId);
25338        }
25339
25340        @Override
25341        public ApplicationInfo getApplicationInfo(
25342                String packageName, int flags, int filterCallingUid, int userId) {
25343            return PackageManagerService.this
25344                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
25345        }
25346
25347        @Override
25348        public ActivityInfo getActivityInfo(
25349                ComponentName component, int flags, int filterCallingUid, int userId) {
25350            return PackageManagerService.this
25351                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
25352        }
25353
25354        @Override
25355        public List<ResolveInfo> queryIntentActivities(
25356                Intent intent, int flags, int filterCallingUid, int userId) {
25357            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25358            return PackageManagerService.this
25359                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
25360                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
25361        }
25362
25363        @Override
25364        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
25365                int userId) {
25366            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
25367        }
25368
25369        @Override
25370        public void setDeviceAndProfileOwnerPackages(
25371                int deviceOwnerUserId, String deviceOwnerPackage,
25372                SparseArray<String> profileOwnerPackages) {
25373            mProtectedPackages.setDeviceAndProfileOwnerPackages(
25374                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
25375        }
25376
25377        @Override
25378        public boolean isPackageDataProtected(int userId, String packageName) {
25379            return mProtectedPackages.isPackageDataProtected(userId, packageName);
25380        }
25381
25382        @Override
25383        public boolean isPackageEphemeral(int userId, String packageName) {
25384            synchronized (mPackages) {
25385                final PackageSetting ps = mSettings.mPackages.get(packageName);
25386                return ps != null ? ps.getInstantApp(userId) : false;
25387            }
25388        }
25389
25390        @Override
25391        public boolean wasPackageEverLaunched(String packageName, int userId) {
25392            synchronized (mPackages) {
25393                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25394            }
25395        }
25396
25397        @Override
25398        public void grantRuntimePermission(String packageName, String name, int userId,
25399                boolean overridePolicy) {
25400            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25401                    overridePolicy);
25402        }
25403
25404        @Override
25405        public void revokeRuntimePermission(String packageName, String name, int userId,
25406                boolean overridePolicy) {
25407            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25408                    overridePolicy);
25409        }
25410
25411        @Override
25412        public String getNameForUid(int uid) {
25413            return PackageManagerService.this.getNameForUid(uid);
25414        }
25415
25416        @Override
25417        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25418                Intent origIntent, String resolvedType, String callingPackage,
25419                Bundle verificationBundle, int userId) {
25420            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25421                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25422                    userId);
25423        }
25424
25425        @Override
25426        public void grantEphemeralAccess(int userId, Intent intent,
25427                int targetAppId, int ephemeralAppId) {
25428            synchronized (mPackages) {
25429                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25430                        targetAppId, ephemeralAppId);
25431            }
25432        }
25433
25434        @Override
25435        public boolean isInstantAppInstallerComponent(ComponentName component) {
25436            synchronized (mPackages) {
25437                return mInstantAppInstallerActivity != null
25438                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25439            }
25440        }
25441
25442        @Override
25443        public void pruneInstantApps() {
25444            mInstantAppRegistry.pruneInstantApps();
25445        }
25446
25447        @Override
25448        public String getSetupWizardPackageName() {
25449            return mSetupWizardPackage;
25450        }
25451
25452        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25453            if (policy != null) {
25454                mExternalSourcesPolicy = policy;
25455            }
25456        }
25457
25458        @Override
25459        public boolean isPackagePersistent(String packageName) {
25460            synchronized (mPackages) {
25461                PackageParser.Package pkg = mPackages.get(packageName);
25462                return pkg != null
25463                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25464                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25465                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25466                        : false;
25467            }
25468        }
25469
25470        @Override
25471        public List<PackageInfo> getOverlayPackages(int userId) {
25472            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25473            synchronized (mPackages) {
25474                for (PackageParser.Package p : mPackages.values()) {
25475                    if (p.mOverlayTarget != null) {
25476                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25477                        if (pkg != null) {
25478                            overlayPackages.add(pkg);
25479                        }
25480                    }
25481                }
25482            }
25483            return overlayPackages;
25484        }
25485
25486        @Override
25487        public List<String> getTargetPackageNames(int userId) {
25488            List<String> targetPackages = new ArrayList<>();
25489            synchronized (mPackages) {
25490                for (PackageParser.Package p : mPackages.values()) {
25491                    if (p.mOverlayTarget == null) {
25492                        targetPackages.add(p.packageName);
25493                    }
25494                }
25495            }
25496            return targetPackages;
25497        }
25498
25499        @Override
25500        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25501                @Nullable List<String> overlayPackageNames) {
25502            synchronized (mPackages) {
25503                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25504                    Slog.e(TAG, "failed to find package " + targetPackageName);
25505                    return false;
25506                }
25507                ArrayList<String> overlayPaths = null;
25508                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25509                    final int N = overlayPackageNames.size();
25510                    overlayPaths = new ArrayList<>(N);
25511                    for (int i = 0; i < N; i++) {
25512                        final String packageName = overlayPackageNames.get(i);
25513                        final PackageParser.Package pkg = mPackages.get(packageName);
25514                        if (pkg == null) {
25515                            Slog.e(TAG, "failed to find package " + packageName);
25516                            return false;
25517                        }
25518                        overlayPaths.add(pkg.baseCodePath);
25519                    }
25520                }
25521
25522                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25523                ps.setOverlayPaths(overlayPaths, userId);
25524                return true;
25525            }
25526        }
25527
25528        @Override
25529        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25530                int flags, int userId) {
25531            return resolveIntentInternal(
25532                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25533        }
25534
25535        @Override
25536        public ResolveInfo resolveService(Intent intent, String resolvedType,
25537                int flags, int userId, int callingUid) {
25538            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25539        }
25540
25541        @Override
25542        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25543            synchronized (mPackages) {
25544                mIsolatedOwners.put(isolatedUid, ownerUid);
25545            }
25546        }
25547
25548        @Override
25549        public void removeIsolatedUid(int isolatedUid) {
25550            synchronized (mPackages) {
25551                mIsolatedOwners.delete(isolatedUid);
25552            }
25553        }
25554
25555        @Override
25556        public int getUidTargetSdkVersion(int uid) {
25557            synchronized (mPackages) {
25558                return getUidTargetSdkVersionLockedLPr(uid);
25559            }
25560        }
25561
25562        @Override
25563        public boolean canAccessInstantApps(int callingUid, int userId) {
25564            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25565        }
25566
25567        @Override
25568        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
25569            synchronized (mPackages) {
25570                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
25571            }
25572        }
25573
25574        @Override
25575        public void notifyPackageUse(String packageName, int reason) {
25576            synchronized (mPackages) {
25577                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
25578            }
25579        }
25580    }
25581
25582    @Override
25583    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25584        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25585        synchronized (mPackages) {
25586            final long identity = Binder.clearCallingIdentity();
25587            try {
25588                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25589                        packageNames, userId);
25590            } finally {
25591                Binder.restoreCallingIdentity(identity);
25592            }
25593        }
25594    }
25595
25596    @Override
25597    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25598        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25599        synchronized (mPackages) {
25600            final long identity = Binder.clearCallingIdentity();
25601            try {
25602                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25603                        packageNames, userId);
25604            } finally {
25605                Binder.restoreCallingIdentity(identity);
25606            }
25607        }
25608    }
25609
25610    private static void enforceSystemOrPhoneCaller(String tag) {
25611        int callingUid = Binder.getCallingUid();
25612        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25613            throw new SecurityException(
25614                    "Cannot call " + tag + " from UID " + callingUid);
25615        }
25616    }
25617
25618    boolean isHistoricalPackageUsageAvailable() {
25619        return mPackageUsage.isHistoricalPackageUsageAvailable();
25620    }
25621
25622    /**
25623     * Return a <b>copy</b> of the collection of packages known to the package manager.
25624     * @return A copy of the values of mPackages.
25625     */
25626    Collection<PackageParser.Package> getPackages() {
25627        synchronized (mPackages) {
25628            return new ArrayList<>(mPackages.values());
25629        }
25630    }
25631
25632    /**
25633     * Logs process start information (including base APK hash) to the security log.
25634     * @hide
25635     */
25636    @Override
25637    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25638            String apkFile, int pid) {
25639        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25640            return;
25641        }
25642        if (!SecurityLog.isLoggingEnabled()) {
25643            return;
25644        }
25645        Bundle data = new Bundle();
25646        data.putLong("startTimestamp", System.currentTimeMillis());
25647        data.putString("processName", processName);
25648        data.putInt("uid", uid);
25649        data.putString("seinfo", seinfo);
25650        data.putString("apkFile", apkFile);
25651        data.putInt("pid", pid);
25652        Message msg = mProcessLoggingHandler.obtainMessage(
25653                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25654        msg.setData(data);
25655        mProcessLoggingHandler.sendMessage(msg);
25656    }
25657
25658    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25659        return mCompilerStats.getPackageStats(pkgName);
25660    }
25661
25662    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25663        return getOrCreateCompilerPackageStats(pkg.packageName);
25664    }
25665
25666    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25667        return mCompilerStats.getOrCreatePackageStats(pkgName);
25668    }
25669
25670    public void deleteCompilerPackageStats(String pkgName) {
25671        mCompilerStats.deletePackageStats(pkgName);
25672    }
25673
25674    @Override
25675    public int getInstallReason(String packageName, int userId) {
25676        final int callingUid = Binder.getCallingUid();
25677        enforceCrossUserPermission(callingUid, userId,
25678                true /* requireFullPermission */, false /* checkShell */,
25679                "get install reason");
25680        synchronized (mPackages) {
25681            final PackageSetting ps = mSettings.mPackages.get(packageName);
25682            if (filterAppAccessLPr(ps, callingUid, userId)) {
25683                return PackageManager.INSTALL_REASON_UNKNOWN;
25684            }
25685            if (ps != null) {
25686                return ps.getInstallReason(userId);
25687            }
25688        }
25689        return PackageManager.INSTALL_REASON_UNKNOWN;
25690    }
25691
25692    @Override
25693    public boolean canRequestPackageInstalls(String packageName, int userId) {
25694        return canRequestPackageInstallsInternal(packageName, 0, userId,
25695                true /* throwIfPermNotDeclared*/);
25696    }
25697
25698    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25699            boolean throwIfPermNotDeclared) {
25700        int callingUid = Binder.getCallingUid();
25701        int uid = getPackageUid(packageName, 0, userId);
25702        if (callingUid != uid && callingUid != Process.ROOT_UID
25703                && callingUid != Process.SYSTEM_UID) {
25704            throw new SecurityException(
25705                    "Caller uid " + callingUid + " does not own package " + packageName);
25706        }
25707        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25708        if (info == null) {
25709            return false;
25710        }
25711        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25712            return false;
25713        }
25714        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25715        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25716        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25717            if (throwIfPermNotDeclared) {
25718                throw new SecurityException("Need to declare " + appOpPermission
25719                        + " to call this api");
25720            } else {
25721                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25722                return false;
25723            }
25724        }
25725        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25726            return false;
25727        }
25728        if (mExternalSourcesPolicy != null) {
25729            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25730            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25731                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25732            }
25733        }
25734        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25735    }
25736
25737    @Override
25738    public ComponentName getInstantAppResolverSettingsComponent() {
25739        return mInstantAppResolverSettingsComponent;
25740    }
25741
25742    @Override
25743    public ComponentName getInstantAppInstallerComponent() {
25744        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25745            return null;
25746        }
25747        return mInstantAppInstallerActivity == null
25748                ? null : mInstantAppInstallerActivity.getComponentName();
25749    }
25750
25751    @Override
25752    public String getInstantAppAndroidId(String packageName, int userId) {
25753        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25754                "getInstantAppAndroidId");
25755        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25756                true /* requireFullPermission */, false /* checkShell */,
25757                "getInstantAppAndroidId");
25758        // Make sure the target is an Instant App.
25759        if (!isInstantApp(packageName, userId)) {
25760            return null;
25761        }
25762        synchronized (mPackages) {
25763            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25764        }
25765    }
25766
25767    boolean canHaveOatDir(String packageName) {
25768        synchronized (mPackages) {
25769            PackageParser.Package p = mPackages.get(packageName);
25770            if (p == null) {
25771                return false;
25772            }
25773            return p.canHaveOatDir();
25774        }
25775    }
25776
25777    private String getOatDir(PackageParser.Package pkg) {
25778        if (!pkg.canHaveOatDir()) {
25779            return null;
25780        }
25781        File codePath = new File(pkg.codePath);
25782        if (codePath.isDirectory()) {
25783            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25784        }
25785        return null;
25786    }
25787
25788    void deleteOatArtifactsOfPackage(String packageName) {
25789        final String[] instructionSets;
25790        final List<String> codePaths;
25791        final String oatDir;
25792        final PackageParser.Package pkg;
25793        synchronized (mPackages) {
25794            pkg = mPackages.get(packageName);
25795        }
25796        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25797        codePaths = pkg.getAllCodePaths();
25798        oatDir = getOatDir(pkg);
25799
25800        for (String codePath : codePaths) {
25801            for (String isa : instructionSets) {
25802                try {
25803                    mInstaller.deleteOdex(codePath, isa, oatDir);
25804                } catch (InstallerException e) {
25805                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25806                }
25807            }
25808        }
25809    }
25810
25811    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25812        Set<String> unusedPackages = new HashSet<>();
25813        long currentTimeInMillis = System.currentTimeMillis();
25814        synchronized (mPackages) {
25815            for (PackageParser.Package pkg : mPackages.values()) {
25816                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25817                if (ps == null) {
25818                    continue;
25819                }
25820                PackageDexUsage.PackageUseInfo packageUseInfo =
25821                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25822                if (PackageManagerServiceUtils
25823                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25824                                downgradeTimeThresholdMillis, packageUseInfo,
25825                                pkg.getLatestPackageUseTimeInMills(),
25826                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25827                    unusedPackages.add(pkg.packageName);
25828                }
25829            }
25830        }
25831        return unusedPackages;
25832    }
25833}
25834
25835interface PackageSender {
25836    void sendPackageBroadcast(final String action, final String pkg,
25837        final Bundle extras, final int flags, final String targetPkg,
25838        final IIntentReceiver finishedReceiver, final int[] userIds);
25839    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25840        boolean includeStopped, int appId, int... userIds);
25841}
25842